- 切割训练集和测试集
- 模型创建
- 逻辑回归(线性模型的分类模型)
- 决策树、随机森林(决策树)
- 输出模型预测结果
- 交叉验证
- 混淆矩阵
- 计算二分类中的混淆矩阵
- 计算精确率、召回率以及f-分数
- ROC曲线
sklearn中切割数据集的方法为train_test_split
from sklearn.model_selection import train_test_split
一般先取出X和y后再切割
# X中数据为清理后的数据,无缺失值,并且没有Survived列 X = data y = train['Survived'] # 对数据集进行切割 X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)模型创建 逻辑回归(线性模型的分类模型)
from sklearn.linear_model import LogisticRegression # 默认参数逻辑回归模型 lr = LogisticRegression() # 调整参数的逻辑回归模型 lr2 = LogisticRegression(C=100) # 训练模型 lr.fit(X_train, y_train)决策树、随机森林(决策树)
随机森林其实是决策树集成为了降低决策树过拟合的情况
from sklearn.ensemble import RandomForestClassifier # 默认参数的随机森林分类模型 rfc = RandomForestClassifier() # 调整参数后的随机森林分类模型 rfc2 = RandomForestClassifier(n_estimators=100, max_depth=5) # 训练模型 rfc.fit(X_train, y_train)输出模型预测结果
输出模型预测分类标签:一般监督模型在sklearn里面有个predict能输出预测标签
输出不同分类标签的预测概率:predict_proba可以输出标签概率
# 预测标签 pred = lr.predict(X_train) # 预测标签概率 pred_proba = lr.predict_proba(X_train) 预测标签的概率: 预测标签的概率能知道模型的准确性。交叉验证
10折交叉验证来评估之前的逻辑回归模型 from sklearn.model_selection import cross_val_score lr = LogisticRegression(C=100) scores = cross_val_score(lr, X_train, y_train, cv=10) # k折交叉验证分数 scores k折越多的情况下会带来什么样的影响? 较大的K值的交叉验证结果倾向于更好,也要考虑较大K值的计算开销。混淆矩阵 计算二分类中的混淆矩阵
from sklearn.metrics import confusion_matrix # 训练模型 lr = LogisticRegression(C=100) lr.fit(X_train, y_train) pred = lr.predict(X_train) # 混淆矩阵 confusion_matrix(y_train, pred)计算精确率、召回率以及f-分数
from sklearn.metrics import classification_report # 精确率、召回率以及f1-score print(classification_report(y_train, pred))ROC曲线
ROC曲线下面所包围的面积越大越好
from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(y_test, lr.decision_function(X_test))
plt.plot(fpr, tpr, label="ROC Curve")
plt.xlabel("FPR")
plt.ylabel("TPR (recall)")
# 找到最接近于0的阈值
close_zero = np.argmin(np.abs(thresholds))
plt.plot(fpr[close_zero], tpr[close_zero], 'o', markersize=10, label="threshold zero", fill, c='k', mew=2)
plt.legend(loc=4)



