1.若使用树型或线性模型,特征构造时多使用× and /
2.在使用线性模型时可能会出现下列错误:
ValueError: Input contains NaN, infinity or a value too large for dtype('float64').
- 检查是否含有空值,inf(无穷),数值溢出
np.any(np.isnan(mat))
np.all(np.isfinite(mat))
-
解决:
-
数据输入模型前,填充空值,一般使用df.fillna(df.mean())。
-
对可能造成无穷大的除法,重新构造函数。A+A.mean()//B+B.mean() or np.aqrt(A+1)/np.sqrt(B)
3.pd.DataFrame中columns参数必须带 [ ]
result = pd.DataFrame({'Id': X_test.Id, 'SalePrice': pred}, columns=['Id', 'SalePrice'])
4.缩放
- 01缩放
###x^=x−xminxmax−xmin\hat x=\frac{x-x_{min}}{x_{max}-x_{min}}x^=xmax−xminx−xmin
min_max_scaler = preprocessing.MinMaxScaler()
X_train_minmax = min_max_scaler.fit_transform(X_train)
- Z-Score标准化
###x^=x−μσ\hat x=\frac{x-\mu}{\sigma}x^=σx−μ
μ 所有样本数据的均值,σ为所有样本数据的标准差
scaler = preprocessing.StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
5. one-hot编码
将分类变量(categorical variable)转换为“哑变量矩阵”(dummy matrix)
X_train = pd.get_dummies(X_train)
a = [1, 2, 3, 1]
one_hot = pd.get_dummies(a)
>>>
1 2 3
0 1 0 0
1 0 1 0
2 0 0 1
3 1 0 0
6.字符分类转数值分类
class_map = {label: idx for idx, label in enumerate(set(data['购买产品']))}
data['购买产品'] = data['购买产品'].map(class_map)
# 也可以自定义class_map = {'A': 1, 'B': 2}
7.协方差与相关系数
Series 有两个方法可以计算协方差与相关系数,方法的主要参数都是另一个 Series。DataFrame 的这两个方法会对列进行两两运算,并返回一个 len(columns) 大小的方阵:
# 相关系数,默认皮尔森
.corr(other, method='pearson', min_periods=1)
# 协方差
.cov(other, min_periods=None)
min_periods 参数为样本量的下限,低于此值的不进行运算。
8.groupby()为并行计算,建议使用此方法
temp = data.groupby(['Id'])
temp['discount'].min()
temp['discount'].max()
temp['discount'].mean()
temp['discount'].var()
temp['discount'].std()
ice_candy = temp['冰糖度'].apply(lambda x: [xxx for xx in x for xxx in xx.split('|')])
# temp 是groupby格式,temp['冰糖度']提取其中一列也是groupby格式,groupby格式循环时,每次循环一个 关键字(此为一个Id),将关键字下的冰糖度,压缩成写成了列表。ice_candy为Series格式,类似字典通过下关键字取值,ice_candy[Id]可得到 这个Id的ice_candy 列表