了解常用的机器学习模型,并掌握机器学习模型的建模与调参流程
相关原理 线性回归模型 https://zhuanlan.zhihu.com/p/49480391
决策树模型 https://zhuanlan.zhihu.com/p/65304798
GBDT模型 https://zhuanlan.zhihu.com/p/45145899
XGBoost模型 https://zhuanlan.zhihu.com/p/86816771
LightGBM模型 https://zhuanlan.zhihu.com/p/89360721
教材推荐
读取数据 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 27 28 29 30 31 32 33 34 35 36 37 38 39 # reduce_mem_usage 函数通过调整数据类型,帮助我们减少数据在内存中占用的空间 def reduce_mem_usage(df): """ iterate through all the columns of a dataframe and modify the data type to reduce memory usage. """ start_mem = df.memory_usage().sum() print('Memory usage of dataframe is {:.2f} MB'.format(start_mem)) for col in df.columns: col_type = df[col].dtype if col_type != object: c_min = df[col].min() c_max = df[col].max() if str(col_type)[:3] == 'int': if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max: df[col] = df[col].astype(np.int8) elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max: df[col] = df[col].astype(np.int16) elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max: df[col] = df[col].astype(np.int32) elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max: df[col] = df[col].astype(np.int64) else: if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max: df[col] = df[col].astype(np.float16) elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max: df[col] = df[col].astype(np.float32) else: df[col] = df[col].astype(np.float64) else: df[col] = df[col].astype('category') end_mem = df.memory_usage().sum() print('Memory usage after optimization is: {:.2f} MB'.format(end_mem)) print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem)) return df sample_feature = reduce_mem_usage(pd.read_csv("data_for_tree.csv"))
Memory usage of dataframe is 62099672.00 MB
Memory usage after optimization is: 16520303.00 MB
Decreased by 73.4%
1 2 # 返回 x in sample_feature.columns not include ['price','brand','model','brand'] 的列表 continuous_feature_names = [x for x in sample_feature.columns if x not in ['price','brand','model','brand']]
线性回归 & 五折交叉验证 & 模拟真实业务情况 1 2 3 4 5 6 7 sample_feature = sample_feature.dropna().replace('-', 0).reset_index(drop=True) sample_feature['notRepairedDamage'] = sample_feature['notRepairedDamage'].astype(np.float32) train = sample_feature[continuous_feature_names + ['price']] train_X = train[continuous_feature_names] train_y = train['price'] `
简单建模 1 2 3 4 5 6 7 8 9 10 from sklearn.linear_model import LinearRegression model = LinearRegression(normalize=True) model = model.fit(train_X, train_y) # 查看训练的线性回归模型的截距(intercept)与权重(coef) print('intercept:'+ str(model.intercept_)) print(sorted(dict(zip(continuous_feature_names, model.coef_)).items(), key=lambda x:x[1], reverse=True))
intercept:-110670.68277241504
[('v_6', 3367064.3416418717),
('v_8', 700675.5609398251),
('v_9', 170630.27723215616),
('v_7', 32322.661931980558),
('v_12', 20473.670796988994),
('v_3', 17868.07954151303),
('v_11', 11474.9389967116),
('v_13', 11261.764560019501),
('v_10', 2683.9200906064084),
('gearbox', 881.8225039250154),
('fuelType', 363.9042507216036),
('bodyType', 189.60271012073036),
('city', 44.94975120522736),
('power', 28.553901616752857),
('brand_price_median', 0.5103728134078609),
('brand_price_std', 0.4503634709263256),
('brand_amount', 0.14881120395065583),
('brand_price_max', 0.0031910186703138638),
('SaleID', 5.355989919860593e-05),
('offerType', 4.397239536046982e-06),
('train', 2.7939677238464355e-07),
('seller', -2.873130142688751e-07),
('brand_price_sum', -2.175006868187596e-05),
('name', -0.0002980012713074109),
('used_time', -0.002515894332880479),
('brand_price_average', -0.404904845101148),
('brand_price_min', -2.2467753486888244),
('power_bin', -34.42064411727887),
('v_14', -274.7841180777388),
('kilometer', -372.89752666073025),
('notRepairedDamage', -495.1903844628239),
('v_0', -2045.0549573558887),
('v_5', -11022.98624082137),
('v_4', -15121.731109860013),
('v_2', -26098.29992055148),
('v_1', -45556.18929726381)]
1 2 3 4 5 6 7 8 9 10 11 from matplotlib import pyplot as plt subsample_index = np.random.randint(low=0, high=len(train_y), size=50) #绘制特征v_9的值与标签的散点图,图片发现模型的预测结果(蓝色点)与真实标签(黑色点)的分布差异较大, # 且部分预测值出现了小于0的情况,说明我们的模型存在一些问题 plt.scatter(train_X['v_9'][subsample_index], train_y[subsample_index], color='black') plt.scatter(train_X['v_9'][subsample_index], model.predict(train_X.loc[subsample_index]), color='blue') plt.xlabel('v_9') plt.ylabel('price') plt.legend(['True Price','Predicted Price'],loc='upper right') print('The predicted price is obvious different from true price') plt.show()
1 2 3 4 5 6 7 8 import seaborn as sns print('It is clear to see the price shows a typical exponential distribution') plt.figure(figsize=(15,5)) plt.subplot(1,2,1) sns.distplot(train_y) plt.subplot(1,2,2) sns.distplot(train_y[train_y < np.quantile(train_y, 0.9)]) plt.show()
1 2 3 4 5 6 7 8 9 # 在这里我们对标签进行了 log(x+1) 变换,使标签贴近于正态分布 train_y_ln = np.log(train_y + 1) print('The transformed price seems like normal distribution') plt.figure(figsize=(15,5)) plt.subplot(1,2,1) sns.distplot(train_y_ln) plt.subplot(1,2,2) sns.distplot(train_y_ln[train_y_ln < np.quantile(train_y_ln, 0.9)]) plt.show()
1 2 3 4 model = model.fit(train_X, train_y_ln) print('intercept:'+ str(model.intercept_)) sorted(dict(zip(continuous_feature_names, model.coef_)).items(), key=lambda x:x[1], reverse=True)
intercept:18.750748443060488
[('v_9', 8.052410408822315),
('v_5', 5.764240780403914),
('v_12', 1.618206098241706),
('v_1', 1.479831064546508),
('v_11', 1.166900417358536),
('v_13', 0.9404706327194452),
('v_7', 0.7137281645215736),
('v_3', 0.6837863827349204),
('v_0', 0.00850050520973589),
('power_bin', 0.008497968353528977),
('gearbox', 0.007922378343285602),
('fuelType', 0.006684768936305926),
('bodyType', 0.004523520651791603),
('power', 0.0007161895389359644),
('brand_price_min', 3.334354528992352e-05),
('brand_amount', 2.897880289491835e-06),
('brand_price_median', 1.2571187771074404e-06),
('brand_price_std', 6.659170007178332e-07),
('brand_price_max', 6.194957302457314e-07),
('brand_price_average', 5.999348706659352e-07),
('SaleID', 2.1194159119234957e-08),
('seller', 1.6262902136077173e-10),
('offerType', 1.1036149771825876e-10),
('train', 6.707523425575346e-12),
('brand_price_sum', -1.5126514245669237e-10),
('name', -7.015511195846627e-08),
('used_time', -4.122477016270915e-06),
('city', -0.002218783709616053),
('v_14', -0.004234189820672137),
('kilometer', -0.013835867353556136),
('notRepairedDamage', -0.27027942480393996),
('v_4', -0.8315697362911634),
('v_2', -0.9470821267759207),
('v_10', -1.6261468392032863),
('v_8', -40.34300817115224),
('v_6', -238.79035497319248)]
1 2 3 4 5 6 7 8 #再次进行可视化,发现预测结果与真实值较为接近,且未出现异常状况 plt.scatter(train_X['v_9'][subsample_index], train_y[subsample_index], color='black') plt.scatter(train_X['v_9'][subsample_index], np.exp(model.predict(train_X.loc[subsample_index])), color='blue') plt.xlabel('v_9') plt.ylabel('price') plt.legend(['True Price','Predicted Price'],loc='upper right') print('The predicted price seems normal after np.log transforming') plt.show()
五折交叉验证
在使用训练集对参数进行训练的时候,经常会发现人们通常会将一整个训练集分为三个部分(比如mnist手写训练集)。一般分为:训练集(train_set),评估集(valid_set),测试集(test_set)这三个部分。这其实是为了保证训练效果而特意设置的。其中测试集很好理解,其实就是完全不参与训练的数据,仅仅用来观测测试效果的数>>据。而训练集和评估集则牵涉到下面的知识了。
因为在实际的训练中,训练的结果对于训练集的拟合程度通常还是挺好的(初始条件敏感),但是对于训练集之外的数据的拟合程度通常就不那么令人满意了。因此我们通常并不会把所有的数据集都拿来训练,而是分出一部分来(这一部分不参加训练)对训练集生成的参数进行测试,相对客观的判断这些参数对训练集之外的数据的符合程度。这种思想就称为交叉验证(Cross Validation)
1 2 3 4 5 6 7 8 9 10 ##使用线性回归模型,对未处理标签的特征数据进行五折交叉验证 from sklearn.model_selection import cross_val_score from sklearn.metrics import mean_absolute_error, make_scorer def log_transfer(func): def wrapper(y, yhat): result = func(np.log(y), np.nan_to_num(np.log(yhat))) return result return wrapper scores = cross_val_score(model, X=train_X, y=train_y, verbose=1, cv = 5, scoring=make_scorer(log_transfer(mean_absolute_error)))
[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done 5 out of 5 | elapsed: 0.7s finished
1 print('AVG:', np.mean(scores))
AVG: 1.3658024027748357
1 2 #使用线性回归模型,对处理过标签的特征数据进行五折交叉验证( scores = cross_val_score(model, X=train_X, y=train_y_ln, verbose=1, cv = 5, scoring=make_scorer(mean_absolute_error))
[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done 5 out of 5 | elapsed: 0.8s finished
1 print('AVG:', np.mean(scores))
AVG: 0.19325301753940502
1 2 3 4 scores = pd.DataFrame(scores.reshape(1,-1)) scores.columns = ['cv' + str(x) for x in range(1, 6)] scores.index = ['MAE'] print(scores)
cv1
cv2
cv3
cv4
cv5
MAE
0.190792
0.193758
0.194132
0.191825
0.195758
模拟真实业务情况
但在事实上,由于我们并不具有预知未来的能力,五折交叉验证在某些与时间相关的数据集上反而反映了不真实的情况。通过2018年的二手车价格预测2017年的二手车价格,这显然是不合理的,因此我们还可以采用时间顺序对数据集进行分隔。在本例中,我们选用靠前时间的4/5样本当作训练集,靠后时间的1/5当作验证集,最终结果与五折交叉验证差距不大
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # 采用时间顺序对数据集进行分隔 选用靠前时间的4/5样本当作训练集,靠后时间的1/5当作验证集 import datetime sample_feature = sample_feature.reset_index(drop=True) split_point = len(sample_feature) // 5 * 4 # 取整除 - 返回商的整数部分(向下取整) train = sample_feature.loc[:split_point].dropna() val = sample_feature.loc[split_point:].dropna() train_X = train[continuous_feature_names] train_y_ln = np.log(train['price'] + 1) val_X = val[continuous_feature_names] val_y_ln = np.log(val['price'] + 1) model = model.fit(train_X, train_y_ln) print(mean_absolute_error(val_y_ln, model.predict(val_X)))
0.19577667229471246
绘制学习率曲线与验证曲线 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 27 28 29 30 31 32 33 34 35 36 # 绘制学习率曲线与验证曲线 from sklearn.model_selection import learning_curve, validation_curve def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,n_jobs=1, train_size=np.linspace(.1, 1.0, 5 )): plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel('Training example') plt.ylabel('score') train_sizes, train_scores, test_scores = learning_curve(estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_size, scoring = make_scorer(mean_absolute_error)) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid()#区域 # x:第一个参数表示覆盖的区域,我直接复制为x,表示整个x都覆盖 # 0:表示覆盖的下限 # y:表示覆盖的上限是y这个曲线 # facecolor:覆盖区域的颜色 # alpha:覆盖区域的透明度[0,1],其值越大,表示越不透明 plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color="g") plt.plot(train_sizes, train_scores_mean, 'o-', color='r', label="Training score") plt.plot(train_sizes, test_scores_mean,'o-',color="g", label="Cross-validation score") plt.legend(loc="best") return plt plot_learning_curve(LinearRegression(), 'Liner_model', train_X[:1000], train_y_ln[:1000], ylim=(0.0, 0.5), cv=5, n_jobs=1) plt.show()
多种模型对比 1 2 3 4 5 train = sample_feature[continuous_feature_names + ['price']].dropna() train_X = train[continuous_feature_names] train_y = train['price'] train_y_ln = np.log(train_y + 1)
线性模型 & 嵌入式特征选择
本章节默认,学习者已经了解关于过拟合、模型复杂度、正则化等概念。否则请寻找相关资料或参考如下连接:
用简单易懂的语言描述「过拟合 overfitting」https://www.zhihu.com/question/32246256/answer/55320482 模型复杂度与模型的泛化能力 http://yangyingming.com/article/434/ 正则化的直观理解 https://blog.csdn.net/jinping_shi/article/details/52433975
在过滤式和包裹式特征选择方法中,特征选择过程与学习器训练过程有明显的分别。而嵌入式特征选择在学习器训练过程中自动地进行特征选择。嵌入式选择最常用的是L1正则化与L2正则化。在对线性回归模型加入两种正则化方法后,他们分别变成了Lasso回归与岭(Ridge)回归。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # 线性模型 & 嵌入式特征选择 from sklearn.linear_model import LinearRegression from sklearn.linear_model import Ridge from sklearn.linear_model import Lasso models = [LinearRegression(), Ridge(), Lasso()] result = dict() for model in models: model_name = str(model).split('(')[0] scores = cross_val_score(model, X=train_X, y=train_y_ln, verbose=0, cv = 5, scoring=make_scorer(mean_absolute_error)) result[model_name] = scores print(model_name + ' is finished')
LinearRegression is finished
Ridge is finished
Lasso is finished
1 2 3 4 # 对三种方法的效果对比 result = pd.DataFrame(result) result.index = ['cv' + str(x) for x in range(1, 6)] print(result)
LinearRegression
Ridge
Lasso
cv1
0.190792
0.194832
0.383899
cv2
0.193758
0.197632
0.381893
cv3
0.194132
0.198123
0.384090
cv4
0.191825
0.195670
0.380526
cv5
0.195758
0.199676
0.383611
1 2 3 4 model = LinearRegression().fit(train_X, train_y_ln) print('intercept:'+ str(model.intercept_)) sns.barplot(abs(model.coef_), continuous_feature_names) plt.show()
intercept:18.75072374836874
L2正则化在拟合过程中通常都倾向于让权值尽可能小,最后构造一个所有参数都比较小的模型。因为一般认为参数值小的模型比较简单,能适应不同的数据集,也在一定程度上避免了过拟合现象。可以设想一下对于一个线性回归方程,若参数很大,那么只要数据偏移一点点,就会对结果造成很大的影响;但如果参数足够小,数据偏移得多一点也不会对结果造成什么影响,专业一点的说法是『抗扰动能力强』
1 2 3 4 model = Ridge().fit(train_X, train_y_ln) print('intercept:'+ str(model.intercept_)) sns.barplot(abs(model.coef_), continuous_feature_names) plt.show()
intercept:4.671710763117783
L1正则化有助于生成一个稀疏权值矩阵,进而可以用于特征选择。如下图,我们发现power与userd_time特征非常重要
1 2 3 4 model = Lasso().fit(train_X, train_y_ln) print('intercept:'+ str(model.intercept_)) sns.barplot(abs(model.coef_), continuous_feature_names) plt.show()
intercept:8.672182470075398
除此之外,决策树通过信息熵或GINI指数选择分裂节点时,优先选择的分裂特征也更加重要,这同样是一种特征选择的方法。XGBoost与LightGBM模型中的model_importance指标正是基于此计算的
非线性模型