基于周志华老师的《机器学习》、上一篇学习笔记以及网络的其他资料,对线性模型的这一部分内容进行一个总结。上接:机器学习:线性模型学习总结(1)。
学习时间:2022.04.18
用于分类:sklearn.linear_model
.LogisticRegression
penalty
正则化方法:默认为“ l 2 l2 l2”。
l1_ratio
:弹性回归参数,[0,1]。确定’ l 2 l2 l2'和 ' l 1 l1 l1'的比率r,仅当是“弹性网”时才使用。默认=None。tol
停止的容差标准:如果不是None,则在连续的epoch (loss > best_loss - tol)时停止训练。默认=1e-4。C
正则强度的倒数:与支持向量机一样,较小的值指定更强的正则化。default=1.0。solver
:用于优化问题的算法。{‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’}, 默认=’lbfgs’。
‘newton-cg’
:也是牛顿法家族的一种,利用损失函数二阶导数矩阵即海森矩阵来迭代优化损失函数。‘lbfgs’
:拟牛顿法的一种,利用损失函数二阶导数矩阵即海森矩阵来迭代优化损失函数。‘liblinear’
:不支持设置 penalty='none'
;L1正则化,多用于二分类。‘sag’
:要求数据进行缩放处理。支持L2正则化。随机平均梯度下降,是梯度下降法的变种。‘saga’
:要求数据进行缩放处理。支持L1、L2和弹性正则化。max_iter
:最大迭代次数,默认=100。multi_class
:分类法类型,默认default=’auto’。
‘auto’
:自动判断。‘ovr’
:每个标签都看做二分类问题。‘multinomial’
:Softmax算法,多分类,即使数据是二分类的,损失最小是多项式损失拟合整个概率分布。(当solver =‘liblinear’ 时, ‘multinomial’ 不可用)。from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
logitReg = LogisticRegression()
params = [
{'penalty': ['l2'], 'C': [0.1, 0.08, 0.12], 'solver': ['lbfgs'],
'max_iter': [1000, 2000], 'multi_class': ['auto', 'multinomial']},
{'penalty': ['l1', 'l2'], 'C': [0.1, 0.08, 0.12], 'solver': ['saga'],
'max_iter': [1000, 2000], 'multi_class': ['auto', 'multinomial']},
{'penalty': ['elasticnet'], 'l1_ratio': [0.1, 0.11, 0.12], 'C': [0.1, 0.08, 0.12], 'solver': ['saga'],
'max_iter': [1000, 2000], 'multi_class': ['auto', 'multinomial']}
] # 根据所要搜索的模型,调整需要搜索的参数
scores = ['accuracy', 'f1']
best_logitReg = GridSearchCV(logitReg, param_grid=params, n_jobs=-1, scoring=scores, refit='f1', error_score='raise')
# 进行网格搜索
best_logitReg.fit(train_x, train_y)
# 将最优模型传入fare_SGD
logitReg = best_logitReg.best_estimator_
logitReg.fit(train_x, train_y)
train_result = logitReg.predict(train_x)
sklearn.metrics
.classification_report
可能涉及的参数:
output_dict=True
,此参数不起作用,返回的数值不作处理。print(classification_report(y_true, y_pred, digits=6))
还是尝试自己构建一个模板,能够批量输出相关的评价指标:
def classification_evaluation(y_true, y_pred):
# 输出准确率
accuracy = accuracy_score(y_true, y_pred)
# 得到混淆矩阵
matrix = confusion_matrix(y_true, y_pred)
# 输出精度:
precision = precision_score(y_true, y_pred)
# 输出宏平均 精确率
macro_precision = metrics.precision_score(y_true, y_pred, average='macro')
# 输出召回率:
recall = recall_score(y_true, y_pred)
# 输出宏平均 召回率
macro_recall = metrics.recall_score(y_true, y_pred, average='macro')
# fl_score
f1 = f1_score(y_true, y_pred)
# 输出宏平均 fl_score
macro_f1 = metrics.f1_score(y_true, y_pred, average='weighted')
# ROC-AUC分数
roc_auc = roc_auc_score(y_true, y_pred)
数据集用的还是Spaceship Titanic的训练集。
import pandas as pd
from Data_processing_by_Pandas import mango_processing
from Classification_Model_evaluation import classification_evaluation
from Classification_Model_evaluation import plot_confusion_matrix
from Classification_Model_evaluation import plot_curve
# 读取数据
train = pd.read_csv('Titanic.csv')
print(train.describe())
train_target = train['Transported']
train_feature_before = train.drop(['PassengerId', 'Cabin', 'Name', 'Transported'], axis=1)
# 进行数据处理
train_feature = mango_processing(train_feature_before)
# 划分训练集与测试集
from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(train_feature, train_target, test_size=0.2, random_state=42)
# 引入网格搜索,找到最优模型
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
logitReg = LogisticRegression()
params = [
{'penalty': ['l2'], 'C': [0.05, 0.08, 0.03], 'solver': ['lbfgs'],
'max_iter': [1000, 800], 'multi_class': ['auto', 'multinomial']},
{'penalty': ['l1'], 'C': [0.05, 0.08, 0.03], 'solver': ['liblinear'],
'max_iter': [1000, 800], 'multi_class': ['auto']},
{'penalty': ['l2'], 'C': [0.05, 0.08, 0.03], 'solver': ['sag'],
'max_iter': [1000, 800], 'multi_class': ['auto', 'multinomial']}
] # 根据所要搜索的模型,调整需要搜索的参数
scores = ['accuracy', 'f1']
best_logitReg = GridSearchCV(logitReg, param_grid=params, n_jobs=-1, scoring=scores, refit='f1', error_score='raise')
# 进行网格搜索
best_logitReg.fit(train_x, train_y)
# 得到相关参数:
print(best_logitReg.best_score_)
print(best_logitReg.best_params_)
# 将最优模型传入模型
logitReg = best_logitReg.best_estimator_
# 训练模型
logitReg.fit(train_x, train_y)
# 模型预测
train_result = logitReg.predict(train_x)
# 应用自己设置的评价函数输出
labels = ['False', 'True']
# 训练集结果评价
plot_confusion_matrix(classification_evaluation(train_y, train_result), labels)
plot_curve(train_y, train_result)
# 测试集结果评价
test_result = logitReg.predict(test_x)
plot_confusion_matrix(classification_evaluation(test_y, test_result), labels)
plot_curve(test_y, test_result)