网站建设与开发考试,兰州画册设计,北海网站开发,石家庄网站排名优化哪家好文章目录 摘要项目地址实战代码#xff08;初级版#xff09;实战代码#xff08;进阶版#xff09; 摘要
本文介绍了一个完整的机器学习流程项目#xff0c;重点涵盖了多元线性回归的建模与评估方法。项目详细讲解了特征工程中的多项实用技巧#xff0c;包括#xff1… 文章目录 摘要项目地址实战代码初级版实战代码进阶版 摘要
本文介绍了一个完整的机器学习流程项目重点涵盖了多元线性回归的建模与评估方法。项目详细讲解了特征工程中的多项实用技巧包括通过np.log变换使数据符合正态分布、离散型数据的one-hot编码处理、缺失值处理、数据标准化归一化、以及多项式回归升维等关键技术。此外项目还特别介绍了使用正则化方法提高模型泛化能力的重要技巧。该研究为机器学习实践者提供了一个全面的技术参考特别是在数据预处理和模型优化方面具有较高的实用价值。
项目地址
人工智能学习代码库
实战代码初级版 #mermaid-svg-RZ565SEfaUax4hne {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-RZ565SEfaUax4hne .error-icon{fill:#552222;}#mermaid-svg-RZ565SEfaUax4hne .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-RZ565SEfaUax4hne .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-RZ565SEfaUax4hne .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-RZ565SEfaUax4hne .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-RZ565SEfaUax4hne .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-RZ565SEfaUax4hne .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-RZ565SEfaUax4hne .marker{fill:#333333;stroke:#333333;}#mermaid-svg-RZ565SEfaUax4hne .marker.cross{stroke:#333333;}#mermaid-svg-RZ565SEfaUax4hne svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-RZ565SEfaUax4hne .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-RZ565SEfaUax4hne .cluster-label text{fill:#333;}#mermaid-svg-RZ565SEfaUax4hne .cluster-label span{color:#333;}#mermaid-svg-RZ565SEfaUax4hne .label text,#mermaid-svg-RZ565SEfaUax4hne span{fill:#333;color:#333;}#mermaid-svg-RZ565SEfaUax4hne .node rect,#mermaid-svg-RZ565SEfaUax4hne .node circle,#mermaid-svg-RZ565SEfaUax4hne .node ellipse,#mermaid-svg-RZ565SEfaUax4hne .node polygon,#mermaid-svg-RZ565SEfaUax4hne .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-RZ565SEfaUax4hne .node .label{text-align:center;}#mermaid-svg-RZ565SEfaUax4hne .node.clickable{cursor:pointer;}#mermaid-svg-RZ565SEfaUax4hne .arrowheadPath{fill:#333333;}#mermaid-svg-RZ565SEfaUax4hne .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-RZ565SEfaUax4hne .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-RZ565SEfaUax4hne .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-RZ565SEfaUax4hne .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-RZ565SEfaUax4hne .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-RZ565SEfaUax4hne .cluster text{fill:#333;}#mermaid-svg-RZ565SEfaUax4hne .cluster span{color:#333;}#mermaid-svg-RZ565SEfaUax4hne div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-RZ565SEfaUax4hne :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 建模评估 特征处理 数据准备 模型训练 模型评估 离散化非数值列 分离特征和目标 缺失值填充 数据集划分 数据标准化 多项式特征扩展 数据读取与初始化 EDA数据探索 开始 绘制原数据分布 绘制对数变换后分布 特征工程 初始化Ridge模型 训练模型 计算对数变换RMSE/MSE 计算还原后RMSE 输出评估结果 结束 import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, PolynomialFeatures# 设置全局字体为支持中文的字体
plt.rcParams[font.sans-serif] [SimHei] # 使用黑体
plt.rcParams[axes.unicode_minus] False # 解决负号 - 显示为方块的问题# 设置显示宽度: 解决数据显示不完整
pd.set_option(display.max_columns, None) # 显示所有列
pd.set_option(display.width, None) # 自动调整显示宽度# 1 读取数据
data pd.read_csv(./data/insurance.csv)
print(data.head(3))# 2 EDA数探索
# 2.1 原数据右偏
plt.hist(data[charges])
plt.title(原数据 charges 的分布)
plt.xlabel(charges)
plt.ylabel(频数)
plt.show()# 2.2 矫正后的数据
plt.hist(np.log(data[charges]))
plt.title(对数变换后的 charges 的分布)
plt.xlabel(log(charges))
plt.ylabel(频数)
plt.show()# 3 特征工程# 3.1 非数值型的列离散化
datapd.get_dummies(data,columns[sex,smoker,region])
data.head(3)# 3.2 删除目标列 花销一列
xdata.drop(charges,axis1)
ydata[charges]# 3.3 缺失值填充
x.fillna(0,inplaceTrue)
y.fillna(0,inplaceTrue)
# 3.4 数据切分 训练集70%和测试集30%
x_train,x_test,y_train,y_testtrain_test_split(x,y,test_size0.3)# 3.5 标准归一化均值归一化方差归一化 确保训练集和测试集的均值和方差相同
scalerStandardScaler(with_meanTrue,with_stdTrue).fit(x_train)
# 对训练集进行拟合并转换
x_train_scaled scaler.transform(x_train)
# 对测试集进行转换使用训练集的均值和标准差
x_test_scaled scaler.transform(x_test)# 3.6 升维 增加Y的维度或因素 利用线性模型做回归
polynomial_features PolynomialFeatures(degree2, include_biasFalse)
x_train_scaled polynomial_features.fit_transform(x_train_scaled)
x_test_scaled polynomial_features.fit_transform(x_test_scaled)# 4 模型训练 RidgeLinearRegressionL2正则化regRidge(alpha10.0)
reg.fit(x_train_scaled,np.log1p(y_train)) #np.log1p对log函数的优化
y_predictreg.predict(x_test_scaled)# 5 模型评估RMSE均方根误差和 MSE均方误差是常用的模型评估指标用于衡量模型预测值与真实值之间的差异。
对数变换后的 RMSE
重要性这些指标衡量了模型在对数变换后的目标变量上的预测误差。对数变换通常用于处理右偏分布的数据使其更接近正态分布。因此这些指标可以帮助你了解模型在对数空间中的表现。
适用场景当你希望模型在对数空间中表现良好时这些指标非常重要。
# 计算训练集上对数变换后的真实值与预测值之间的均方根误差RMSE
rmse_train_log np.sqrt(mean_squared_error(y_truenp.log1p(y_train), y_predreg.predict(x_train_scaled)))
print(f训练集上对数变换后的 RMSE: {rmse_train_log})# 计算测试集上对数变换后的真实值与预测值之间的均方根误差RMSE
rmse_test_log np.sqrt(mean_squared_error(y_truenp.log1p(y_test), y_predy_predict))
print(f测试集上对数变换后的 RMSE: {rmse_test_log})# 计算训练集上对数变换后的真实值与预测值之间的均方误差MSE
mse_train_log mean_squared_error(y_truenp.log1p(y_train), y_predreg.predict(x_train_scaled))
print(f训练集上对数变换后的 MSE: {mse_train_log})# 计算测试集上对数变换后的真实值与预测值之间的均方误差MSE
mse_test_log mean_squared_error(y_truenp.log1p(y_test), y_predy_predict)
print(f测试集上对数变换后的 MSE: {mse_test_log})
还原后的 RMSE
重要性这些指标衡量了模型在原始目标变量上的预测误差。还原后的 RMSE 更直观地反映了模型在实际数据尺度上的表现。
适用场景当你希望模型在原始数据尺度上表现良好时这些指标非常重要。
# 计算训练集上真实值与预测值经过指数变换还原之间的均方根误差RMSE
rmse_train_exp np.sqrt(mean_squared_error(y_truey_train, y_prednp.exp(reg.predict(x_train_scaled))))
print(f训练集上还原后的 RMSE: {rmse_train_exp})# 计算测试集上真实值与预测值经过指数变换还原之间的均方根误差RMSE
rmse_test_exp np.sqrt(mean_squared_error(y_truey_test, y_prednp.exp(y_predict)))
print(f测试集上还原后的 RMSE: {rmse_test_exp}) age sex bmi children smoker region charges
0 19 female 27.90 0 yes southwest 16884.9240
1 18 male 33.77 1 no southeast 1725.5523
2 28 male 33.00 3 no southeast 4449.4620
训练集上对数变换后的 RMSE: 0.35492916766241805
测试集上对数变换后的 RMSE: 0.3896820204464227
训练集上对数变换后的 MSE: 0.12597471405753685
测试集上对数变换后的 MSE: 0.1518520770592062
训练集上还原后的 RMSE: 4940.399449726374
测试集上还原后的 RMSE: 5243.354576700596实战代码进阶版 #mermaid-svg-uOsuKo2YydZdGHDj {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-uOsuKo2YydZdGHDj .error-icon{fill:#552222;}#mermaid-svg-uOsuKo2YydZdGHDj .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-uOsuKo2YydZdGHDj .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-uOsuKo2YydZdGHDj .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-uOsuKo2YydZdGHDj .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-uOsuKo2YydZdGHDj .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-uOsuKo2YydZdGHDj .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-uOsuKo2YydZdGHDj .marker{fill:#333333;stroke:#333333;}#mermaid-svg-uOsuKo2YydZdGHDj .marker.cross{stroke:#333333;}#mermaid-svg-uOsuKo2YydZdGHDj svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-uOsuKo2YydZdGHDj .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-uOsuKo2YydZdGHDj .cluster-label text{fill:#333;}#mermaid-svg-uOsuKo2YydZdGHDj .cluster-label span{color:#333;}#mermaid-svg-uOsuKo2YydZdGHDj .label text,#mermaid-svg-uOsuKo2YydZdGHDj span{fill:#333;color:#333;}#mermaid-svg-uOsuKo2YydZdGHDj .node rect,#mermaid-svg-uOsuKo2YydZdGHDj .node circle,#mermaid-svg-uOsuKo2YydZdGHDj .node ellipse,#mermaid-svg-uOsuKo2YydZdGHDj .node polygon,#mermaid-svg-uOsuKo2YydZdGHDj .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-uOsuKo2YydZdGHDj .node .label{text-align:center;}#mermaid-svg-uOsuKo2YydZdGHDj .node.clickable{cursor:pointer;}#mermaid-svg-uOsuKo2YydZdGHDj .arrowheadPath{fill:#333333;}#mermaid-svg-uOsuKo2YydZdGHDj .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-uOsuKo2YydZdGHDj .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-uOsuKo2YydZdGHDj .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-uOsuKo2YydZdGHDj .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-uOsuKo2YydZdGHDj .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-uOsuKo2YydZdGHDj .cluster text{fill:#333;}#mermaid-svg-uOsuKo2YydZdGHDj .cluster span{color:#333;}#mermaid-svg-uOsuKo2YydZdGHDj div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-uOsuKo2YydZdGHDj :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 建模评估 特征处理 数据准备 模型训练 模型评估 删除低相关列 连续值离散化 One-Hot编码 分离特征和目标 缺失值填充 数据集划分 多项式特征扩展 数据读取与初始化 EDA数据探索 开始 绘制费用分布 绘制对数变换分布 性别影响分析 区域影响分析 吸烟影响分析 孩子数量影响分析 特征工程 初始化Ridge模型 训练模型 计算对数变换RMSE 计算还原后RMSE 输出评估结果 结束 import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import PolynomialFeatures# 设置全局字体为支持中文的字体
plt.rcParams[font.sans-serif] [SimHei] # 使用黑体
plt.rcParams[axes.unicode_minus] False # 解决负号 - 显示为方块的问题# 设置显示宽度: 解决数据显示不完整
pd.set_option(display.max_columns, None) # 显示所有列
pd.set_option(display.width, None) # 自动调整显示宽度# 1 读取数据
data pd.read_csv(./data/insurance.csv)
print(原数据)
print(data.head(3))# 2 EDA数探索
# 2.1 原数据右偏
plt.hist(data[charges])
plt.title(原数据 charges 的分布)
plt.xlabel(charges)
plt.ylabel(频数)
plt.show()# 2.2 矫正后的数据
plt.hist(np.log(data[charges]))
plt.title(对数变换后的 charges 的分布)
plt.xlabel(log(charges))
plt.ylabel(频数)
plt.show()# 2.2 性别对花费的影响分析
sns.kdeplot(data.loc[data.sex male, charges], labelmale)
sns.kdeplot(data.loc[data.sex female, charges], labelfemale)
plt.legend(title性别对花费的影响分析)
plt.show()# 2.3 区域对花费的影响分析
sns.kdeplot(data.loc[data.region northwest, charges], labelnorthwest)
sns.kdeplot(data.loc[data.region northeast, charges], labelnortheast)
sns.kdeplot(data.loc[data.region southwest, charges], labelsouthwest)
sns.kdeplot(data.loc[data.region southeast, charges], labelsoutheast)
plt.legend(title区域对花费的影响分析)
plt.show()# 2.4 吸烟对花费的影响分析
sns.kdeplot(data.loc[data.smoker yes, charges], labelsmoker)
sns.kdeplot(data.loc[data.smoker no, charges], labelno smoker)
plt.legend(title吸烟对花费的影响分析)
plt.show()# 2.5 孩子个数对花费的影响分析
sns.kdeplot(data.loc[data.children 0, charges], labelno children)
sns.kdeplot(data.loc[data.children 1, charges], labelone children)
sns.kdeplot(data.loc[data.children 2, charges], labeltwo children)
sns.kdeplot(data.loc[data.children 3, charges], labelthree children)
sns.kdeplot(data.loc[data.children 4, charges], labelfour children)
sns.kdeplot(data.loc[data.children 5, charges], labelfive children)
plt.legend(title孩子个数对花费的影响分析)
plt.show()# 3 特征工程
# 3.1 删除系数相关低的列 region、sex
data data.drop([region, sex], axis1)
print(删除系数相关低的列 region、sex)
print(data.head(3))# 3.2 降噪 连续值变为离散值
def greater(df, bmi, num_child):df[bmi] over if df[bmi] bmi else underdf[children] no if df[children] num_child else yesreturn dfdata data.apply(greater, axis1, args(30, 0))# 3.3 非数值型的列离散化
data pd.get_dummies(data)
print(bmi,num_child连续值变为离散值)
print(data.head(3))# 3.4 删除目标列 花销一列
x data.drop(charges, axis1)
y data[charges]# 3.5 缺失值填充
x.fillna(0, inplaceTrue)
y.fillna(0, inplaceTrue)# 3.6 数据切分 训练集70%和测试集30%
x_train, x_test, y_train, y_test train_test_split(x, y, test_size0.3)# 3.7 升维 增加Y的维度 利用线性模型做回归
polynomial_features PolynomialFeatures(degree2, include_biasFalse)
x_train_poly polynomial_features.fit_transform(x_train)
x_test_poly polynomial_features.fit_transform(x_test)# 4 模型训练 RidgeLinearRegressionL2正则化
reg Ridge(alpha10.0)reg.fit(x_train_poly, np.log1p(y_train)) # np.log1p对log函数的优化
y_predict reg.predict(x_test_poly)# 5 模型评估
# 计算训练集上对数变换后的真实值与预测值之间的均方根误差RMSE
print(计算训练集上对数变换后的真实值与预测值之间的均方根误差RMSE)
print(np.sqrt(mean_squared_error(y_truenp.log1p(y_train), y_predreg.predict(x_train_poly))))# 计算测试集上对数变换后的真实值与预测值之间的均方根误差RMSE
print(计算测试集上对数变换后的真实值与预测值之间的均方根误差RMSE)
print(np.sqrt(mean_squared_error(y_truenp.log1p(y_test), y_predy_predict)))# 计算训练集上真实值与预测值经过指数变换还原之间的均方根误差RMSE
print(计算训练集上真实值与预测值经过指数变换还原之间的均方根误差RMSE)
print(np.sqrt(mean_squared_error(y_truey_train, y_prednp.exp(reg.predict(x_train_poly)))))# 计算测试集上真实值与预测值经过指数变换还原之间的均方根误差RMSE
print(计算测试集上真实值与预测值经过指数变换还原之间的均方根误差RMSE)
print(np.sqrt(mean_squared_error(y_truey_test, y_prednp.exp(y_predict))))原数据age sex bmi children smoker region charges
0 19 female 27.90 0 yes southwest 16884.9240
1 18 male 33.77 1 no southeast 1725.5523
2 28 male 33.00 3 no southeast 4449.4620
删除系数相关低的列 region、sexage bmi children smoker charges
0 19 27.90 0 yes 16884.9240
1 18 33.77 1 no 1725.5523
2 28 33.00 3 no 4449.4620
bmi,num_child连续值变为离散值age charges bmi_over bmi_under children_no children_yes smoker_no smoker_yes
0 19 16884.9240 False True True False False True
1 18 1725.5523 True False False True True False
2 28 4449.4620 True False False True True False
计算训练集上对数变换后的真实值与预测值之间的均方根误差RMSE
0.38316517904805586
计算测试集上对数变换后的真实值与预测值之间的均方根误差RMSE
0.3812317453220069
计算训练集上真实值与预测值经过指数变换还原之间的均方根误差RMSE
4746.576620613462
计算测试集上真实值与预测值经过指数变换还原之间的均方根误差RMSE
4899.862272153837