数据预处理:
建模:
from sklearn import datasets
import pandas as pd
import numpy as np
from sklearn import preprocessing
#数据举例
iris = datasets.load_iris()
X, y = iris.data, iris.target
testData = pd.read_csv('C:\\Users\\Load_model\\all_model\\traindata_v2.csv')
testData = testData[:10000]
testData.describe().T
# 有时候需要对数据进行合并, pd.merge pd.concat
#自己生成数据玩一下
playData = pd.DataFrame({
'fillNan1' : [0,1]*10 + [2]*20 + [np.nan]*10,
'date' : pd.date_range('20130101', periods=50),
'continue1' : pd.Series(3,index=list(range(50)),dtype='float32'),
'continue2' : np.array([3,4,5,6,7] * 10,dtype='int32'),
'categorial1' : ["test","train"]*25,
'cateorial2' : ['male','female',np.nan]*15 + ['male','female','female','feamel','male'],
'fillNan2' : list(range(0,45)) + ([np.nan]*5),
'outlier':[-100] + list(range(0,48)) + [200],
'y' :[0,1]*25
}
)
#查看数据类型:
playData.dtypes
#查看分类变量
playData.categorial1.value_counts()
playData.cateorial2.value_counts()
#查看数值型变量
playData.describe()
分箱(binning)
首先排序数据,并将他们分到等深的箱中
然后可以按箱的平均值平滑,按箱中值平滑,按箱的边界值平滑
聚类:检测并且去除孤立点
计算机和人工检查结合:计算机检测可疑数据,然后对他们进行人工判断
数据归约
很多算法都有一个基本假设,那就是数据分布是均匀的
+ 采样:上采样(Oversampling)和下采样(Undersampling)
+ 数据合成:利用已有样本生成更多样本,这类方法在小数据场景下有很多成功案例(SMOTE)
+ 加权:对不同类别分错的代价基于不同的权重
+ 一分类:对于正负样本极不平衡的场景,我们可以换一个完全不同的角度来看待问题:把它看做一分类(One Class Learning)或异常检测(Novelty Detection)问题。这类方法的重点不在于捕捉类间的差别,而是为其中一类进行建模,经典的工作包括One-class SVM等
#二值化
# binarizer = preprocessing.Binarizer(copy=True, threshold=0.0).fit(playData['outlier']) #does nothing
# binarizer.transform(playData['outlier'])
#离散化
# ages = [20, 22, 25, 27, 21, 23, 37, 31, 61, 45, 41, 32]
# bins = [18, 25, 35, 60, 100]
# cats = pd.cut(ages, bins)
# pd.DataFrame([ages,list(cats)]).T
#分类变量数值化
playData['categorial1'] = playData['categorial1'].replace('test',1).replace('train',0)
playData['cateorial2'] = playData['cateorial2'].replace('male',0).replace('feamel','female').replace('female',1)
#分类变量变成新特征值
pd.get_dummies(playData['categorial1'])
pd.get_dummies(playData['cateorial2'])
#上面的变换后与原始值加以区分
dummies = pd.get_dummies(playData['categorial1'], prefix='categorial1')
df_with_dummy = playData[['categorial1']].join(dummies)
df_with_dummy
#缺失值处理
playData['fillNan1'].fillna(playData.fillNan1.mean())
# playData['fillNan1'].fillna(-1)
playData['fillNan2'].fillna(playData.fillNan1.median())
playData = playData.fillna(0)
#异常值处理
# step1:看一下异常值
# import matplotlib.pyplot as plt
# playData['outlier'].hist()
# plt.show()
# step2: 异常值处理 + 数据标准化
# playData.loc[0,'outlier'] = playData.loc[1,'outlier']
# playData.loc[50,'outlier'] = playData.outlier.max()
#数据变换
## 扩充维度
playData = playData.drop('date',axis=1)
ploy = preprocessing.PolynomialFeatures(degree=2, interaction_only=False, include_bias=True).fit(playData)
add_fea_data = pd.DataFrame(ploy.transform(playData))
## 异常值+ 标准化
from sklearn import preprocessing
scale = preprocessing.robust_scale(add_fea_data,quantile_range=(25.0, 75.0))
pd.DataFrame(scale)
#异常值处理举例
#异常值举例
'''
1 生成0~1之间的随机数据;
2 加入一些异常值;
3 用is_outlier()方法检测异常值;
4 绘制出两个数据的集合(x和filtered)的图表,观察他们的区别。
'''
import numpy as np
import matplotlib.pyplot as plt
def is_outlier(points, threshold=3.5):
"""
返回一个布尔型的数组,如果数据点是异常值返回True,反之,返回False。
数据点的值不在阈值范围内将被定义为异常值
阈值默认为3.5
"""
# 转化为向量
if len(points.shape) == 1:
points = points[:,None]
# 数组的中位数
median = np.median(points, axis=0)
# 计算方差
diff = np.sum((points - median)**2, axis=-1)
#标准差
diff = np.sqrt(diff)
# 中位数绝对偏差
med_abs_deviation = np.median(diff)
# compute modified Z-score
# http://www.itl.nist.gov/div898/handbook/eda/section4/eda43.htm#Iglewicz
modified_z_score = 0.6745 * diff / med_abs_deviation
# return a mask for each outlier
return modified_z_score > threshold
# 随机数据(100个在0~1之间的浮点数)
x = np.random.random(100)
# 直方图桶数量
buckets = 50
# 加入一些异常值
x = np.r_[x, -49, 95, 100, -100]
# Keep inlier data points
# "~"操作符被重载为一个逻辑操作符,作用在布尔数组上时为取非操作
filtered = x[~is_outlier(x)]
# 画一个直方图
plt.figure()
plt.subplot(211)
plt.hist(x, buckets)
plt.subplot(212)
plt.hist(filtered, buckets)
plt.xlabel('Cleaned')
plt.show()
from sklearn import preprocessing
#map函数:是一种实现元素级转换以及其他数据清理工作的便捷方式。
playData['cateorial2'].fillna('male').map(str.upper)
# l = [random.randint(0,100) for i in range(10)]
# def sub50(a):
# return a-50
# map(sub50,l)
#apply函数
playData['fillNan2'].apply(lambda x: x/100)
#group by
playData.groupby(['categorial1','cateorial2']).count()
#pd.pivot_table
pd.pivot_table(playData,index=['cateorial2'],columns=['categorial1'],values=['continue2'],aggfunc=np.sum)