总结常用或不常用但很实用的机器学习库及相关函数

# 分类任务评估 sklearn.metrics.classification_report

sklearn.metrics.classification_report(y_true, y_pred, labels=None, target_names=None, sample_weight=None, digits=2, output_dict=False)

可以报告预测结果的准确率,召回率,F1

重点介绍一下 labelstarget_names 参数:

labels : array, shape = [n_labels]

Optional list of label indices to include in the report.

target_names : list of strings

Optional display names matching the labels (same order).

labels用于指定所有标签所对应的索引坐标,也就是样本空间的label大小

target_names 指标签所对应的标签名

report 函数默认只会检测样本中所包含的标签值,比如下面这个例子,假如样本空间有4个标签c1 - c4,但是某测试集只出现了其中两种,而预测出了3种:

(以下代码在 colab 中提供 点我查看(科学上网))

y_ture = [0, 0, 2, 2, 0]
y_pred = [0, 2 ,1, 2, 0]
# report
report = classification_report(y_true, y_pred)
-----------------------------------------------------
              precision    recall  f1-score   support
           0       1.00      0.67      0.80         3
           1       0.00      0.00      0.00         0
           2       0.50      0.50      0.50         2
   micro avg       0.60      0.60      0.60         5
   macro avg       0.50      0.39      0.43         5
weighted avg       0.80      0.60      0.68         5
1
2
3
4
5
6
7
8
9
10
11
12
13
14

我们会发现 report 只报告了它“看见”的三种标签,而忽略了第四个,因此如果要展示样本空间的所有标签值,需要指定labels:

# labels
labels = [0,1,2,3]
report = classification_report(y_true, y_pred, labels = labels)
print(report)
-------------------------------------------------------
              precision    recall  f1-score   support
           0       1.00      0.67      0.80         3
           1       0.00      0.00      0.00         0
           2       0.50      0.50      0.50         2
           3       0.00      0.00      0.00         0
   micro avg       0.60      0.60      0.60         5
   macro avg       0.38      0.29      0.33         5
weighted avg       0.80      0.60      0.68         5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

target_names 用于指定每个label 的名称,其顺序和大小应与 labels 对应,因此如果要展示所有labels,要配合labels参数使用:

target_names = ["c1", "c2", "c3", "c4"]
# 下面这个会报错,因为函数默认只检测到了3种label,而names含有4个名称
# report = classification_report(y_true, y_pred, target_names = target_names)
# 因此需要配合 labels 使用
report = classification_report(y_true, y_pred, labels = labels, target_names = target_names)
-----------------------------------------------------
              precision    recall  f1-score   support
          c1       1.00      0.67      0.80         3
          c2       0.00      0.00      0.00         0
          c3       0.50      0.50      0.50         2
          c4       0.00      0.00      0.00         0
   micro avg       0.60      0.60      0.60         5
   macro avg       0.38      0.29      0.33         5
weighted avg       0.80      0.60      0.68         5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 训练和测试集样本分割 sklearn.model_selection.train_test_split

这个函数是偶然在一个文档里发现的,sklearn里面的函数实在是太多了,其实很多功能都已经封装好了。

从函数名就可以看出来,这个用于样本训练和测试集的分割,而且函数的输入很万能,list, numpy, scipy, pandas 都有支持。在知道这个函数前我一直都是对 pandas 做 DataFrame.sample() 进行样本分割,然后再取差集得到另一部分,现在看看指的是很智障了。

进入正题,来看看函数能接收的参数:

sklearn.model_selection.train_test_split(arrays, test_size=0.25, train_size=None, random_state=np.random, shuffle=True, stratify = None)

函数的一些细节:

test_sizetrain_size 决定了分割部分,默认4:1,两者可以用小数做比例,也可以是整数直接明确数量,指定了 test_size 后可以不指定 train_size ,反之亦然random_satate 是 随机种子,可以指定 int 或 一个随机种子实例, shuffle 是分割前重排。

无论接收什么值,最后函数都会返回两个 list,需要自己再做类型转换

示例 点我查看(科学上网)

from sklearn.model_selection import train_test_split
import pandas as pd
from pandas import DataFrame as DF
# 数据
datas = [ {"name": "name_%s" % i} for i in range(10)]
df_data = DF(datas)
# 分割
d_train, d_test = train_test_split(datas, test_size = 3) # 默认 shuffle
print("*"*10 + "train:" + "*"*10)
print(d_train)
print(len(d_train), type(d_train))
print("*"*10 + "test:" + "*"*10)
print(d_test)
print(len(d_test), type(d_test))
------------------------------------
**********train:**********
[{'name': 'name_8'}, {'name': 'name_3'}, {'name': 'name_6'}, {'name': 'name_2'}, {'name': 'name_1'}, {'name': 'name_0'}, {'name': 'name_9'}]
7 <class 'list'>
**********test:**********
[{'name': 'name_4'}, {'name': 'name_7'}, {'name': 'name_5'}]
3 <class 'list'>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26