逻辑回归:针对二分类问题的简单但更高效的算法
逻辑回归是一个分类模型,不是回归模型。
逻辑回归是针对线性可分问题的一种易于实现且性能优异的分类模型。
逻辑回归通过一对多技术可以扩展到多类别分类
几率比:特定事件发生的几率p/(1-p),p为正事件发生的几率。
正事件:我们需要预测的事件
逻辑函数是几率比的对数函数:log p/(1-p)
预测某一样本属于特定类别的概率,是逻辑函数的反函数:Φ(z)=1/(1+e^-z)
使用jupyter notebook
数据集和库文件定义在该章节有定义了,链接:http://mp.blog.csdn.net/postedit/79196206
函数的图像代码:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
z = np.arange(-7, 7, 0.1)
phi_z = sigmoid(z)
plt.plot(z, phi_z)
plt.axvline(0.0, color='k')
plt.ylim(-0.1, 1.1)
plt.xlabel('z')
plt.ylabel('$\phi (z)$')
# y axis ticks and gridline
plt.yticks([0.0, 0.5, 1.0])
ax = plt.gca()
ax.yaxis.grid(True)
plt.tight_layout()
# plt.savefig('./figures/sigmoid.png', dpi=300)
plt.show()
# 绘制损失函数
def cost_1(z):
return - np.log (sigmoid (z))
def cost_0(z):
return - np.log (1 - sigmoid (z))
def PlotCostFunc():
z = np.arange (-10, 10, 0.1)
phi_z = sigmoid (z)
c1 = [cost_1 (x) for x in z]
plt.plot (phi_z, c1, label='J(w) if y=1')
c0 = [cost_0 (x) for x in z]
plt.plot (phi_z, c0, linestyle='--', label='J(w) if y=0')
plt.ylim (0.0, 5.1)
plt.xlim ([0, 1])
plt.xlabel ('$\phi$(z)')
plt.ylabel ('J(w)')
plt.legend (loc='best')
plt.tight_layout ()
# plt.savefig('./figures/log_cost.png', dpi=300)
plt.show ()
PlotCostFunc()
构建逻辑回归模型。
def tLogisticRegression():
lr = LogisticRegression (C=1000.0, random_state=0)
lr.fit (X_train_std, y_train)
plot_decision_regions (X_combined_std, y_combined,
classifier=lr, test_idx=range (105, 150))
plt.xlabel ('花瓣长度 [标准化]')
plt.ylabel ('花瓣宽度 [标准化]')
plt.legend (loc='upper left')
plt.tight_layout ()
# plt.savefig('./figures/logistic_regression.png', dpi=300)
plt.show ()
tLogisticRegression()