做免费外贸网站,申请账号注册,仓库出入库管理系统,网站建设 上美天空文章目录 目标步骤1. 调整数据类型#xff0c;减少数据在内存中占用的空间2. 使用线性回归来简单建模3. 五折交叉验证4. 模拟真实业务情况5. 绘制学习率曲线与验证曲线6. 嵌入式特征选择6. 非线性模型7. 模型调参#xff08;1#xff09; 贪心调参#xff08;2#xff09;… 文章目录 目标步骤1. 调整数据类型减少数据在内存中占用的空间2. 使用线性回归来简单建模3. 五折交叉验证4. 模拟真实业务情况5. 绘制学习率曲线与验证曲线6. 嵌入式特征选择6. 非线性模型7. 模型调参1 贪心调参2Grid Search 调参3贝叶斯调参 总结 本文数据集来自阿里天池https://tianchi.aliyun.com/competition/entrance/231784/information 主要参考了Datawhale的整个操作流程https://tianchi.aliyun.com/notebook/95460 小编也是第一次接触数据挖掘所以先跟着Datawhale写的教程操作了一遍不懂的地方加了一点点自己的理解感谢Datawhale 目标
了解常用的机器学习模型并掌握机器学习模型的建模与调参流程
步骤
1. 调整数据类型减少数据在内存中占用的空间
具体方法定义如下 对每一列循环将每一列的转化为对应的数据类型在不损失数据的情况下尽可能地减少DataFrame中每列的内存占用
def reduce_mem_usage(df): iterate through all the columns of a dataframe and modify the data typeto reduce memory usage. start_mem df.memory_usage().sum() # 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:# np.int8 是 NumPy 中表示 8 位整数的数据类型。# np.iinfo(np.int8) 返回一个描述 np.int8 数据类型的信息对象。# .min 是该信息对象的一个属性用于获取该数据类型的最小值。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调用上述函数查看效果 其中data_for_tree.csv保存的是我们在特征工程步骤中简单处理过的特征
sample_feature reduce_mem_usage(pd.read_csv(data_for_tree.csv))2. 使用线性回归来简单建模
因为上述特征当时是为树模型分析保存的所以没有对空值进行处理这里简单处理一下
sample_feature.head()可以看到notRepairedDamage这一列有异常值‘-’
sample_feature sample_feature.dropna().replace(-, 0).reset_index(dropTrue)
sample_feature[notRepairedDamage] sample_feature[notRepairedDamage].astype(np.float32)建立训练数据和标签
train_X sample_feature.drop(price,axis1)
train_y sample_feature[price]简单建模
from sklearn.linear_model import LinearRegression
model LinearRegression()
model model.fit(train_X, train_y)
intercept: str(model.intercept_) # 这一行代码用于输出模型的截距即常数项
sorted(dict(zip(sample_feature.columns, model.coef_)).items(), keylambda x:x[1], reverseTrue) # 这行代码是用于输出模型的系数并按照系数的大小进行排序
# sample_feature.columns 是特征的列名。
# model.coef_ 是线性回归模型的系数。
# zip(sample_feature.columns, model.coef_) 将特征列名与对应的系数打包成元组。
# dict(...) 将打包好的元组转换为字典。
# sorted(..., keylambda x:x[1], reverseTrue) 对字典按照值系数进行降序排序。画图查看真实值与预测值之间的差距
from matplotlib import pyplot as plt
subsample_index np.random.randint(low0, highlen(train_y), size50) # 从训练数据中随机选择 50 个样本的索引
plt.scatter(train_X[v_9][subsample_index], train_y[subsample_index], colorblack) # 绘制真实价格与特征 v_9 之间的散点图
plt.scatter(train_X[v_9][subsample_index], model.predict(train_X.loc[subsample_index]), colorblue) # 绘制模型预测价格与特征 v_9 之间的散点图
plt.xlabel(v_9)
plt.ylabel(price)
plt.legend([True Price,Predicted Price],locupper right)
print(The predicted price is obvious different from true price)
plt.show()通过作图我们发现数据的标签price呈现长尾分布不利于我们的建模预测。 对标签进行进一步分析 画图显示标签的分布左边是所有标签数据的一个分布右边是去掉最大的10%标签数据之后的一个分布
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) # 创建一个包含 1 行 2 列的子图并将当前子图设置为第一个子图
sns.distplot(train_y) # 显示价格数据的直方图以及拟合的密度曲线
plt.subplot(1,2,2)
# quantile 函数来计算价格数据的第 90%分位数然后通过布尔索引选取低于第 90 百分位数的价格数据
sns.distplot(train_y[train_y np.quantile(train_y, 0.9)])对标签进行 log(x1) 变换使标签贴近于正态分布
train_y_ln np.log(train_y 1)显示log变化之后的数据分布
import seaborn as sns
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)])然后我们重新训练再可视化
model model.fit(train_X, train_y_ln)
print(intercept: str(model.intercept_))
sorted(dict(zip(continuous_feature_names, model.coef_)).items(), keylambda x:x[1], reverseTrue)
plt.scatter(train_X[v_9][subsample_index], train_y[subsample_index], colorblack)
plt.scatter(train_X[v_9][subsample_index], np.exp(model.predict(train_X.loc[subsample_index])), colorblue)
plt.xlabel(v_9)
plt.ylabel(price)
plt.legend([True Price,Predicted Price],locupper right)
print(The predicted price seems normal after np.log transforming)
plt.show()可以看出结果要比上面的好一点
3. 五折交叉验证 在使用训练集对参数进行训练的时候一般会将整个训练集分为三个部分训练集train_set评估集valid_set测试集test_set这三个部分。这其实是为了保证训练效果而特意设置的。 测试集很好理解其实就是完全不参与训练的数据仅仅用来观测测试效果的数据。在实际的训练中训练的结果对于训练集的拟合程度通常还是挺好的初始条件敏感但是对于训练集之外的数据的拟合程度通常就不那么令人满意了。因此我们通常并不会把所有的数据集都拿来训练而是分出一部分来这一部分不参加训练对训练集生成的参数进行测试相对客观的判断这些参数对训练集之外的数据的符合程度。这种思想就称为交叉验证Cross Validation 1使用线性回归模型对未处理标签的特征数据进行五折交叉验证
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):# np.nan_to_num 函数用于将对数转换后可能出现的 NaN 值转换为 0result func(np.log(y), np.nan_to_num(np.log(yhat)))return result# 返回内部函数 wrapper这是一个对原始函数的包装器它将对传入的参数进行对数转换后再调用原始函数return wrapper
# 计算5折交叉验证得分
scores cross_val_score(model, Xtrain_X, ytrain_y, verbose1, cv 5, scoringmake_scorer(log_transfer(mean_absolute_error)))
# model 是要评估的模型对象。
# train_X 是训练数据的特征train_y 是训练数据的目标变量。
# verbose1 设置为 1 时表示打印详细信息。
# cv5 表示进行 5 折交叉验证。
# scoringmake_scorer(log_transfer(mean_absolute_error)) 指定了评分标准
# 使用了 make_scorer 函数将一个自定义的评分函数 log_transfer(mean_absolute_error) 转换为一个可用于评分的评估器。
# log_transfer(mean_absolute_error) 这一步的作用就是将真实值和预测值在输入到mean_absolute_error之前进行log转换
# mean_absolute_error 是一个回归问题中常用的评估指标用于衡量预测值与实际值之间的平均绝对误差
print(AVG:, np.mean(scores))结果展示 使用线性回归模型对处理过标签的特征数据进行五折交叉验证
scores cross_val_score(model, Xtrain_X, ytrain_y_ln, verbose1, cv 5, scoringmake_scorer(mean_absolute_error))
print(AVG:, np.mean(scores))结果展示 可以看见调整之后的数据误差明显变小 查看scores
scores pd.DataFrame(scores.reshape(1,-1))
scores.columns [cv str(x) for x in range(1, 6)]
scores.index [MAE]
scores4. 模拟真实业务情况
交叉验证在某些与时间相关的数据集上可能反映了不真实的情况比如我们不能通过2018年的二手车价格来预测2017年的二手车价格。这个时候我们可以采用时间顺序对数据集进行分隔。在本例中我们可以选用靠前时间的4/5样本当作训练集靠后时间的1/5当作验证集 具体操作如下
import datetime
sample_feature sample_feature.reset_index(dropTrue)
split_point len(sample_feature) // 5 * 4
train sample_feature.loc[:split_point].dropna()
val sample_feature.loc[split_point:].dropna()
train_X train.drop(price,axis1)
train_y_ln np.log(train[price] 1)
val_X val.drop(price,axis1)
val_y_ln np.log(val[price] 1)
model model.fit(train_X, train_y_ln)
mean_absolute_error(val_y_ln, model.predict(val_X))结果展示
5. 绘制学习率曲线与验证曲线
def plot_learning_curve(estimator, title, X, y, ylimNone, cvNone,n_jobs1, train_sizenp.linspace(.1, 1.0, 5 )): 模型估计器 estimator图的标题 title特征数据 X目标数据 yy轴的范围 ylim交叉验证分割策略 cv并行运行的作业数 n_jobs 训练样本的大小 train_sizeplt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) # 设置 y 轴的范围为 ylimplt.xlabel(Training example) plt.ylabel(score) # 使用 learning_curve 函数计算学习曲线的训练集得分和交叉验证集得分train_sizes, train_scores, test_scores learning_curve(estimator, X, y, cvcv, n_jobsn_jobs, train_sizestrain_size, scoring make_scorer(mean_absolute_error)) train_scores_mean np.mean(train_scores, axis1) # 计算训练集得分的均值train_scores_std np.std(train_scores, axis1) # 计算训练集得分的标准差test_scores_mean np.mean(test_scores, axis1) test_scores_std np.std(test_scores, axis1) plt.grid()#区域 # 使用红色填充训练集得分的方差范围plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean train_scores_std, alpha0.1, colorr) # 使用绿色填充交叉验证集得分的方差范围plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean test_scores_std, alpha0.1, colorg) # 绘制训练集得分曲线plt.plot(train_sizes, train_scores_mean, o-, colorr, labelTraining score) # 绘制交叉验证集得分曲线plt.plot(train_sizes, test_scores_mean,o-,colorg, labelCross-validation score) plt.legend(locbest) return plt
plot_learning_curve(LinearRegression(), Liner_model, train_X[:1000], train_y_ln[:1000], ylim(0.0, 0.5), cv5, n_jobs1) 6. 嵌入式特征选择 在过滤式和包裹式特征选择方法中特征选择过程与学习器训练过程有明显的分别。而嵌入式特征选择在学习器训练过程中自动地进行特征选择。嵌入式选择最常用的是L1正则化与L2正则化。在对线性回归模型加入两种正则化方法后他们分别变成了岭回归与Lasso回归 对上述三种模型进行交叉验证训练并对比结果
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)[:-2] # 获取模型名称# 训练模型scores cross_val_score(model, Xtrain_X, ytrain_y_ln, verbose0, cv 5, scoringmake_scorer(mean_absolute_error))# 收集各模型训练得分result[model_name] scoresprint(model_name is finished)
result pd.DataFrame(result)
result.index [cv str(x) for x in range(1, 6)]
result结果展示 分别对三个模型训练得到的参数进行分析
一般线性回归
import seaborn as sns
model LinearRegression().fit(train_X, train_y_ln)
print(intercept:, model.intercept_)
# 组合数据
data pd.DataFrame({coef_abs: abs(model.coef_), feature: train_X.columns})
# 画图
sns.barplot(xcoef_abs, yfeature, datadata)展示
岭回归 L2正则化在拟合过程中通常都倾向于让权值尽可能小最后构造一个所有参数都比较小的模型。因为一般认为参数值小的模型比较简单能适应不同的数据集也在一定程度上避免了过拟合现象。可以设想一下对于一个线性回归方程若参数很大那么只要数据偏移一点点就会对结果造成很大的影响但如果参数足够小数据偏移得多一点也不会对结果造成什么影响专业一点的说法是『抗扰动能力强』 import seaborn as sns
model Ridge().fit(train_X, train_y_ln)
print(intercept:, model.intercept_)
# 组合数据
data pd.DataFrame({coef_abs: abs(model.coef_), feature: train_X.columns})
sns.barplot(xcoef_abs, yfeature, datadata)展示
Lasso回归 L1正则化有助于生成一个稀疏权值矩阵进而可以用于特征选择
import seaborn as sns
model Lasso().fit(train_X, train_y_ln)
print(intercept:, model.intercept_)
# 组合数据
data pd.DataFrame({coef_abs: abs(model.coef_), feature: train_X.columns})
sns.barplot(xcoef_abs, yfeature, datadata)展示 在这里我们可以看到power、used_time等特征非常重要
6. 非线性模型 决策树通过信息熵或GINI指数选择分裂节点时优先选择的分裂特征也更加重要这同样是一种特征选择的方法。XGBoost与LightGBM模型中的model_importance指标正是基于此计算的 下面我们选择部分模型进行对比
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.neural_network import MLPRegressor
from xgboost.sklearn import XGBRegressor
from lightgbm.sklearn import LGBMRegressor
models [LinearRegression(),DecisionTreeRegressor(),RandomForestRegressor(),GradientBoostingRegressor(),MLPRegressor(solverlbfgs, max_iter100), XGBRegressor(n_estimators 100, objectivereg:squarederror), LGBMRegressor(n_estimators 100)]
result dict()
for model in models:model_name str(model).split(()[0]scores cross_val_score(model, Xtrain_X, ytrain_y_ln, verbose0, cv 5, scoringmake_scorer(mean_absolute_error))result[model_name] scoresprint(model_name is finished)
result pd.DataFrame(result)
result.index [cv str(x) for x in range(1, 6)]
result结果 可以看到随机森林模型在每一个fold中均取得了更好的效果
7. 模型调参
在这里主要介绍三种调参方法
1 贪心调参 所谓贪心算法是指在对问题求解时总是做出在当前看来是最好的选择。也就是说不从整体最优上加以考虑它所做出的仅仅是在某种意义上的局部最优解。 以lightgbm模型为例
## LGB的参数集合
# 损失函数
objective [regression, regression_l1, mape, huber, fair]
# 叶子节点数
num_leaves [3,5,10,15,20,40, 55]
# 最大深度
max_depth [3,5,10,15,20,40, 55]
bagging_fraction []
feature_fraction []
drop_rate []
best_obj dict()
# 计算不同选择下对应结果其中 score最小时为最优结果
for obj in objective:model LGBMRegressor(objectiveobj)score np.mean(cross_val_score(model, Xtrain_X, ytrain_y_ln, verbose0, cv 5, scoringmake_scorer(mean_absolute_error)))best_obj[obj] scorebest_leaves dict()
for leaves in num_leaves:model LGBMRegressor(objectivemin(best_obj.items(), keylambda x:x[1])[0], num_leavesleaves)score np.mean(cross_val_score(model, Xtrain_X, ytrain_y_ln, verbose0, cv 5, scoringmake_scorer(mean_absolute_error)))best_leaves[leaves] scorebest_depth dict()
for depth in max_depth:model LGBMRegressor(objectivemin(best_obj.items(), keylambda x:x[1])[0],num_leavesmin(best_leaves.items(), keylambda x:x[1])[0],max_depthdepth)score np.mean(cross_val_score(model, Xtrain_X, ytrain_y_ln, verbose0, cv 5, scoringmake_scorer(mean_absolute_error)))best_depth[depth] score
# 画出各选择下损失的变化
sns.lineplot(x[0_initial,1_turning_obj,2_turning_leaves,3_turning_depth], y[0.143 ,min(best_obj.values()), min(best_leaves.values()), min(best_depth.values())])2Grid Search 调参 GridSearchCV一种调参的方法当你算法模型效果不是很好时可以通过该方法来调整参数通过循环遍历尝试每一种参数组合返回最好的得分值的参数组合 from sklearn.model_selection import GridSearchCV
parameters {objective: objective , num_leaves: num_leaves, max_depth: max_depth}
model LGBMRegressor()
clf GridSearchCV(model, parameters, cv5)
clf clf.fit(train_X, train_y_ln)
clf.best_params_得到的最佳参数为{max_depth: 10, num_leaves: 55, objective: huber} 我们再用最佳参数来训练模型
model LGBMRegressor(objectivehuber,num_leaves55,max_depth10)
np.mean(cross_val_score(model, Xtrain_X, ytrain_y_ln, verbose0, cv 5, scoringmake_scorer(mean_absolute_error)))结果跟之前的调参是相当的
3贝叶斯调参 贝叶斯优化通过基于目标函数的过去评估结果建立替代函数概率模型来找到最小化目标函数的值。贝叶斯方法与随机或网格搜索的不同之处在于它在尝试下一组超参数时会参考之前的评估结果因此可以省去很多无用功。 from bayes_opt import BayesianOptimization
def rf_cv(num_leaves, max_depth, subsample, min_child_samples):#num_leaves: 决策树上的叶子节点数量。较大的值可以提高模型的复杂度但也容易导致过拟合。# max_depth: 决策树的最大深度。控制树的深度可以限制模型的复杂度有助于防止过拟合。# subsample: 训练数据的子样本比例。该参数可以用来控制每次迭代时使用的数据量有助于加速训练过程并提高模型的泛化能力。# min_child_samples: 每个叶子节点所需的最小样本数。通过限制叶子节点中的样本数量可以控制树的生长避免过拟合。val cross_val_score(LGBMRegressor(objective regression_l1,num_leavesint(num_leaves),max_depthint(max_depth),subsample subsample,min_child_samples int(min_child_samples)),Xtrain_X, ytrain_y_ln, verbose0, cv 5, scoringmake_scorer(mean_absolute_error)).mean()return 1 - valrf_bo BayesianOptimization(rf_cv,{num_leaves: (2, 100),max_depth: (2, 100),subsample: (0.1, 1),min_child_samples : (2, 100)}
)
# 最大化 rf_cv 函数返回的值即最小化负的平均绝对误差
rf_bo.maximize()结果
1 - rf_bo.max[target]总结
上述我们主要通过log转换、正则化、模型选择、参数微调等方法来提高预测的精度最后附上一些学习链接供大家参考线性回归模型https://zhuanlan.zhihu.com/p/49480391决策树模型https://zhuanlan.zhihu.com/p/65304798GBDT模型https://zhuanlan.zhihu.com/p/45145899XGBoost模型https://zhuanlan.zhihu.com/p/86816771LightGBM模型https://zhuanlan.zhihu.com/p/89360721用简单易懂的语言描述「过拟合 overfitting」https://www.zhihu.com/question/32246256/answer/55320482模型复杂度与模型的泛化能力http://yangyingming.com/article/434/正则化的直观理解https://blog.csdn.net/jinping_shi/article/details/52433975贪心算法 https://www.jianshu.com/p/ab89df9759c8网格调参 https://blog.csdn.net/weixin_43172660/article/details/83032029贝叶斯调参 https://blog.csdn.net/linxid/article/details/81189154