机器学习-1:线性回归

常用的线性回归模型主要有以下这些

  • 简单线性回归
  • 多元线性回归
  • 多项式回归
  • 岭回归
  • 套索回归
  • 弹性网络回归
  • 逐步回归

 一.简单的一元线性回归

1.导入必备的库

#导入必备的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split,cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

 2.设置显示选项

# 设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    #显示最大行数
pd.set_option('display.max_columns', None)  #显示最大列数
pd.set_option('display.max_colwidth', None)  #显示的最大列宽
pd.set_option('display.width', None)  #显示的最宽度

3.导入数据

data=pd.read_excel("汽车制造行业收入表.xlsx")
data=pd.DataFrame(data)
x=pd.DataFrame(data["工龄"])
y=pd.DataFrame(data["薪水"])

4.划分训练集和测试集

x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)

 变量名:

  • x_train: 训练集的特征数据。用于训练模型。

  • x_test: 测试集的特征数据。用于评估模型的性能。

  • y_train: 训练集的目标变量。与 x_train 对应,用于训练模型。

  • y_test: 测试集的目标变量。与 x_test 对应,用于评估模型的性能。

train_test_split 函数参数:

  • x: 输入特征数据。可以是 NumPy 数组、Pandas DataFrame 或其他可迭代的数据结构。

  • y: 目标变量。与 x 对应,表示要预测的值。

  • test_size=0.2: 指定测试集的比例。0.2 表示 20% 的数据将被分配到测试集,剩余 80% 的数据将被分配到训练集。

  • random_state=42: 随机种子,用于确保数据分割的可重复性。指定一个整数(如 42)可以使每次运行代码时,数据分割的结果相同。这对于调试和结果复现非常有用

5.数据预处理

根据数据情况进行数据的标准化/归一化/二值化

6.模型建立 

6.1创建线性回归模型:y=a*x+b

model = LinearRegression()

 6.2训练模型

model.fit(x_train, y_train)

 6.3输出线性回归系数

print("线性回归系数a:",model.coef_)
print("线性回归截距b:",model.intercept_)
线性回归系数a: [[1114.15442257]]
线性回归截距b: [7680.390625]

 6.4预测数据

y_test_pred= model.predict(x_test)

 6.5评估

mse = mean_squared_error(y_test, y_test_pred)
r2 = r2_score(y_test, y_test_pred)
rmse = np.sqrt(mse)
mae = np.mean(np.abs(y_test - y_test_pred))
# 计算调整后的R平方
n = len(y_test)
p = x_train.shape[1]
adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)
cv_scores = cross_val_score(model, x, y, cv=5, scoring='r2')

 1. mse = mean_squared_error(y_test, y_test_pred)

  • 功能:计算测试集上的均方误差(Mean Squared Error, MSE)。

  • y_test: 测试集的真实目标值。

  • y_test_pred: 模型在测试集上的预测值。

  • MSE 越小,表示模型的预测值与实际值越接近

2. r2 = r2_score(y_test, y_test_pred)

  • 功能:计算测试集上的R平方(R2)得分。

  • y_test: 测试集的真实目标值。

  • y_test_pred: 模型在测试集上的预测值

  • R2 越接近1,表示模型越好

3.rmse = np.sqrt(mse)

  • 功能:计算均方误差的平方根。

  • RMSE 提供了与原始数据相同单位的误差度量,便于解释。与 MSE 类似,RMSE 越小,模型越好。

4.mae = np.mean(np.abs(y_test - y_test_pred))

  • 功能:计算测试集上预测值与实际值之间的平均绝对误差。

  • MAE 是预测值与实际值之间绝对差异的平均值,MAE 越小,表示模型的预测值与实际值越接近,MAE 对异常值不如 MSE 敏感

5.adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)

  • 功能:计算调整后的 R2 值。

  • 调整后的 R2 在自变量数量较多时更为可靠,因为它惩罚了不必要的复杂性

6. cv_scores = cross_val_score(model, x, y, cv=5, scoring='r2')

  • 功能:使用5折交叉验证来评估模型的R平方得分。

  • model: 要评估的模型对象,例如 LinearRegression()。

  • x: 特征数据。

  • y: 目标变量。

  • cv=5: 使用5折交叉验证,将数据分成5个子集。

  • scoring='r2': 使用R平方作为评估指标。

  • 输出:cv_scores 是一个数组,包含每次交叉验证的R平方得分。

其中交叉验证的评估指标主要有以下几种

1. R平方(R2)

  • 范围:[−∞,1]

  • 𝑅2=1:表示模型完美拟合数据。

  • 𝑅2=0:表示模型没有解释任何方差,预测的效果与简单的均值预测相同。

  • 𝑅2<0:表示模型比简单的均值预测效果还差。

2. 均方误差(Mean Squared Error, MSE)

  • 范围:[0,∞)

  • MSE 越小,表示模型的预测值与实际值越接近。

  • MSE 为 0 表示模型预测完全准确。

3. 均方根误差(Root Mean Squared Error, RMSE)

  • 范围:[0,∞)

  • RMSE 是 MSE 的平方根,提供了与原始数据相同单位的误差度量。

  • RMSE 越小,表示模型的预测值与实际值越接近。

4. 平均绝对误差(Mean Absolute Error, MAE)

  • 范围:[0,∞)

  • MAE 越小,表示模型的预测值与实际值越接近。

  • MAE 为 0 表示模型预测完全准确。

5. 分类准确率(Accuracy)

  • 范围:[0,1]

  • 准确率为 1 表示模型预测完全准确。

  • 准确率为 0 表示模型预测完全错误。

6. F1分数(F1 Score)

  • 范围:[0,1]

  • F1 分数为 1 表示完美的精确率和召回率。

  • F1 分数为 0 表示模型没有正确预测任何正类样本。

对于回归问题,常用的指标包括 R2、MSE、RMSE 和 MAE;对于分类问题,常用的指标包括准确率和 F1 分数

5.7可视化

plt.scatter(x_train, y_train, color='blue', label='训练数据')
plt.scatter(x_test, y_test, color='green', label='测试数据')
plt.plot(x_test, y_test_pred, color='red', linewidth=2, label='预测数据')
plt.xlabel('工龄')
plt.ylabel('薪水')
plt.title('简单的线性回归')
plt.legend()
plt.show()

5.8代码汇总

#1.导入必备的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split,cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
#2.设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    #显示最大行数
pd.set_option('display.max_columns', None)  #显示最大列数
pd.set_option('display.max_colwidth', None)  #显示的最大列宽
pd.set_option('display.width', None)  #显示的最宽度
#3.导入数据
data=pd.read_excel("汽车制造行业收入表.xlsx")
data=pd.DataFrame(data)
x=pd.DataFrame(data["工龄"])
y=pd.DataFrame(data["薪水"])
#4.划分训练集与测试集
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)
#5数据预处理
#6.1创建线性回归模型
model = LinearRegression()
#6.2模型训练
model.fit(x_train, y_train)
#6.3输出回归数值
print("线性回归系数a:",model.coef_)
print("线性回归截距b:",model.intercept_)
#6.4预测数据
y_test_pred= model.predict(x_test)
#6.5模型评估
mse = mean_squared_error(y_test, y_test_pred)
r2 = r2_score(y_test, y_test_pred)
rmse = np.sqrt(mse)
mae = np.mean(np.abs(y_test - y_test_pred))
# 计算调整后的R平方
n = len(y_test)
p = x_train.shape[1]
adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)
cv_scores = cross_val_score(model, x, y, cv=5, scoring='r2')
# 输出结果
print("交叉验证评估:", cv_scores)#用于评估模型的泛化能力和稳定性
print("平均交叉验证:", np.mean(cv_scores))
print("均方误差:", mse)#它表示预测值与实际值之间误差的平方的平均值
print("决定系数:", r2)
print("均方根误差 (RMSE):", rmse)
print("平均绝对误差 (MAE):", mae)
print("调整后的R^2:", adjusted_r2)
# 数据可视化
plt.scatter(x_train, y_train, color='blue', label='训练数据')
plt.scatter(x_test, y_test, color='green', label='测试数据')
plt.plot(x_test, y_test_pred, color='red', linewidth=2, label='预测数据')
plt.xlabel('工龄')
plt.ylabel('薪水')
plt.title('简单的线性回归')
plt.legend()
plt.show()

二.多元线性回归:客户价值数据表

#1.导入必备的库
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import statsmodels.api as sm
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error as mse
from sklearn.preprocessing import StandardScaler
from scipy import stats
#2.显示设置
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    #显示最大行数
pd.set_option('display.max_columns', None)  #显示最大列数
pd.set_option('display.max_colwidth', None)  #显示的最大列宽
pd.set_option('display.width', None)  #显示的最宽度
#3.数据导入
data=pd.read_excel("客户价值数据表.xlsx")#4.数据预处理
#4.1使用均值填写缺失值
print("缺失值统计:\n",data.isnull().sum())
data = data.apply(lambda col: col.fillna(col.mean()), axis=0)#使用每一列的平均值填充
# print(data.head())
#4.2异常值处理
numeric_data = data.select_dtypes(include=[np.number])
z_scores = np.abs(stats.zscore(data.select_dtypes(include=[np.number])))  # 仅对数值型数据计算 Z-score
threshold = 3  # Z-score 阈值 3个标准差
outliers = (z_scores > threshold).any(axis=1)  # 检测异常值
print("检测到的异常值行索引:\n", data[outliers].index.tolist())  # 输出异常值的行索引
print(data[outliers])
data = data[~outliers]  # 移除异常值#4.3训练集与测试集的划分
x=data.drop(["客户价值"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)
#4.4创建标准化训练集与测试集
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)  # 对训练集进行标准化
x_test = scaler.transform(x_test)#5建立模型
#5.1建立线性回归模型(多元)
linear=LinearRegression()
#5.2模型训练
linear.fit(x_train,y_train)  #使用标准化后的数据进行模型训练
#5.3输出各项系数
print("线性回归的系数a是:",linear.coef_)  #
print("线性回归的截距b是:",linear.intercept_)
#5.4数据预测
y_pred=linear.predict(x_test)
#5.5模型评估
print("回归得分:",linear.score(x_test,y_test).__round__(2))  #保留两位小数
print("mse线性回归评估:",mse(y_test, y_pred).__round__(2))
#5.6可视化
plt.bar(range(len(linear.coef_)), linear.coef_)
plt.xlabel("特征")
plt.ylabel("系数")
plt.title("特征重要性")plt.show()
plt.figure(figsize=(10, 6))
plt.boxplot(numeric_data.values, tick_labels=numeric_data.columns)
plt.title("箱线图检测异常值")
plt.xticks(rotation=45)
plt.show()

三.多项式回归

适用于一元和多元的非线性关系

#1.导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from scipy import stats
#2.设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    #显示最大行数
pd.set_option('display.max_columns', None)  #显示最大列数
pd.set_option('display.max_colwidth', None)  #显示的最大列宽
pd.set_option('display.width', None)  #显示的最宽度#3.读取数据
data=pd.read_excel("客户价值数据表.xlsx")#4.数据预处理
#4.1使用均值填写缺失值
print("缺失值统计:\n",data.isnull().sum())
data = data.apply(lambda col: col.fillna(col.mean()), axis=0)#使用每一列的平均值填充
# print(data.head())
#4.2异常值处理
numeric_data = data.select_dtypes(include=[np.number])
z_scores = np.abs(stats.zscore(data.select_dtypes(include=[np.number])))  # 仅对数值型数据计算 Z-score
threshold = 3  # Z-score 阈值 3个标准差
outliers = (z_scores > threshold).any(axis=1)  # 检测异常值
print("检测到的异常值行索引:\n", data[outliers].index.tolist())  # 输出异常值的行索引
print(data[outliers])
data = data[~outliers]  # 移除异常值
x=data.drop(["客户价值","性别"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]
#4.3多项式特征转换
degree = 2
poly = PolynomialFeatures(degree=degree)
x_poly = poly.fit_transform(x)
#4.4划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x_poly, y, test_size=0.2, random_state=42)
#4.5标准化训练集与测试集
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)  # 对训练集进行标准化
x_test = scaler.transform(x_test)#5模型建立
#5.1建立多项式回归模型
model = LinearRegression()
#5.2训练模型
model.fit(x_train, y_train)
#5.3输出模型参数
print("模型系数(权重):", model.coef_)
print("模型截距:", model.intercept_)
#5.4预测
y_pred = model.predict(x_test)
#5.5模型评估(计算均方误差(MSE)和 R² 得分)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("均方误差 (MSE):", mse)
print("R² 得分:", r2)

四.岭回归

1.使用L2正则化

正则化(Regularization)是一种用于防止机器学习模型过拟合的技术。

过拟合是指模型在训练集上表现很好,但在测试集上表现较差

# 1. 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import mean_squared_error, r2_score
from scipy import stats
# 2. 设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    # 显示最大行数
pd.set_option('display.max_columns', None)  # 显示最大列数
pd.set_option('display.max_colwidth', None)  # 显示的最大列宽
pd.set_option('display.width', None)  # 显示的最宽度# 3. 读取数据
data=pd.read_excel("客户价值数据表.xlsx")# 4. 数据预处理
#4.1使用均值填写缺失值
print("缺失值统计:\n",data.isnull().sum())
data = data.apply(lambda col: col.fillna(col.mean()), axis=0)#使用每一列的平均值填充
# print(data.head())
#4.2异常值处理
numeric_data = data.select_dtypes(include=[np.number])
z_scores = np.abs(stats.zscore(data.select_dtypes(include=[np.number])))  # 仅对数值型数据计算 Z-score
threshold = 3  # Z-score 阈值 3个标准差
outliers = (z_scores > threshold).any(axis=1)  # 检测异常值
print("检测到的异常值行索引:\n", data[outliers].index.tolist())  # 输出异常值的行索引
print(data[outliers])
data = data[~outliers]  # 移除异常值
x=data.drop(["客户价值"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]
# 4.3 将数据分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
# 4.4 标准化
scaler = StandardScaler()
x_train = scaler.fit_transform(X_train)  # 对训练集进行标准化
x_test = scaler.transform(X_test)# 5. 建立模型
# 5.1 定义参数网格
param_grid = {'alpha': np.logspace(-4, 4, 100)}  # 从 0.0001 到 10000 的 100 个值
# 5.2 使用 GridSearchCV 寻找最佳 alpha
ridge = Ridge()
grid_search = GridSearchCV(ridge, param_grid, cv=5, scoring='neg_mean_squared_error')
grid_search.fit(X_train, y_train)
# 5.3 输出最佳参数和对应的模型
best_alpha = grid_search.best_params_['alpha']
print("最佳 alpha:", best_alpha)
# 5.4 使用最佳 alpha 训练最终模型
ridge_best = Ridge(alpha=best_alpha)
ridge_best.fit(X_train, y_train)
# 5.5 预测
y_pred = ridge_best.predict(X_test)
# 5.6 模型评估
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
# 6. 残差分析
residuals = y_test - y_pred
# 6.1 绘制残差图
plt.figure(figsize=(10, 6))
plt.scatter(y_pred, residuals)
plt.axhline(0, color='red', linestyle='--')
plt.xlabel("预测值")
plt.ylabel("残差")
plt.title("残差分析")
plt.show()
# 7. 计算 AIC 和 BIC
n = len(y_test)  # 样本数量
k = X_train.shape[1]  # 自变量数量
# 计算 AIC 和 BIC
aic = n * np.log(mse) + 2 * (k + 1)  # +1 是因为有截距项
bic = n * np.log(mse) + np.log(n) * (k + 1)
print("AIC:", aic)
print("BIC:", bic)
# 8. 计算调整后的 R²
r2 = r2_score(y_test, y_pred)
adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - k - 1)
print("调整后的 R²:", adjusted_r2)

五.套索回归 

使用L1正则化

# 1. 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LassoCV, Lasso
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from scipy import stats
# 2. 设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    # 显示最大行数
pd.set_option('display.max_columns', None)  # 显示最大列数
pd.set_option('display.max_colwidth', None)  # 显示的最大列宽
pd.set_option('display.width', None)  # 显示的最宽度# 3. 读取数据
data=pd.read_excel("客户价值数据表.xlsx")# 4. 数据预处理
#4.1使用均值填写缺失值
print("缺失值统计:\n",data.isnull().sum())
data = data.apply(lambda col: col.fillna(col.mean()), axis=0)#使用每一列的平均值填充
# print(data.head())
#4.2异常值处理
numeric_data = data.select_dtypes(include=[np.number])
z_scores = np.abs(stats.zscore(data.select_dtypes(include=[np.number])))  # 仅对数值型数据计算 Z-score
threshold = 3  # Z-score 阈值 3个标准差
outliers = (z_scores > threshold).any(axis=1)  # 检测异常值
print("检测到的异常值行索引:\n", data[outliers].index.tolist())  # 输出异常值的行索引
print(data[outliers])
data = data[~outliers]  # 移除异常值
x=data.drop(["客户价值"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]
# 4.3 将数据分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
#4.4创建标准化训练集与测试集
scaler = StandardScaler()
x_train = scaler.fit_transform(X_train)  # 对训练集进行标准化
x_test = scaler.transform(X_test)# 5. 建立模型
# 5.1 使用 LassoCV 寻找最佳 alpha
lasso_cv = LassoCV(alphas=np.logspace(-4, 4, 100), cv=5)  # 100 个 alpha 值,5 折交叉验证
lasso_cv.fit(X_train, y_train)
# 5.2 输出最佳参数和对应的模型
best_alpha = lasso_cv.alpha_
print("最佳 alpha:", best_alpha)
# 5.3 使用最佳 alpha 训练最终模型
lasso_best = Lasso(alpha=best_alpha)
lasso_best.fit(X_train, y_train)
# 5.4 预测
y_pred = lasso_best.predict(X_test)
# 5.5 模型评估
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
# 5.6 输出模型系数
print("Coefficients:", lasso_best.coef_)
print("Intercept:", lasso_best.intercept_)
# 6. 计算 AIC 和 BIC
n = len(y_test)  # 样本数量
k = np.sum(lasso_best.coef_ != 0)  # 非零系数的数量
# 计算 AIC 和 BIC
aic = n * np.log(mse) + 2 * (k + 1)  # +1 是因为有截距项
bic = n * np.log(mse) + np.log(n) * (k + 1)
print("AIC:", aic)
print("BIC:", bic)
# 7. 计算调整后的 R²
r2 = r2_score(y_test, y_pred)
adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - k - 1)
print("调整后的 R²:", adjusted_r2)
# 8. 残差分析
residuals = y_test - y_pred
# 8.1 绘制残差图
plt.figure(figsize=(10, 6))
plt.scatter(y_pred, residuals)
plt.axhline(0, color='red', linestyle='--')
plt.xlabel("预测值")
plt.ylabel("残差")
plt.title("残差分析")
plt.show()

六.弹性网络回归

使用L1与L2正则化相结合

# 1. 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import ElasticNetCV, ElasticNet
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from scipy import stats
# 2. 设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    # 显示最大行数
pd.set_option('display.max_columns', None)  # 显示最大列数
pd.set_option('display.max_colwidth', None)  # 显示的最大列宽
pd.set_option('display.width', None)  # 显示的最宽度# 3. 读取数据
data=pd.read_excel("客户价值数据表.xlsx")# 4. 数据预处理
#4.1使用均值填写缺失值
print("缺失值统计:\n",data.isnull().sum())
data = data.apply(lambda col: col.fillna(col.mean()), axis=0)#使用每一列的平均值填充
# print(data.head())
#4.2异常值处理
numeric_data = data.select_dtypes(include=[np.number])
z_scores = np.abs(stats.zscore(data.select_dtypes(include=[np.number])))  # 仅对数值型数据计算 Z-score
threshold = 3  # Z-score 阈值 3个标准差
outliers = (z_scores > threshold).any(axis=1)  # 检测异常值
print("检测到的异常值行索引:\n", data[outliers].index.tolist())  # 输出异常值的行索引
print(data[outliers])
data = data[~outliers]  # 移除异常值
x=data.drop(["客户价值"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]
# 4.3 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
#4.4创建标准化训练集与测试集
scaler = StandardScaler()
x_train = scaler.fit_transform(X_train)  # 对训练集进行标准化
x_test = scaler.transform(X_test)# 5. 建立模型
# 5.1 使用 ElasticNetCV 寻找最佳 alpha 和 l1_ratio
alphas = np.logspace(-4, 4, 100)  # 100 个 alpha 值
l1_ratios = np.linspace(0.1, 1, 10)  # 10 个 l1_ratio 值,确保大于 0
model_cv = ElasticNetCV(alphas=alphas, l1_ratio=l1_ratios, cv=5, random_state=42, max_iter=5000, tol=1e-5)
model_cv.fit(X_train, y_train)# 5.2 输出最佳参数和对应的模型
best_alpha = model_cv.alpha_
best_l1_ratio = model_cv.l1_ratio_
print("最佳 alpha:", best_alpha)
print("最佳 l1_ratio:", best_l1_ratio)# 5.3 使用最佳参数训练最终模型
model = ElasticNet(alpha=best_alpha, l1_ratio=best_l1_ratio, random_state=42)
model.fit(X_train, y_train)# 5.4 预测
y_pred = model.predict(X_test)# 5.5 评估
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("均方误差 (MSE):", mse)
print("R² 得分:", r2)# 6. 可视化
# 绘制系数
plt.figure(figsize=(10, 6))
plt.bar(range(len(model.coef_)), model.coef_)
plt.xlabel("特征")
plt.ylabel("系数")
plt.title("弹性网络回归系数")
plt.show()
# 8. 残差分析
residuals = y_test - y_pred# 8.1 绘制残差图
plt.figure(figsize=(10, 6))
plt.scatter(y_pred, residuals)
plt.axhline(0, color='red', linestyle='--')
plt.xlabel("预测值")
plt.ylabel("残差")
plt.title("残差分析")
plt.show()
# 8.2 绘制残差的直方图
plt.figure(figsize=(10, 6))
plt.hist(residuals, bins=30, edgecolor='k')
plt.xlabel("残差")
plt.ylabel("频率")
plt.title("残差的直方图")
plt.show()
# 8.3 绘制 Q-Q 图
import scipy.stats as stats
plt.figure(figsize=(10, 6))
stats.probplot(residuals, dist="norm", plot=plt)
plt.title("Q-Q 图")
plt.show()

特征工程1

#1.导入必备的库
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from statsmodels.stats.outliers_influence import variance_inflation_factor
from sklearn.feature_selection import mutual_info_regression
#2.显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False"""
1.皮尔逊相关系数:用于衡量两个连续变量之间的线性关系,值范围在 -1 到 1 之间。
值接近 1 表示强正相关,接近 -1 表示强负相关,接近 0 表示无相关性。   
2.斯皮尔曼等级相关系数:用于衡量两个变量之间的单调关系,适用于非正态分布的数据。
3.肯德尔相关系数:另一种用于衡量两个变量之间的相关性的方法,适用于小样本数据。
"""
df=pd.read_excel("客户价值数据表.xlsx")
pearson = df.corr(method='pearson')  # 计算皮尔逊相关系数
spearman =df.corr(method='spearman') # 计算斯皮尔曼等级相关系数
kendall = df.corr(method='kendall')  # 计算肯德尔相关系数
correlation_matrices = [pearson, spearman, kendall]
names = ["pearson", "spearman", "kendall"]
# 遍历列表并绘制热力图
for matrix, name in zip(correlation_matrices, names):plt.figure(figsize=(10, 8))sns.heatmap(matrix, annot=True, fmt=".2f", cmap='coolwarm')plt.title(f"{name}相关性矩阵")plt.show()#2.VIF 用于检测多重共线性,计算每个特征与其他特征的相关性。VIF 值越高,表示该特征与其他特征的相关性越强,通常 VIF > 10 被认为存在严重的多重共线性
# 计算 VIF
X = df.drop('客户价值', axis=1)  # 特征
vif = pd.DataFrame()
vif['特征'] = X.columns
vif['VIF'] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]
print(vif)# 互信息用于衡量两个变量之间的信息共享程度,适用于分类和连续变量。值越高,表示两个变量之间的相关性越强。
y=df["客户价值"]
mi = mutual_info_regression(X, y)
mi_scores = pd.Series(mi, index=X.columns)
print(mi_scores.sort_values(ascending=False))

特征选择方法:

一.逐步回归

#1.导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.preprocessing import StandardScaler#2.设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    #显示最大行数
pd.set_option('display.max_columns', None)  #显示最大列数
pd.set_option('display.max_colwidth', None)  #显示的最大列宽
pd.set_option('display.width', None)  #显示的最宽度#3.导入数据
data=pd.read_excel("客户价值数据表.xlsx")
x=data.drop(["客户价值"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]#4.数据预处理
#4.1标准化
scaler = StandardScaler()
x=scaler.fit_transform(x)
x=pd.DataFrame(x,columns=["历史贷款金额","贷款次数","学历","月收入","性别"])
#4.2划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)#5.建立模型
def stepwise_selection(X, y, initial_list=[], threshold_in=0.01, threshold_out=0.05, verbose=True):"""逐步回归特征选择:param X: 特征数据(DataFrame):param y: 目标变量(Series):param initial_list: 初始特征列表:param threshold_in: 添加特征的显著性阈值:param threshold_out: 删除特征的显著性阈值:param verbose: 是否打印过程:return: 最终选择的特征列表"""included = list(initial_list)while True:changed = False# 前向选择excluded = list(set(X.columns) - set(included))new_pval = pd.Series(index=excluded, dtype=float)for new_column in excluded:model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included + [new_column]]))).fit()new_pval[new_column] = model.pvalues[new_column]best_pval = new_pval.min()if best_pval < threshold_in:best_feature = new_pval.idxmin()included.append(best_feature)changed = Trueif verbose:print(f"Add {best_feature} with p-value {best_pval:.6f}")# 后向消除model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included]))).fit()pvalues = model.pvalues.iloc[1:]  # 忽略截距worst_pval = pvalues.max()if worst_pval > threshold_out:changed = Trueworst_feature = pvalues.idxmax()included.remove(worst_feature)if verbose:print(f"Remove {worst_feature} with p-value {worst_pval:.6f}")if not changed:breakreturn included# 运行逐步回归
selected_features = stepwise_selection(X_train, y_train)
# 输出最终选择的特征
print("最终选择的特征:", selected_features)

二.主成分分析

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/17534.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【DuodooBMS】给PDF附件加“受控”水印的完整Python实现

给PDF附件加“受控”水印的完整Python实现 功能需求 在实际工作中&#xff0c;许多文件需要添加水印以标识其状态&#xff0c;例如“受控”“机密”等。对于PDF文件&#xff0c;添加水印不仅可以增强文件的可识别性&#xff0c;还可以防止未经授权的使用。本代码的功能需求是…

java每日精进 2.13 Ganache(区块链本地私有化部署)

需求&#xff1a;使用区块链实现数据村存储&#xff0c;记录一些不可篡改的交互信息&#xff0c;网络环境为内外网均需要部署&#xff1b; 1.准备工作&#xff08;软件安装&#xff09; 1.1 安装 Node.js 和 npm 1.2 安装 Ganache 地址如下&#xff1a;windows有可视化界面 &a…

RAGFlow和Dify对比

‌ RAGFlow和Dify都是基于大语言模型&#xff08;LLM&#xff09;的应用开发平台&#xff0c;具有相似的功能和应用场景&#xff0c;但它们在技术架构、部署要求和用户体验上存在一些差异。‌‌ RAGFlow和Dify对比 2025-02-13 22.08 RAGFlow‌ ‌技术栈‌&#xff1a;RAGFlow…

day9手机创意软件

趣味类 in:记录趣味生活&#xff08;通用&#xff09; 魔漫相机&#xff1a;真人变漫画&#xff08;通用&#xff09; 活照片&#xff1a;让照片活过来&#xff08;通用&#xff09; 画中画相机&#xff1a;与众不同的艺术 年龄检测仪&#xff1a;比一比谁更年轻&#xf…

Next.js 15【实用教程】2025最新版

官网 https://nextjs.org/docs/app/getting-started Next.js 简介 Next.js 由 Vercel 开发和维护&#xff0c;旨在解决单页应用&#xff08;SPA&#xff09;和多页应用&#xff08;MPA&#xff09;在性能和 SEO 上的不足。 核心特性 服务端渲染&#xff08;SSR&#xff09;--…

MySQL 联合索引的最左匹配原则

环境&#xff1a;MySQL 版本&#xff1a;8.0.27 执行计划基础知识 possible_keys&#xff1a;可能用到的索引 key&#xff1a;实际用到的索引 type: ref&#xff1a;当通过普通的二级索引列与常量进行等值匹配的方式 询某个表时const&#xff1a;当我们根据主键或者唯一得…

2025 西湖论剑wp

web Rank-l 打开题目环境&#xff1a; 发现一个输入框&#xff0c;看一下他是用上面语言写的 发现是python&#xff0c;很容易想到ssti 密码随便输&#xff0c;发现没有回显 但是输入其他字符会报错 确定为ssti注入 开始构造payload&#xff0c; {{(lipsum|attr(‘global…

【2024 CSDN博客之星】大学四年,我如何在CSDN实现学业与事业的“双逆袭”?

前言&#xff1a; Hello大家好&#xff0c;我是Dream。不知不觉2024年已经过去&#xff0c;自己也马上迈入23岁&#xff0c;感慨时间飞快&#xff0c;从19岁刚入大学加入CSDN&#xff0c;到现在大学毕业已经整整四年了。CSDN陪伴我走过了最青涩的四年大学时光&#xff0c;在这里…

RAG(检索增强生成)落地:基于阿里云opensearch视线智能问答机器人与企业知识库

文章目录 一、环境准备二、阿里云opensearch准备1、产品文档2、准备我们的数据3、上传文件 三、对接1、对接文本问答 一、环境准备 # 准备python环境 conda create -n opensearch conda activate opensearch# 安装必要的包 pip install alibabacloud_tea_util pip install ali…

Qt事件机制

目录 一、事件基本概念 1.1 事件基本概念和产生 1.2 事件类 1.3 事件发送 二、事件的捕获处理 2.1 事件处理流程 2.2事件分发&#xff08;event&#xff09;处捕获事件 2.3 事件过滤器 2.4 重新实现事件处理函数 三、 QEventLoop 3.1事件循环基本概念 3.2 QEventL…

20250212:sigmastar系列2-获取UUID进行授权

距离上一篇Sigmastar文章已经过去3年了。最近基于Sigmastar-330 开发人脸识别SDK,需要进行授权管理,所以需要获取UUID作为激活、授权的凭证。 本文记录2个事情:授权逻辑 + sigmastar获取UUID 1:授权流程 step1:算法SDK在设备上电,算法初始化环节,校验本地是否有加密存…

STM32F407通过FSMC扩展外部SRAM和NAND FLASH

1 扩展外部SRAM 1.1 地址情况 FSMC控制器的存储区分为4个区(Bank)&#xff0c;每个区256MB。其中&#xff0c;Bank1可以用于连接SRAM、NOR FLASH、PSRAM&#xff0c;还可以连接TFT LCD。Bank1的地址范围是0x60000000&#xff5e;0x6FFFFFFF。Bank1又分为4个子区&#xff0c;每…

MySQL Workbench工具 导出导入数据库

第一步 数据库导出 1、打开workbench->连接数据库->Server->Data Export 2、选择要导出的数据库&#xff0c;Export Self-Contained File ->更改导出位置和数据库名->Start Export 3、提示“sql has finished”&#xff0c;没有error表示导出成功 第二步 数据…

我用AI做数据分析之四种堆叠聚合模型的比较

我用AI做数据分析之四种堆叠聚合模型的比较 这里AI数据分析不仅仅是指AI生成代码的能力&#xff0c;我想是测试AI数据分析方面的四个能力&#xff0c;理解人类指令的能力、撰写代码的能力、执行代码的能力和解释结果的能力。如果这四个能力都达到了相当的水准&#xff0c;才可…

广告深度学习计算:阿里妈妈大模型服务框架HighService

一、背景 HighService(High-Performance Pythonic AI Service) 是在支持阿里妈妈业务过程中&#xff0c;不断提炼抽象出的高性能Python AI服务框架&#xff0c;支持视频、图文、LLM等多种模型&#xff0c;能够显著加快模型的推理速度&#xff0c;提高集群的资源利用效率。随着S…

深度学习框架探秘|TensorFlow vs PyTorch:AI 框架的巅峰对决

在深度学习框架中&#xff0c;TensorFlow 和 PyTorch 无疑是两大明星框架。前面两篇文章我们分别介绍了 TensorFlow&#xff08;点击查看&#xff09; 和 PyTorch&#xff08;点击查看&#xff09;。它们引领着 AI 开发的潮流&#xff0c;吸引着无数开发者投身其中。但这两大框…

企语企业管理系iFair(F23.2_a0)在Debian操作系统中的安装

起因&#xff1a;在安装了F24.8版本后&#xff0c;发现生产用环境和测试、开发用环境还是分开的好。 旧版的用来实验、测试&#xff0c;新版的一步一步小心的配置、使用是比较稳妥的操作。因此&#xff0c;决定在KVM虚拟机上搭建一个F23.2版本的企语系统。 一、 存在的问题 而…

Redis 数据类型 Hash 哈希

在 Redis 中&#xff0c;哈希类型是指值本⾝⼜是⼀个键值对结构&#xff0c;形如 key "key"&#xff0c;value { { field1, value1 }, ..., {fieldN, valueN } }&#xff0c;Redis String 和 Hash 类型⼆者的关系可以⽤下图来表⽰。 Hash 数据类型的特点 键值对集合…

Elasticsearch:15 年来致力于索引一切,找到重要内容

作者&#xff1a;来自 Elastic Shay Banon 及 Philipp Krenn Elasticsearch 刚刚 15 岁了&#xff01;回顾过去 15 年的索引和搜索&#xff0c;并展望未来 15 年的相关内容。 Elasticsearch 刚刚成立 15 周年。一切始于 2010 年 2 月的一篇公告博客文章&#xff08;带有标志性的…

EF Core中实现值对象

目录 值对象优点 值对象的需求 值类型的实现 值类型GEO的实现 值类型MultilingualString的实现 案例&#xff1a;构建表达式树&#xff0c;简化值对象的比较 值对象优点 把有紧密关系的属性打包为一个类型把领域知识放到类的定义中 class shangjia {long id;string nam…