导包
from sklearn import datasets#导入数据
# 机器学习sklearn中的datasets模块提供了一些自带的小数据集。
#1、常见的小数据集:
# 鸢尾花:load_iris()
乳腺癌:load_breast_cancer()
手写数字:load_digits()
糖尿病:load_diabetes()
波士顿房价:load_biston()
体能训练:load_linnerud()
图像数据:load_sample_image(name)
from sklearn.linear_model import LogisticRegression
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D#绘制3d
from sklearn.preprocessing import scale,StandardScaler#归一化
1.1 加载数据
np.set_printoptions(suppress=True)
x,y=datasets.load_breast_cancer(return_X_y=True)
x=x[:,:2]#切片前两个特征
#x=scale(x)
#30项特征
display(x.shape,y.shape)
输出:
(569, 2)
(569,)
1.2 建模
model=LogisticRegression()
model.fit(x,y)
model.coef_
输出:
array([[-1.0462619 , -0.21688595]])
1.3 逻辑回归中线方程获取:系数
w1=model.coef_[0,0]
w2=model.coef_[0,1]
b=model.intercept_[0]
print('方程的系数,截距为:',w1,w2,b)
输出:
方程的系数,截距为: -1.0462619024003457 -0.21688595452490766 19.671351031534858
1.4 定义sigmoid函数
def sigmoid(x,w1,w2,b):
z=w1*x[0]+w2*x[1]+b#表示线性方程
return 1/(1+np.exp(-z))
1.5 定义损失函数
def loss_function(x,y,w1,w2,b):
loss=0
for x_i,y_i in zip(x,y):
p=sigmoid(x_i,w1,w2,b)#计算概率
p=np.clip(p,0.000001,0.999999)
loss+=-(y_i*np.log(p)+(1-y_i)*np.log(1-p))
return(loss)
1.6 参数w1和w2范围
w1_space=np.linspace(w1-1.5,w1+1.5,100)
w2_space=np.linspace(w2-1.6,w2+1.6,100)
1.7 损失计算
loss1_=np.array([loss_function(x,y,i,w2,b) for i in w1_space])
loss2_=np.array([loss_function(x,y,w1,i,b) for i in w2_space])
1.8 可视化¶
fig=plt.figure(figsize=(12,9))
plt.subplot(2,2,1)
plt.title('w1')
plt.plot(w1_space,loss1_,color='green')
plt.subplot(2,2,2)
plt.plot(w2_space,loss2_,color='r')
plt.title('w2')
plt.subplot(223)
#等高线(w1和w2同时绘制)
w1_grid,w2_grid=np.meshgrid(w1_space,w2_space)
loss_grid=loss_function(x,y,w1_grid,w2_grid,b)
plt.contour(w1_grid,w2_grid,loss_grid,c='p')
#登高面
plt.subplot(224)
plt.contourf(w1_grid,w2_grid,loss_grid)
1.9 3D可视化
fig2=plt.figure(figsize=(12,9))
ax=Axes3D(fig2)
ax.plot_surface(w1_grid,w2_grid,loss_grid,cmap='rainbow')
plt.xlabel('w1',size=20)
plt.ylabel('w2',size=20)
ax.view_init(30,-30)
输出:
#查看所有颜色重量方法
plt.colormaps()
输出:
['Accent',
'Accent_r',
'Blues',
'Blues_r',
'BrBG',
'BrBG_r',
'BuGn',
'BuGn_r',
'BuPu',
'BuPu_r',
'CMRmap',
'CMRmap_r',
'Dark2',
'Dark2_r',
'GnBu',
'GnBu_r',
'Greens',
'Greens_r',
'Greys',
'Greys_r',
'OrRd',
'OrRd_r',
'Oranges',
'Oranges_r',
'PRGn',
'PRGn_r',
'Paired',
'Paired_r',
'Pastel1',
'Pastel1_r',
'Pastel2',
'Pastel2_r',
'PiYG',
'PiYG_r',
'PuBu',
'PuBuGn',
'PuBuGn_r',
'PuBu_r',
'PuOr',
'PuOr_r',
'PuRd',
'PuRd_r',
'Purples',
'Purples_r',
'RdBu',
'RdBu_r',
'RdGy',
'RdGy_r',
'RdPu',
'RdPu_r',
'RdYlBu',
'RdYlBu_r',
'RdYlGn',
'RdYlGn_r',
'Reds',
'Reds_r',
'Set1',
'Set1_r',
'Set2',
'Set2_r',
'Set3',
'Set3_r',
'Spectral',
'Spectral_r',
'Wistia',
'Wistia_r',
'YlGn',
'YlGnBu',
'YlGnBu_r',
'YlGn_r',
'YlOrBr',
'YlOrBr_r',
'YlOrRd',
'YlOrRd_r',
'afmhot',
'afmhot_r',
'autumn',
'autumn_r',
'binary',
'binary_r',
'bone',
'bone_r',
'brg',
'brg_r',
'bwr',
'bwr_r',
'cividis',
'cividis_r',
'cool',
'cool_r',
'coolwarm',
'coolwarm_r',
'copper',
'copper_r',
'cubehelix',
'cubehelix_r',
'flag',
'flag_r',
'gist_earth',
'gist_earth_r',
'gist_gray',
'gist_gray_r',
'gist_heat',
'gist_heat_r',
'gist_ncar',
'gist_ncar_r',
'gist_rainbow',
'gist_rainbow_r',
'gist_stern',
'gist_stern_r',
'gist_yarg',
'gist_yarg_r',
'gnuplot',
'gnuplot2',
'gnuplot2_r',
'gnuplot_r',
'gray',
'gray_r',
'hot',
'hot_r',
'hsv',
'hsv_r',
'inferno',
'inferno_r',
'jet',
'jet_r',
'magma',
'magma_r',
'nipy_spectral',
'nipy_spectral_r',
'ocean',
'ocean_r',
'pink',
'pink_r',
'plasma',
'plasma_r',
'prism',
'prism_r',
'rainbow',
'rainbow_r',
'seismic',
'seismic_r',
'spring',
'spring_r',
'summer',
'summer_r',
'tab10',
'tab10_r',
'tab20',
'tab20_r',
'tab20b',
'tab20b_r',
'tab20c',
'tab20c_r',
'terrain',
'terrain_r',
'turbo',
'turbo_r',
'twilight',
'twilight_r',
'twilight_shifted',
'twilight_shifted_r',
'viridis',
'viridis_r',
'winter',
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.model_selection import train_test_split
x,y=datasets.load_iris(return_X_y= True)
cond =y !=2
x=x[cond]
y=y[cond]
2.1 加载数据并安装
#将训练数据和测试数据进行拆分,80%训练数据,20%测试数据
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
display(x_train.shape,x_test.shape)
display(y_train.shape,y_test.shape)
输出:
(80, 4)
(20, 4)
(80,)
(20,)
2.2 训练
model=LogisticRegression()
model.fit(x_train,y_train)
y_pred=model.predict(x_test)
print('预测结果是:',y_pred)
print('真实类别是:',y_test)
#概率
proda_=model.predict_proba(x_test)
print('预测概率是:',proda_)
输出:
预测结果是: [0 1 1 1 0 1 1 0 0 0 0 1 0 1 1 0 1 0 1 0]
真实类别是: [0 1 1 1 0 1 1 0 0 0 0 1 0 1 1 0 1 0 1 0]
预测概率是: [[0.97456206 0.02543794]
[0.0778261 0.9221739 ]
[0.02082688 0.97917312]
[0.00717788 0.99282212]
[0.9452395 0.0547605 ]
[0.02184599 0.97815401]
[0.01038339 0.98961661]
[0.99386613 0.00613387]
[0.97750671 0.02249329]
[0.98698777 0.01301223]
[0.96419055 0.03580945]
[0.00393648 0.99606352]
[0.95903557 0.04096443]
[0.00447606 0.99552394]
[0.00850355 0.99149645]
[0.9803306 0.0196694 ]
[0.00761245 0.99238755]
[0.98873177 0.01126823]
[0.02963912 0.97036088]
[0.96295267 0.03704733]]
一些总结知识
# 线性回归方程
b = lr.intercept_
w = lr.coef_
# 逻辑回归函数
def sigmoid(z):
return 1/(1 + np.exp(-z))
# y = 1 概率
z = X_test.dot(w.T) + b
p_1 = sigmoid(z)
# y = 0 概率
p_0 = 1 - p_1
# 最终结果
p = np.concatenate([p_0,p_1],axis = 1)
# **结论:**
# * 通过数据提取与筛选,创建二分类问题
# * 类别的划分,通过概率比较大小完成了