数据预处理
去处重复数据:
>>> a = pd.DataFrame({'a':[1,1,2], 'b':[1,1,3]})
>>> a
a b
0 1 1
1 1 1
2 2 3
>>> a.drop_duplicates()
a b
0 1 1
2 2 3
缺失值处理
缺失值判断:
>>> df = pd.DataFrame({'A':[0, 1, np.nan], 'B': [4,5,6]})
>>> df
A B
0 0.0 4
1 1.0 5
2 NaN 6
>>> df.isnull().sum() # 查看每列的缺失值个数
A 1
B 0
dtype: int64
缺失值的删除:
>>> df.dropna() # 删除存在NaN的行
A B
0 0.0 4
1 1.0 5
>>> df.dropna(axis=1) # 删除存在NaN的列
B
0 4
1 5
2 6
缺失值填充
对于类别型数据,一般采用填充众数的形式。对于连续型数据,一般采用填充均值,中值或众数。有时直接填充当前特征没有出现的一个值,比如0.
from sklearn.preprocessing import Imputer
import numpy as np
# strategy:mean,median.most_frequent
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
a = [[1, 2], [np.nan, 3], [7, 6]]
a = imp.fit_transform(a)
print(a)
'''
[[1. 2.]
[4. 3.]
[7. 6.]]
'''
类别数据的处理
类标的编码
(1)通过map函数进行映射
>>> df = pd.DataFrame({'feature':[0, 1, 4], 'label': ['A','B','C']})
>>> df
feature label
0 0 A
1 1 B
2 4 C
>>> df['label'] = df['label'].map({'A': 1, 'B': 2, 'C': 3})
>>> df
feature label
0 0 1
1 1 2
2 4 3
(2)通过sklearn中的LabelEncoder可以直接编码,不过只能从0开始,不能自定义它的类标。
>>> df = pd.DataFrame({'feature':[0, 1, 4], 'label': ['A','B','C']})
>>> y = le.fit_transform(df['label'].values) # 编码为整数类型
>>> y
array([0, 1, 2], dtype=int64)
>>> le.inverse_transform(y) # 逆编码
array(['A', 'B', 'C'], dtype=object)
对离散特征进行独热编码(one-hot)[树模型无需进行此项操作]
(1)使用pandas对DataFrame类型的数据进行one-hot
>>> df = pd.DataFrame({'color':[0, 1, 4], 'label': ['A','B','C']})
>>> df
color label
0 0 A
1 1 B
2 4 C
>>> pd.get_dummies(df, columns=['color'])
label color_0 color_1 color_4
0 A 1 0 0
1 B 0 1 0
2 C 0 0 1
(2)使用sklearn中OneHotEncoder对数组进行one-hot
>>> df = pd.DataFrame({'color':[0, 1, 4], 'label': [1,2,3]})
>>> from sklearn.preprocessing import OneHotEncoder
># categorical_feature里面表示要one-hot的列位置
>>> ohe = OneHotEncoder(categorical_feature=[0], sparse=False)
>>> ohe.fit_transform(df.values)
array([[1., 0., 0., 1.],
[0., 1., 0., 2.],
[0., 0., 1., 3.]])
数据分析
多分类评价指标
多分类问题一般采用macro-F1指标去评判分类的结果,等价于所有类别的F1值重要性相同。若类别中样本数量不一样,对于预测错的样本,出现在样本数少的类别就会使得F1值下降很多;反之,对于样本多的类别此时的F1值下降很小。所以我们不能只关注样本的准确率,而是要关注每个类别的F1表现,此时可以采用多分类的混淆矩阵来可视化各个类别的错分样本数量。
可视化混淆矩阵函数:https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import numpy as np
y_true = [2, 0, 2, 2, 0, 1]
y_pred = [0, 0, 2, 2, 0, 2]
cnf_matrix = confusion_matrix(y_true, y_pred)
np.set_printoptions(precision=2)
print(cnf_matrix)
plot_confusion_matrix(cnf_matrix, classes=[1,2,3],
title='Confusion matrix, without normalization')
plt.show()
类别样本分布以及特征分布
用条形图统计各类别样本个数:
fig, ax = plt.subplots()
people = ('Tom', 'Dick', 'Harry')
ax.bar([1, 2, 3], [2, 10, 5], align='center', color='green')
ax.set_xticks([1, 2, 3])
ax.set_xticklabels(people)
ax.set_ylabel('Performance')
ax.set_title('Sample number of Categorical')
plt.show()
统计特征中特征值的分布:
df = pd.DataFrame([[0, 10], [0, 11], [1, 24], [0, 145]],
columns=['gender', 'age'])
# df.groupby('gender').size()为一个特征值和数量的series字典
data = pd.Series(df.groupby('gender').size(), name='gender')
data.plot.pie(subplots=True,labels=['male', 'female',],
colors=['r', 'g', 'b', 'c'], autopct='%.2f%%', figsize=(2, 2))
plt.show()
特征与类别之间的相关性:
pandas中的corr()函数默认为Pearson相关系数。
heatmap函数可见:Matplotlib heatmap函数代码
df = pd.DataFrame([[1, 0, 1], [1, 1, 1], [1, 0, 1],
[2, 1, 2], [3, 0, 2], [4, 1, 2]],
columns=['A', 'B', 'categories'])
fig, ax = plt.subplots()
feature_label = ['A', 'B', 'categories']
im, cbar = heatmap(df.corr(), feature_label, feature_label, ax=ax,
cmap="YlGn", cbarlabel="Correlation")
texts = annotate_heatmap(im, valfmt="{x:.2f} ")
fig.tight_layout()
plt.show()
不同特征值对应的不同类别样本数量绘制
def plot_feature_with_sample_num(features, labels):
fig, ax = plt.subplots(len(features), 1)
for id, feature in enumerate(features):
count = []
f_set = set(list(df[feature]))
for label in labels:
tmp_count = []
for f in f_set:
tmp_count.append\
(df[df.categories == label][df[feature] == f].shape[0])
count.append(tmp_count)
im, cbar = heatmap(np.array(count), labels, f_set, ax=ax[id],
cmap="YlGn", cbarlabel=feature)
texts = annotate_heatmap(im, valfmt="{x: d} ")
fig.tight_layout()
plt.show()
df = pd.DataFrame([[1, 0, 1], [1, 1, 1], [1, 0, 1],
[2, 1, 2], [3, 0, 2], [3, 1, 2]],
columns=['A', 'B', 'categories'])
# ['A', 'B']输入为df中对应的特征名,[1, 2]为类别
# 绘制A特征下不同值与样本类别数量的对应关系
plot_feature_with_sample_num(['A', 'B'], [1, 2])
数据集的迁移学习
在实际比赛中,经常分为初赛和复赛。在复赛阶段,如何使用初赛的数据是一个关键问题。在机器学习中,针对不同阶段的同源数据,通常有直接拼接数据和迁移学习的方法来利用初赛数据。由于初赛和复赛数据极有可能是不同分布的,即使他们是同源的,所以拼接数据极有可能会使得分类效果下降;迁移学习直接对预测概率(或标注)编码为被迁移模型的特征,生成预测概率的模型可以只基于初赛训练集训练或初赛训练集+复赛训练集训练,一般采用后者效果更好。