文章目录
- 1.简单介绍
- 2.优缺点
- 3.模型理解与推导
- 3.1 二分类问题
- 3.2 Sigmod函数
- 函数形式
- 函数图像
- 函数特点
- 3.3 预测模型
- 3.4 模型解释
- 3.5 代价函数
- 4. 代码实现(python)
- 4.1 Demo实践
- 4.2 基于鸢尾花(iris)数据集的逻辑回归分类实践
1.简单介绍
逻辑回归(Logistic Regression,简称LR)虽然带有回归两个字,但它其实是一种分类模型。逻辑回归被广泛应用于各个领域之中,是当下最流行的学习算法之一。
2.优缺点
- 优点:模型简单,模型的可解释性强,易于理解和实现;计算代价不高,速度很快,存储资源低
- 缺点:容易欠拟合,分类精度不高
3.模型理解与推导
3.1 二分类问题
在二分类问题里,我们最终要得到的预测结果是离散的,并且预测结果只有两种情况,即
而线性回归模型的输出结果是连续的,且值域是整个实数集。
为了方便进行分类预测,我们需要一个函数,来帮助我们把线性回归模型的输出结果映射到(0,1)区间内,即得到概率预测值。
下面介绍一下Sigmod函数。
3.2 Sigmod函数
函数形式
函数图像
函数特点
- 容易求导,函数单调递增
- 值域在(0,1)范围内
3.3 预测模型
线性回归的基本方程为:
联立线性回归方程与Sigmod函数得:
最终求得的就是我们所需要的预测模型。
3.4 模型解释
的输出值可以理解为:对一个输入值x,其预测结果为
的概率估计。
即:
- 举例:(假设y = 0是类别0,y = 1是类别1)
- 当
时,可以解释为:输入值x有0.7的概率属于类别1。
同时,因为二分类问题的可能预测结果只有两个,所以我们可以很容易推导出的概率估计:
因此,我们可以把设为阈值:当
时,我们就预测
;当
时,就预测
再来看一下Sigmod函数,可以发现当且仅当时,
,因此,当且仅当
时,
。
同理,当且仅当时,
。
3.5 代价函数
作用:用来拟合模型里的参数。当
取得最小值时,所对应的
即为所求。
形式:
其中:可简化为:
于是有:
求解
4. 代码实现(python)
4.1 Demo实践
- Step1 模型参数查看
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LogisticRegression
x_fearures = np.array([[-1,-2],[-2,-1],[-3,-2],[1,3],[2,1],[3,2]])
y_label = np.array([0,0,0,1,1,1])
lr_clf = LogisticRegression()
lr_clf = lr_clf.fit(x_fearures,y_label)
print(r'the weight of Logistic Regression is:',lr_clf.coef_)
print(r'the intercept of Logistic Regression is:',lr_clf.intercept_)
输出:
- Step2 数据和模型可视化
plt.figure()
plt.scatter(x_fearures[:,0],x_fearures[:,1],c=y_label,s=50)
plt.title(r'DataSet')
#plt.show()
nx = 100
ny = 200
x_min,x_max = plt.xlim()
y_min,y_max = plt.ylim()
x_grid,y_grid = np.meshgrid(np.linspace(x_min,x_max,nx),np.linspace(y_min,y_max,ny))
z_proba = lr_clf.predict_proba(np.c_[x_grid.ravel(),y_grid.ravel()])
z_proba = z_proba[:,1].reshape(x_grid.shape)
plt.contour(x_grid,y_grid,z_proba,[0.5])
plt.show()
输出:
- Step3 可视化预测新样本
### 可视化预测新样本
plt.figure()
## new point 1
x_fearures_new1 = np.array([[0, -1]])
plt.scatter(x_fearures_new1[:,0],x_fearures_new1[:,1], s=50, cmap='viridis')
plt.annotate(s='New point 1',xy=(0,-1),xytext=
(-2,0),color='blue',arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red'))
## new point 2
x_fearures_new2 = np.array([[1, 2]])
plt.scatter(x_fearures_new2[:,0],x_fearures_new2[:,1], s=50, cmap='viridis')
plt.annotate(s='New point 2',xy=(1,2),xytext=
(-1.5,2.5),color='red',arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red'))
## 训练样本
plt.scatter(x_fearures[:,0],x_fearures[:,1], c=y_label, s=50, cmap='viridis')
plt.title('Dataset')
# 可视化决策边界
plt.contour(x_grid, y_grid, z_proba, [0.5], linewidths=2., colors='blue')
plt.show()
输出结果:
- Step4 模型预测
## 在训练集和测试集上分布利用训练好的模型进行预测
y_label_new1_predict = lr_clf.predict(x_fearures_new1)
y_label_new2_predict = lr_clf.predict(x_fearures_new2)
print('The New point 1 predict class:\n',y_label_new1_predict)
print('The New point 2 predict class:\n',y_label_new2_predict)
## 由于逻辑回归模型是概率预测模型(前文介绍的 p = p(y=1|x,\theta)),所有我们可以利用predict_proba 函数预测其概率
y_label_new1_predict_proba = lr_clf.predict_proba(x_fearures_new1)
y_label_new2_predict_proba = lr_clf.predict_proba(x_fearures_new2)
print('The New point 1 predict Probability of each class:\n',y_label_new1_predict_proba)
print('The New point 2 predict Probability of each class:\n',y_label_new2_predict_proba)
输出结果:
4.2 基于鸢尾花(iris)数据集的逻辑回归分类实践
- Step1 数据简单查看
## 基础函数库
import numpy as np
import pandas as pd
## 绘图函数库
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import load_iris
data = load_iris() #得到数据特征
iris_target = data.target #得到数据对应的标签
iris_features = pd.DataFrame(data=data.data, columns=data.feature_names) #利用Pandas转化为DataFrame格式
iris_features.head()
#iris_features.tail()
输出结果:
- Step2 可视化描述
## 合并标签和特征信息
iris_all = iris_features.copy() ##进行浅拷贝,防止对于原始数据的修改
iris_all['target'] = iris_target
## 特征与标签组合的散点可视化
sns.pairplot(data=iris_all,diag_kind='hist', hue= 'target')
plt.show()
输出结果:
- Step3 利用逻辑回归模型进行分类预测
## 为了正确评估模型性能,将数据划分为训练集和测试集,并在训练集上训练模型,在测试集上验证模型性能。
from sklearn.model_selection import train_test_split
## 选择其类别为0和1的样本 (不包括类别为2的样本)
iris_features_part = iris_features.iloc[:100]
iris_target_part = iris_target[:100]
## 测试集大小为20%, 80%/20%分
x_train, x_test, y_train, y_test = train_test_split(iris_features_part, iris_target_part,
test_size = 0.2, random_state = 2020)
## 从sklearn中导入逻辑回归模型
from sklearn.linear_model import LogisticRegression
## 定义 逻辑回归模型
clf = LogisticRegression(random_state=0, solver='lbfgs')
# 在训练集上训练逻辑回归模型
clf.fit(x_train, y_train)
## 在训练集和测试集上分布利用训练好的模型进行预测
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
from sklearn import metrics
## 利用accuracy(准确度)【预测正确的样本数目占总预测样本数目的比例】评估模型效果
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))
# 利用热力图对于结果进行可视化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()
输出结果: