一、算法简介
1、定义
类型:分类算法
逻辑回归又叫对数几率回归,是一种广义的线性回归分析模型。虽然名字里有回归,但其实是分类模型,常用于二分类。逻辑回归的原理是用逻辑函数把线性回归的结果(-∞,∞)映射到(0,1),从而显示概率。
2、输入输出
逻辑回归算法的输入
逻辑回归算法的输出
逻辑回归输出值为概率值
3、损失
逻辑回归中的损失被称为似然损失
计算损失公式如下(hθ(x)为概率,即为sigmoid函数的输出结果,y为逻辑回归输出的分类结果)
损失
损失尽量小,所以
当y=1时,hθ(x)越大越好
当y=0时,hθ(x)越小越好
此时正确率最高
综合损失函数
二、使用
API
sklearn.linear_model.LogisticRegression(solver='liblinear',penalty=l2,C=1.0)
solver:优化问题算法,可选择’liblinear’、‘sag’、‘saga’、‘newton_cg’、‘lbfgs’
. liblinear:仅能处理二项损失,对小数据集来说是个不错的选择
. sag、saga:随机平均梯度下降,较适合大数据集
. sag、saga、newton_cg、lbfgs均可以处理多项损失,可应用于多分类问题
penalty:正则化种类(L1、L2)
C:正则化力度
2、案例
使用逻辑回归算法预测癌症类型
数据集来源:UCI机器学习数据库
实现:
import numpy as np
import pandas as pd
#标准化
from sklearn.preprocessing import StandardScaler
#数据分割
from sklearn.model_selection import train_test_split
#参数调优
from sklearn.model_selection import GridSearchCV
#逻辑回归
from sklearn.linear_model import LogisticRegression
#保存
import joblib
names=['Sample code number',
'Clump Thickness',
'Uniformity of Cell Size',
'Uniformity of Cell Shape',
'Marginal Adhesion',
'Single Epithelial Cell Size',
'Bare Nuclei',
'Bland Chromatin',
'Normal Nucleoli',
'Mitoses',
'Class']
#清除缺失值
datas=pd.read_csv('./breast-cancer-wisconsin .data',names=names)
datas=datas.replace(to_replace='?',value=np.NAN)
datas=datas.dropna()
#确认特征值与目标值
x=datas.iloc[:,1:-1]
y=datas.iloc[:,10]
#数据分割
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=2,test_size=0.2)
#标准化
transfer=StandardScaler()
x_train=transfer.fit_transform(x_train)
x_test=transfer.transform(x_test)
#参数调优、训练模型
estimator=LogisticRegression(max_iter=10000)
param_grid={'solver':['liblinear', 'newton-cg', 'lbfgs', 'sag', 'saga'],'C':[1,10,20]}
estimator=GridSearchCV(estimator=estimator,param_grid=param_grid,cv=4)
estimator.fit(x_train,y_train)
#结果评估
print('交叉验证最好结果', estimator.best_score_)
print('交叉验证最好估计器', estimator.best_estimator_)
print('每次的结果', estimator.cv_results_)
#保存模型
joblib.dump(estimator.best_estimator_,filename='./breast-cancer-wisconsin.pkl')
三、分类评估方法
1、混淆矩阵
在分类问题中,真实值和预测值的组合有四种,组成了混淆矩阵
2、常用指标
准确率:(TP+TN)/(TP+TN+FP+FN)
精确率:TP/(TP+FP)
召回率(TPR):TP/(TP+FN)
F1-score(反映了模型的稳健性):2TP/(2TP+FN+FP)
3、API
sklearn.metrics.classification_report(y_true, y_pred, labels=None, target_names=None,
sample_weight=None, digits=2, output_dict=False,
zero_division="warn")
常用参数
y_trueL:真实目标值
y_pred:预测目标值
labels=None:指定类别对应的数字
target_names=None:目标类别名称
返回值
return:每个类别精确率(precision)、召回率(recall)、f1-score
以前文预测肿瘤状况的案例为例
ret=classification_report(y_true=y_test,y_pred=estimator.predict(x_test),labels=[2,4],target_names=['良性','恶性'])
print(ret)
输出结果
precision recall f1-score support
良性 0.98 0.95 0.96 83
恶性 0.93 0.96 0.95 54
accuracy 0.96 137
macro avg 0.95 0.96 0.95 137
weighted avg 0.96 0.96 0.96 137
ps:若样本全部为癌症,可能准确率会很高,但这样并不好,这就是样本不均衡对分类评估造成的不良影响,会导致评估失效
4、ROC曲线
当数据分类比例大于4:1时,就认为样本极度不均衡.
FPR
FP/(FP+TN)
ROC曲线
横轴为FPR,纵轴为TPR的坐标系下绘制的曲线
曲线越趋近于TPR轴,说明模型效果越好
ROC曲线绘制实现
(1)构建模型,把模型的概率值从大到小排序
(2)按照概率从大到小计算tpr、fpr,并构建完整模型
(3)计算面积,即为AUC指标
5、AUC指标
. 概率意义为随即取一对正负样本,正样本得分大于负样本得分的概率。
. 范围是[0,1],越靠近1模型效果越好,越接近0.5效果越差,小于0.5则说明模型效果与所需恰好相反。
. AUC=1,完美分类器,在任何阈值下都能完美预测,现实中一般不存在(除非特征值及其明显且相差巨大)。
. 0.5<AUC<1,一般分类器,若阈值设定得当,具有一定的预测价值。
特点:只能用于评判二分类,但非常用于评价样本不均衡的情况。
ps:AUC实质上也是ROC曲线的面积
API
from sklearn.metrics import roc_auc_score
使用(以上文癌症预测为例)
代码
#AUC
from sklearn.metrics import roc_auc_score
print(roc_auc_score(y_true=y_test,y_score=estimator.predict(x_test)))
输出
0.9573850959393128