0%

python学习系列之sklearn

python sklearn库中相关api的使用

1 model_selection

1
from sklearn import model_selection

sklearn.model_selection中的相关api

(1) train_test_split : 矩阵随机划分测试集和训练集合

1
X_train, X_validation, Y_train, Y_validation = train_test_split(X, y, test_size=0.20, random_state=1, shuffle=True)
2
# x_train、X_validation为训练特征文本数据;Y_train, Y_validation 为标签数据
3
#参数
4
# test_size:样本占比,测试集占数据集的比重,如果是整数的话就是样本的数量
5
# random_state :给定random_state后,每次构建的模型是相同的、生成的数据集是相同的、每次的拆分结果也是相同的。
6
# shuffle:是否打乱数据顺序

(2) cross_val_score:交叉验证

以例子说明含义:若将数据集分为10折,做一次交叉验证,实际上它是计算了十次,将每一折都当做一次测试集,其余九折当做训练集,这样循环十次。通过传入的模型,训练十次,最后将十次结果求平均值。将每个数据集都算一次

1
# Spot Check Algorithms
2
models = []
3
models.append(('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))
4
models.append(('LDA', LinearDiscriminantAnalysis()))
5
models.append(('KNN', KNeighborsClassifier()))
6
models.append(('CART', DecisionTreeClassifier()))
7
models.append(('NB', GaussianNB()))
8
models.append(('SVM', SVC(gamma='auto')))
9
# evaluate each model in turn
10
results = []
11
names = []
12
for name, model in models:
13
    print(model)
14
    kfold = StratifiedKFold(n_splits=10, random_state=1)
15
cv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring='accuracy')
16
# model:通常指数据对象 
17
# X_train为数据, Y_train为预测数据
18
# cv:交叉验证生成器或可迭代的次数

(3) StratifiedKFold:

StratifiedKFold用法类似Kfold,但是他是分层采样,确保训练集,测试集中各类别样本**的比例与原始数据集中相同。**

1
kfold = StratifiedKFold(n_splits=10, random_state=1)
2
# n_splits:折叠次数,默认为3,至少为2。
3
# shuffle:是否在每次分割之前打乱顺序。 
4
# random_state:随机种子,在shuffle==True时使用,默认使用np.random。

2 metrics 评价指标函数

1
from sklearn import metrics

(1) confusion_matrix: 混淆矩阵

混淆矩阵的定义:

  • TP(True Positive):将正类预测为正类数,真实为0,预测也为0
  • FN(False Negative):将正类预测为负类数,真实为0,预测为1
  • FP(False Positive):将负类预测为正类数, 真实为1,预测为0
  • TN(True Negative):将负类预测为负类数,真实为1,预测也为1

如果每个类别中的观察数不相等,或者数据集中有两个以上类别,则仅分类精度可能会产生误导。计算混淆矩阵可以使您更好地了解分类模型正确的地方以及产生的错误类型。

1

举例: 宠物店有10只动物,其中:狗:6只、猫:4只,若分类后的混淆矩阵如下:

2

  • 真实值狗的数量(行数量相加)为6=5+1,分类得到狗的数量(列数量相加)为5=5+0;
  • 真实猫的数量为4=0+4,分类得到猫的数量为5=1+4
1
metrics.confusion_matrix(expected, predicted)# expected 期望值,predicted 预测值

(2) accuracy_score:分类正确的百分比

1
metrics.accuracy_score(y_true, y_pred, normalize=True, sample_weight=None)
2
# y_true 实际值, y_pred预测值, normalize返回值要求(True返回正确的样本占比,false返回的是正确分类的样本数量)

(3) classification_report

1
# y_true 实际值, y_pred预测值
2
# labels:分类报告中显示的类标签的索引列表
3
# target_names:显示与labels对应的名称
4
# digits:指定输出格式的精确度
5
metrics.classification_report(y_true, y_pred, labels=None, target_names=None, sample_weight=None, digits=2)

(4) ROC

1
fpr, tpr, thresholds = metrics.roc_curve(y_true,y_score,pos_label=None,sample_weight=None, drop_intermediate=True)

(5) AUC

-------------未完待续-------------