本栏目为本人自学B站各位好心的博主所录视频过程中记录下来的笔记,出处基本来自于B站视频博主以及csdn中各位大佬的解释,我只起到了转载的作用。因来源过于复杂,因此无法标注来源。
1.分类算法-逻辑回归与二分类
1.1 逻辑回归的应用场景
- 广告点击率
- 是否会被点击
- 是否为垃圾邮件
- 是否患病
- 是否为金融诈骗
- 是否为虚假账号
以上均为:正例 / 反例
1.2 逻辑回归的原理
-
线型回归的输出 就是 逻辑回归的输入
-
激活函数
-
sigmoid函数 [0, 1]
1/(1 + e^(-x))
-
分析
- 回归的结果输入到sigmoid函数当中
- 输出结果:[0,1]区间中的一个概率值,默认为0.5为阈值
1.3 逻辑回归API
- sklearn.linear_model.LogisticRegression(solverm=“liblinear” , penalty=‘L2’,C =1.0)
- solver:优化求解方式(默认开源的liblinear库实现,内部使用了坐标轴下降法来迭代优化损失函数)
- sag:根据数据集自动选择,随机平均梯度下降
- penalty:正则化的种类
- C:正则化力度
- solver:优化求解方式(默认开源的liblinear库实现,内部使用了坐标轴下降法来迭代优化损失函数)
默认将类别数量少的当做正例
1.4 案例:癌症分类预测-良/恶性乳腺癌肿瘤预测
流程分析:
- 获取数据
- 数据集划分
- 特征工程:标准化
- 逻辑回归预估器
- 模型评估
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
# 1. 获取数据
data = load_breast_cancer()
# 2. 数据集划分
x_train,x_test,y_train,y_test = train_test_split(data.data,data.target,random_state=10)
# 3. 特征工程:标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
# 4. 逻辑回归预估器
estimator = LogisticRegression()
estimator.fit(x_train,y_train)
# 5.逻辑回归的模型参数:回归系数和偏置
print("回归系数为:\n",estimator.coef_)
print("偏置为:\n",estimator.intercept_)
# 6. 模型评估
# 方法1:直接比对真实值和预测值
y_predict = estimator.predict(x_test)
print("直接比对真实值和预测值:\n", y_test == y_predict)
# 方法2:计算准确率
score = estimator.score(x_test, y_test)
print("准确率为:\n", score)
1.5 分类的评估方法
- 精确率与召回率
- sklearn.metrics.classification_report(y _true. y_pred, labels=[],target_names=None )
- y_true:真实目标值
- y_pred:估计器预测目标值
- labels:指定类别对应的数字
- target_names:目标类别名称
- return:每个类别精确率与召回率
- sklearn.metrics.classification_report(y _true. y_pred, labels=[],target_names=None )
# 查看精确率、召回率、F1-score
report = classification_report(y_test,y_predict,labels=[0,1],target_names=["恶性","良性"])
2.模型保存和加载
- from sklearn.externals import joblib
- 保存:joblib.dump(rf, "test.pkl’)
- 加载: estimator = joblib.load(“'test.pkl”)