本次训练的变量是一致对应的,训练准备通过后,后续建模都不会有报错的!
一、训练准备(x_train, x_test, y_train, y_test)
1.1 导包
scikit-learn包以及镜像
pip3 install --index-url https://pypi.douban.com/simple scikit-learn
1.2 数据要求
必须全部为数字类型且无空值才能进行训练,关于非数据类型需要进行相对处理例如:可以采用独热编码或者label编码进行处理。
本文演示的是pandas 的dataframe数据类型的操作,转换成别的类型也同理
1.21 导入数据
import pandas as pd df = pd.read_csv('data.csv') df.head(5) #查看数据前五条
1.22 数据类型查看检测以及转换
1. 通过df.info()查看类型以及缺失值情况
df.info()
2. label编码
使用sklearn中的LabelEncoder类,将标签分配给分类变量的不同类别,并将其转换为整数标签。from sklearn.preprocessing import LabelEncoder Label_df[i] = LabelEncoder().fit_transform(Label_df[i])
3. 独热编码
pd.get_dummies函数是Pandas中用于执行独热编码的函数。它将类别变量转换为独热编码的形式,其中每个类别将被转换为新的二进制特征,表示原始特征中是否存在该类别。这对于机器学习模型处理分类数据时非常有用。
例如,如果有一个类别特征"color",包含红色、蓝色和绿色三个类别。使用pd.get_dummies函数可以将这个特征转换为三个新的特征"color_red"、“color_blue"和"color_green”,它们的取值为0或1,表示原始特征中是否包含对应的颜色。df_one_hot = pd.get_dummies(df, columns=['color']) df_one_hot.replace({False: 0, True: 1})
4. 缺失值处理
直接删除#删除指定列缺失值 df.dropna(subset=['身份证号'],inplace = True) #删除NaN值 df.dropna(axis=0,inplace=True) #全部为空就删除此行 df.dropna(axis=0,how="all",inplace=True) #有一个为空就删除此行 df.dropna(axis=0, how='any', inplace=True)
填充
#数据填充 df.fillna(method='pad', inplace=True) # 填充前一条数据的值 df.fillna(method='bfill', inplace=True) # 填充后一条数据的值 df.fillna(df['cname'].mean(), inplace=True) # 填充平均值
5. 检测函数这里是我自己定义的高效快速便捷方式
检测函数,输入dataframe用for循环对每列检测和操作, 自动检测空值,object类型数据,并且进行默认操作,
df.fillna(method=‘pad’, inplace=True) # 填充前一条数据的值
df.fillna(method=‘bfill’, inplace=True) # 填充后一条数据的值
独热编码
df_one_hot = pd.get_dummies(df, columns=[‘color’])
返回处理好的dataframedef process_dataframe(df): df.fillna(method='pad', inplace=True) # 填充前一条数据的值 df.fillna(method='bfill', inplace=True) # 填充后一条数据的值 df_one_hot = df.copy() for i in df.columns: if df[i].dtype == object: df_one_hot = pd.get_dummies(df, columns=[i]) # 独热编码 return df_one_hot
更多dataframe操作可以看一下鄙人不才总结的小处理
http://t.yssmx.com/iRbFj1.22 划分数据
from sklearn.model_selection import train_test_split x_data = df.iloc[:, 0:-1] y_data = df.iloc[:, -1] # 划分数据集 x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3, random_state=42)
二、回归
2.1 线性回归
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression
训练以及简单预测
from sklearn.linear_model import LinearRegression
from sklearn import metrics
#加载模型训练
Linear_R = LinearRegression()
Linear_R.fit(x_train, y_train)
# 预测
y_pred = Linear_R.predict(x_test)
# 评估
MAE_lr = metrics.mean_absolute_error(y_test, y_pred)
MSE_lr = metrics.mean_squared_error(y_test, y_pred)
RMSE_lr = metrics.mean_squared_error(y_test, y_pred, squared=False)
R2_Score_lr = metrics.r2_score(y_test, y_pred)
print("LinearRegression 评估")
print("MAE: ", MAE_lr)
print("MSE: ", MSE_lr)
print("RMSE: ", RMSE_lr)
print("R2 Score: ", R2_Score_lr)
2.2 随机森林回归
from sklearn.ensemble import RandomForestRegressor
from sklearn import metrics
#加载模型训练
RandomForest_R = RandomForestRegressor()
RandomForest_R.fit(x_train, y_train)
# 预测
y_pred = RandomForest_R.predict(x_test)
# 评估
MAE_Forest= metrics.mean_absolute_error(y_test, y_pred)
MSE_Forest = metrics.mean_squared_error(y_test, y_pred)
RMSE_Forest = metrics.mean_squared_error(y_test, y_pred, squared=False)
R2_Score_Forest = metrics.r2_score(y_test, y_pred)
print("LinearRegression 评估")
print("MAE: ", MAE_Forest)
print("MSE: ", MSE_Forest)
print("RMSE: ", RMSE_Forest)
print("R2 Score: ", R2_Score_Forest)
模型优化
from sklearn.model_selection import RandomizedSearchCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import make_regression
# 创建一个参数网格,定义需要调整的超参数及其可能的取值范围
param_grid = {
'n_estimators': [100, 200, 300], # 树的数量
'max_depth': [None, 5, 10, 15], # 最大深度
'min_samples_split': [2, 5, 10], # 内部节点再划分所需最小样本数
'min_samples_leaf': [1, 2, 4] # 叶子节点最少样本数
}
# 创建一个随机森林回归模型
rf = RandomForestRegressor()
# 使用 RandomizedSearchCV 进行参数搜索
random_search = RandomizedSearchCV(estimator=rf, param_distributions=param_grid, n_iter=100, cv=5, verbose=2, random_state=42, n_jobs=-1)
# 训练模型并搜索最佳参数组合
random_search.fit(x_train, y_train)
# 输出最佳参数组合和最佳评分
print("Best Parameters:", random_search.best_params_)
print("Best Score:", random_search.best_score_)
# 使用最佳参数组合的模型进行预测
best_model = random_search.best_estimator_
y_pred = best_model.predict(x_test)
# 评估模型性能
MAE_Forest = metrics.mean_absolute_error(y_test, y_pred)
MSE_Forest = metrics.mean_squared_error(y_test, y_pred)
RMSE_Forest = metrics.mean_squared_error(y_test, y_pred, squared=False)
R2_Score_Forest = metrics.r2_score(y_test, y_pred)
print("\nRandom Forest Regression Evaluation with Best Parameters:")
print("MAE: ", MAE_Forest)
print("MSE: ", MSE_Forest)
print("RMSE: ", RMSE_Forest)
print("R2 Score: ", R2_Score_Forest)
2.3 GradientBoostingRegressor梯度提升树回归
https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html
这里是引用梯度提升树(GradientBoosting)是一种集成学习方法,通过构建多个弱预测模型(通常是决策树),然后将它们组合成一个强预测模型。梯度提升树通过迭代的方式训练决策树模型,每一次迭代都会针对之前迭代的残差进行拟合。它通过梯度下降的方式逐步改进模型,以最小化损失函数。
梯度提升树在每一轮迭代中,通过拟合一个新的弱模型来纠正之前模型的错误。在每一轮迭代中,它会计算出模型的负梯度(残差),然后用新的弱模型去拟合这个负梯度,使得之前模型的残差得到修正。最终,多个弱模型组合成一个强模型,可以用于回归问题和分类问题。在Scikit-Learn中,GradientBoostingRegressor是基于梯度提升树的回归模型。它可以通过调节树的数量、树的深度以及学习率等超参数来控制模型的复杂度和泛化能力。梯度提升树在处理各种类型的数据集时都表现良好,并且常被用于解决回归问题。
from sklearn.ensemble import GradientBoostingRegressor
from sklearn import metrics
#加载模型训练
GradientBoosting_R = GradientBoostingRegressor()
GradientBoosting_R.fit(x_train, y_train)
# 预测
y_pred = GradientBoosting_R.predict(x_test)
# 评估
MAE_GradientBoosting= metrics.mean_absolute_error(y_test, y_pred)
MSE_GradientBoosting = metrics.mean_squared_error(y_test, y_pred)
RMSE_GradientBoosting = metrics.mean_squared_error(y_test, y_pred, squared=False)
R2_Score_GradientBoosting = r2_score(y_test, y_pred)
print("GradientBoostingRegressor 评估")
print("MAE: ", MAE_GradientBoosting)
print("MSE: ", MSE_GradientBoosting)
print("RMSE: ", RMSE_GradientBoosting)
print("R2 Score: ", R2_Score_GradientBoosting)
2.4 Lasso回归
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Lasso.html#sklearn.linear_model.Lasso
Lasso回归(Least Absolute Shrinkage and Selection Operator Regression)是一种线性回归方法,它利用L1正则化来限制模型参数的大小,并倾向于产生稀疏模型。与传统的最小二乘法不同,Lasso回归在优化目标函数时,不仅考虑到数据拟合项,还考虑到对模型参数的惩罚项。
Lasso回归的优化目标函数是普通最小二乘法的损失函数加上L1范数的惩罚项
from sklearn.linear_model import Lasso
from sklearn import metrics
#加载模型训练
Lasso_R = Lasso()
Lasso_R.fit(x_train, y_train)
# 预测
y_pred = Lasso_R.predict(x_test)
# 评估
MAE_Lasso= metrics.mean_absolute_error(y_test, y_pred)
MSE_Lasso = metrics.mean_squared_error(y_test, y_pred)
RMSE_Lasso = metrics.mean_squared_error(y_test, y_pred, squared=False)
R2_Score_Lasso = metrics.r2_score(y_test, y_pred)
print("Lasso 评估")
print("MAE: ", MAE_Lasso)
print("MSE: ", MSE_Lasso)
print("RMSE: ", RMSE_Lasso)
print("R2 Score: ", R2_Score_Lasso)
2.5 Ridge岭回归
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html#sklearn.linear_model.Ridge
from sklearn.linear_model import Ridge
from sklearn import metrics
#加载模型训练
Ridge_R = Ridge()
Ridge_R.fit(x_train, y_train)
# 预测
y_pred = Ridge_R.predict(x_test)
# 评估
MAE_Ridge= metrics.mean_absolute_error(y_test, y_pred)
MSE_Ridge = metrics.mean_squared_error(y_test, y_pred)
RMSE_Ridge = metrics.mean_squared_error(y_test, y_pred, squared=False)
R2_Score_Ridge = r2_score(y_test, y_pred)
print("RidgeCV 评估")
print("MAE: ", MAE_Ridge)
print("MSE: ", MSE_Ridge)
print("RMSE: ", RMSE_Ridge)
print("R2 Score: ", R2_Score_Ridge)
2.6 Elastic Net回归
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.ElasticNet.html
Elastic Net回归是一种结合了岭回归(Ridge Regression)和Lasso回归(Lasso
Regression)的线性回归模型。它通过结合L1和L2正则化惩罚项来克服岭回归和Lasso回归各自的限制,以达到更好的预测性能。岭回归使用L2正则化,它通过向损失函数添加一个惩罚项来限制模型参数的大小,防止过拟合。Lasso回归使用L1正则化,它倾向于产生稀疏的模型,即使大部分特征对目标变量没有影响,也会将它们的系数缩减为零。
Elastic
Net回归结合了L1和L2正则化的优点,可以同时产生稀疏模型并减少多重共线性带来的影响。它的损失函数包括数据拟合项和正则化项,其中正则化项是L1和L2范数的线性组合。Elastic Net回归在特征维度很高,且特征之间存在相关性时很有用。它可以用于特征选择和回归分析,尤其适用于处理实际数据集中的复杂问题。文章来源:https://www.toymoban.com/news/detail-741936.html
from sklearn.linear_model import ElasticNet
from sklearn import metrics
# 使用训练数据拟合模型
elastic_net = ElasticNet()
elastic_net.fit(x_train, y_train)
# 预测
y_pred = elastic_net.predict(x_test)
# 评估
MAE_ElasticNet= metrics.mean_absolute_error(y_test, y_pred)
MSE_ElasticNet = metrics.mean_squared_error(y_test, y_pred)
RMSE_ElasticNet = metrics.mean_squared_error(y_test, y_pred, squared=False)
R2_Score_ElasticNet = metrics.r2_score(y_test, y_pred)
print("ElasticNet 评估")
print("MAE: ", MAE_ElasticNet)
print("MSE: ", MSE_ElasticNet)
print("RMSE: ", RMSE_ElasticNet)
print("R2 Score: ", R2_Score_ElasticNet)
2.7 DecisionTreeRegressor决策树模型
https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html文章来源地址https://www.toymoban.com/news/detail-741936.html
from sklearn.tree import DecisionTreeRegressor
from sklearn import metrics
decision_tree = DecisionTreeRegressor()
decision_tree.fit(x_train, y_train)
y_pred = decision_tree.predict(x_test)
# 评估
MAE_decision_tree= metrics.mean_absolute_error(y_test, y_pred)
MSE_decision_tree = metrics.mean_squared_error(y_test, y_pred)
RMSE_decision_tree = metrics.mean_squared_error(y_test, y_pred, squared=False)
R2_Score_decision_tree = r2_score(y_test, y_pred)
print("DecisionTreeRegressor 评估")
print("MAE: ", MAE_decision_tree)
print("MSE: ", MSE_decision_tree)
print("RMSE: ", RMSE_decision_tree)
print("R2 Score: ", R2_Score_decision_tree)
自动化模型加评估
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge
from sklearn.linear_model import ElasticNet
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, mean_squared_error, r2_score
modellist = [LinearRegression,RandomForestRegressor,GradientBoostingRegressor,Lasso,Ridge,ElasticNet,DecisionTreeRegressor]
namelist = ['LinearRegression','RandomForest','GradientBoosting','Lasso','Ridge','ElasticNet','DecisionTree']
RMSE = []
R2_Score = []
for i in range(len(modellist)):
mymodel = modellist[i]
tr_model = mymodel()
tr_model.fit(x_train, y_train)
y_pred = tr_model.predict(x_train)
print(f'{namelist[i]} 模型评估 \n MAE:{mean_absolute_error(y_train, y_pred)} MSE:{mean_squared_error(y_train, y_pred)} RMSE:{mean_squared_error(y_train,y_pred, squared=False)} R2 Score:{r2_score(y_train, y_pred)}')
y_pred = tr_model.predict(x_test)
RMSE.append(mean_squared_error(y_test,y_pred, squared=False))
R2_Score.append(r2_score(y_test, y_pred))
data_show = pd.concat([pd.DataFrame(RMSE),pd.DataFrame(R2_Score),pd.DataFrame(namelist)],axis=1)
data_show.columns = ['RMSE','R2_Score','model']
data_show
三、分类
…未完待续
到了这里,关于模型应用系实习生-模型训练笔记(更新至线性回归、Ridge回归、Lasso回归、Elastic Net回归、决策树回归、梯度提升树回归和随机森林回归)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!