机器学习算法-逻辑回归
1.K-近邻算法
(略)
2.线性回归
(略)
3.逻辑回归
3.1逻辑回归介绍
逻辑回归(Logistic Regression)是机器学习中的一种分类模型,逻辑回归是一种分类算法,虽然名字中带有回归,但是它与回归之间有一定的练习。由于算法的简单和高效,在实际中应用非常广泛。
1、逻辑回归的应用场景
-
广告点击率
-
是否为垃圾邮件
-
是否患病
-
金融诈骗
-
虚假账号
2 逻辑回归的原理
2.1输入
$$
h(w)=w_1x_1+w_2x_2+w_3x_3...+b
$$
逻辑回归的输入就是一个线性回归的结果
2.2 激活函数
-
sigmoid函数
$$
g(w^T,x)=\frac{1}{1+e^{-h(w)}}=\frac{1}{1+e^{-w^Tx}}
$$
-
判断标准
-
回归的结果输入到sigmoid函数当中
-
输出结果:[0,1]间的一个概率值,默认为0.5为阈值
-
3 损失以及优化
3.1损失
逻辑回归的损失,称之为对数似然损失,公式如下:
-
分开类别
$$
cost(h_\theta(x),y)=\begin{cases} -log(h_\theta(x)) &if&y=1\\ -log(1-h_\theta(x)) &if&y=0\\ \end{cases}\\ 其中y为真实值,h_\theta(x)为预测值
$$
综合完整损失函数:
$$
cost(h_\theta(x),y)=\sum_{i=1}^{m}-y_ilog(h_\theta(x))-(1-y_i)log(1-h_\theta(x))
$$
3.2优化
同样使用梯度下降优化算法,去减少损失函数的值。这样去更新逻辑回归前面对应算法的权重参数,提升原本属于1类别的概率,降低原本是0类别的概率。
4.小结
3.2逻辑回归api介绍
-
sklearn.linear_model.LogisticRegression(solve='liblinear',penalty='l2',C=1.0)
-
solver可选参数:{'liblinear','sag','saga','newton-cg','libfgs'},
-
默认:'liblinear';用于优化问题的算啊。
-
对于小数据集来说,“liblinear"是个不错的选择,而“sag"和"saga"对于大型数据集会更快。
-
对于多类问题,只有“newton-cg","sag","saga"和"lbfgs"可以处理多项损失,"liblinear"仅限于"one-versus-rest"分类。
-
-
penalty:正则化的种类
-
C:正则化力度
LogisticRegression方法相当于SGDClassifier(loss="log",penalty=""),SGDClassifier实现了一个普通的随即梯度下降学习,而使用LogisticRegression(是实现了SAG)
-
3.3案例:癌症分类预测-良/恶性乳腺癌肿瘤预测
1背景介绍
-
数据介绍
原始数据下载地址:https://archive.ics.uci.edu/ml/machine-learning-databases/(这个不行)
这个数据:https://archive.ics.uci.edu/static/public/15/breast+cancer+wisconsin+original.zip
其他参考:
UCI Machine Learning Repository
UCI Machine Learning Repository
Breast Cancer Wisconsin (Original)
Original Wisconsin Breast Cancer Database
Classification
Multivariate
699 Instances
9 Features
-
数据描述
-
699条样本,共11列数据,第一列用语检索ID,后9列分别是与肿瘤相关的医学特征,最后一列表示肿瘤类型的数值。
-
包含16个缺失值,用“?”标出。
-
2案例分析
1.获取数据 2.基本数据处理 2.1缺失值处理 2.2确定特征值,目标值 2.3分割数据 3.特征工程(标准化) 4.机器学习(逻辑回归) 5.模型评估
3代码实现
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression import ssl from sklearn.utils import column_or_1d ssl._create_default_https_context = ssl._create_unverified_context 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'] # 数据加标题 data = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",names = names) # data = pd.read_csv("D:\\AI\\ML\\data\\breast+cancer+wisconsin+original\\breast-cancer-wisconsin.data2", names = names) # data = pd.read_csv("D:\\AI\\ML\\data\\breast+cancer+wisconsin+original\\breast-cancer-wisconsin.data2") # 2基本数据处理 # 2.1 缺失数据值处理 data = data.replace(to_replace="?", value=np.nan) data=data.dropna() # print(data.head()) # print(data.shape) # 获取第2列到倒数第2列的值 x = data.iloc[:, 1:10] # print(x.head()) # print(x.shape) # 实际值在最后一列 y = data["Class"] # y = data.iloc[:, 10:11] # print(y.head()) # print(y.shape) # print(y.head) # 2.3分割数据 x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=22, test_size=0.25) # 3特征工程(标准化) # x_train 标准化后反而不行了,y_train不能标准化 transfer = StandardScaler() # x_train = transfer.fit_transform(x_train) # y_train=y_train.ravel() # np.array(y_train).reshape(1,-1)[0] # y_train = transfer.fit_transform(y_train) # y = column_or_1d(y_train, warn=True) # y_train = ravel() # print(y) # 4机器学习(逻辑回归) estimator = LogisticRegression() estimator.fit(x_train, y_train) # 5模型评估 # 5.1准确率 ret = estimator.score(x_test, y_test) print("准确率为:\n", ret) # 5.2预测值 y_pre = estimator.predict(x_test) print("预测值为:\n", y_pre)
3.4分类评估方法
1.分类评估方法
1.1 精确率与召回率
1.1.1 混肴矩阵
在分类任务下,预测结果(Predicted Condition)与正确标记(True Condition)之间存在四种不同的组合,构成了混肴矩阵(适用于多分类)
预测结果 | 预测结果 | ||
---|---|---|---|
正例 | 假例 | ||
真实结果 | 正例 | 真正例TP | 伪反例FN |
真实结果 | 假例 | 伪正例FP | 真反例TN |
T-True
F-False
P-positive
N-negative
准确率:(TP+TN)/(TP+FN+FP+TN)
1.1.2 精确率(Precision)与召回率(Recall)
-
精确率:预测结果为正例样本中真实为正例的比例
-
(TP)/(TP+FP)
-
-
召回率:真实为正例的样本中预测结果为正例的比例(查的全,对正样本的区分能力)
-
(TP)/(TP+FN)
-
code
#精确率、召回率指标评估 from sklearn.metrics import classification_report ret= classification_report(y_test,y_pre,labels=(2,4),target_names=("良性","恶性")) print(ret) precision recall f1-score support 良性 0.98 0.98 0.98 111 恶性 0.97 0.97 0.97 60 accuracy 0.98 171 macro avg 0.97 0.97 0.97 171 weighted avg 0.98 0.98 0.98 171
样本不均衡下如何评估
2 ROC曲线与AUC指标
2.1TPR与FPR
-
TPR=TP/(TP+FN)
-
所有真实类别为1的样本中,预测类别为1的比例
-
-
FPR=FP/(FP+TN)
-
所有真实类别为0的样本中,预测类别为1的比例
-
2.2 ROC曲线
2.3 AUC指标
-
AUC的概率意义是随即取一对正负样本,正样本得分大于负样本得分的概率
2.4 AUC计算API
-
from sklearn.metrics import roc_auc_score
-
sklearn.metrics.roc_auc_score(y_true,y_score)
-
计算ROC曲线面积,即AUC值
-
y_true:每个样本的真是类别,必须为0(反例),1(正例)标记
-
y_score:预测得分,可以是正例的估计概率、置信或者分类器的返回值
-
-
code
#5.4 auc指标计算 #0.5~1 之间,越接近于1越好 y_test = np.where(y_test>2.5,1,0) print("AUC指标",roc_auc_score(y_test,y_pre)) #AUC指标 0.9743243243243243
-
AUC只能评价二分类
-
AUC非常适合评价不均衡中的分类器性能
3.5 ROC曲线的绘制
AUC -- Area Under roc Curve,就是ROC曲线的积分,也是ROC曲线下面的面积。
4、数据不平衡数据生成和绘制
代码:
from sklearn.datasets import make_classification import matplotlib.pyplot as plt from collections import Counter #准备类别不均衡数据 X,y = make_classification(n_samples=5000,n_features=2, n_informative=2,n_redundant=0, n_repeated=0,n_classes=3, n_clusters_per_class=1, weights=[0.01,0.05,0.94],random_state=0) print(Counter(y)) plt.scatter(X[:,0],X[:,1],c=y) plt.show()
5、分类中解决不平衡问题
5.1 过采用方法
5.1.1 什么是过采样方法
对训练集里的少数类进行”过采样“(oversampling),即增加一些少数样本使得正、反例树木接近,然后再进行学习。
5.1.2 随机过采样方法
随机过采样是再少数类Smin中随机选择一些样本,然后通过复制所选择的样本集E,将他们添加到Smin中扩大原始数据据集从而得到新的少数类集合Snew-min。 新的数据集Snew-min=Sim+E。
-
通过代码实现随机过采用方法:
#使用imblearn进行随机采用 from imblearn.over_sampling import RandomOverSampler ros=RandomOverSampler(random_state=0) X_resampled,y_resampled=ros.fit_resample(X,y) #查看结果 print(Counter(y_resampled)) #过采样后样本结果 # Counter({2: 4674, 1: 262, 0: 64}) # Counter({2: 4674, 1: 4674, 0: 4674}) #数据集可视化 plt.scatter(X_resampled[:,0],X_resampled[:,1],c=y_resampled) plt.show()