機器學習-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)和 R2 得分)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("均方誤差 (MSE):", mse)
print("R2 得分:", 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. 計算調整后的 R2
r2 = r2_score(y_test, y_pred)
adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - k - 1)
print("調整后的 R2:", 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. 計算調整后的 R2
r2 = r2_score(y_test, y_pred)
adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - k - 1)
print("調整后的 R2:", 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("R2 得分:", 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.pswp.cn/news/895721.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/895721.shtml
英文地址,請注明出處:http://en.pswp.cn/news/895721.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

SQL SERVER的PARTITION BY應用場景

SQL SERVER的PARTITION BY關鍵字說明介紹 PARTITION BY關鍵字介紹具體使用場景排名計算累計求和分組求最值分組內百分比計算分組內移動平均計算分組內數據分布統計分組內數據偏移計算 總結 PARTITION BY關鍵字介紹 在SQL SERVER中&#xff0c;關鍵字PARTITION BY主要用于窗口函…

NO.18十六屆藍橋杯備戰|循環嵌套|乘法表|斐波那契|質數|水仙花數|(C++)

循環嵌套 循環嵌套的使? while &#xff0c; do while &#xff0c; for &#xff0c;這三種循環往往會嵌套在?起才能更好的解決問題&#xff0c;就是我們所說的&#xff1a;循環嵌套。這三種循環都可以任意嵌套使? ?如&#xff1a; 寫?個代碼&#xff0c;打印?個乘法?…

leetcode - hot100 - python - 專題一:哈希

1、兩數之和 簡單 題目&#xff1a; 給定一個整數數組 nums 和一個整數目標值 target&#xff0c;請你在該數組中找出 和為目標值 target 的那 兩個 整數&#xff0c;并返回它們的數組下標。你可以假設每種輸入只會對應一個答案&#xff0c;并且你不能使用兩次相同的元素。你可…

JavaEE-SpringBoot快速入門

文章目錄 本節目標Maven什么是Maven創建一個Maven項目maven項目功能maven的依賴管理全球倉庫, 私服, 本地服務器, 配置國內鏡像 第一個SpringBoot項目創建項目運行SpringBoot程序 SpringBoot原理初步Web服務器 總結 本節目標 了解什么是maven, 配置國內源使用Springboot創建項…

【Viper】配置格式與支持的數據源與go案例

Viper 是一個用于 Go 應用程序的配置管理庫&#xff0c;支持多種配置格式和數據源。 安裝依賴 go get github.com/spf13/viper go get github.com/spf13/viper/remote go get go.etcd.io/etcd/client/v3"github.com/spf13/viper/remote"要寫在etcd客戶端import里 1…

【C/C++】后綴表達式 藍橋杯/ACM備賽

核心考點&#xff1a;1.棧的應用 2.字符串處理 題目描述 所謂后綴表達式是指這樣的一個表達式&#xff1a;式中不再引用括號&#xff0c;運算符號放在兩個運算對象之后&#xff0c;所有計算按運算符號出現的順序&#xff0c;嚴格地由左而右新進行&#xff08;不用考慮運算符的…

【AI實踐】deepseek支持升級git

當前Windows 11 WSL的git是2.17&#xff0c;Android Studio提示需要升級到2.19版本 網上找到指導文章 安裝git 2.19.2 cd /usr/src wget https://www.kernel.org/pub/software/scm/git/git-2.19.2.tar.gz tar xzf git-2.19.2.tar.gz cd git-2.19.2 make prefix/usr/l…

QEMU 搭建 Ubuntu x86 虛擬機

1. 安裝 QEMU 在 Ubuntu 系統中&#xff0c;可以通過以下命令安裝 QEMU&#xff1a; sudo apt-get update sudo apt-get install qemu-system-x86_64 qemu-kvm libvirt-daemon libvirt-clients bridge-utils virt-manager2. 創建虛擬硬盤鏡像 qemu-img create -f raw ubuntu…

Linux驅動層學習:Linux 設備樹

設備樹是一種數據結構&#xff0c;包含多個節點&#xff0c;用于描述硬件設備及其配置信息&#xff0c;它通常用于嵌入式系統中&#xff0c;尤其是在Linux操作系統中&#xff0c;幫助操作系統識別和管理硬件資源&#xff0c;設備樹不是代碼&#xff0c;而是一種用數據描述硬件信…

金蝶云星空與釘釘高效數據集成案例分享

金蝶云星空數據集成到釘釘的技術案例分享 在企業信息化系統中&#xff0c;數據的高效流動和實時反饋是提升業務效率的關鍵。本文將聚焦于一個具體的系統對接集成案例&#xff1a;如何將金蝶云星空的數據集成到釘釘&#xff0c;并實現審核狀態的回傳提示。 本次集成方案名為“…

圖形渲染(一)——Skia、OpenGL、Mesa 和 Vulkan簡介

1.Skia —— 2D 圖形庫 Skia 是一個 2D 圖形庫&#xff0c;它的作用是為開發者提供一個高層次的繪圖接口&#xff0c;方便他們進行 2D 圖形渲染&#xff08;比如繪制文本、形狀、圖像等&#xff09;。Skia 本身不直接管理 GPU 或進行底層的渲染工作&#xff0c;而是通過 底層圖…

GIT提錯分支,回滾提交

1. 準備示例 假設我們有三次提交&#xff1a; test1&#xff1a;需要在 master 分支提交test2、test3&#xff1a;需要在 develop 分支提交 遠端線上記錄 2. 步驟 選擇需要回退的記錄&#xff1a; 選中需要回退的 commit&#xff0c;選擇 Reset Current Branch to Here...。…

【原創】在ubuntu中搭建gradle開發環境

檢查Linux版本 rootwww:~# hostnamectlStatic hostname: www.0x88.comIcon name: computer-vmChassis: vmMachine ID: 30fa955a36be492ca459599ef20bc508Boot ID: 37084dbe36f44adaa075e8f9a98f132eVirtualization: kvm Operating System: Ubuntu 22.04.5 LTSKernel: Linux 5.…

【JavaEE進階】MyBatis入門

目錄 &#x1f334;前言 &#x1f332;什么是MyBatis? &#x1f333;準備工作 &#x1f6a9;創建工程 &#x1f6a9;配置數據庫連接字符串 &#x1f6a9;數據準備 &#x1f6a9;編寫持久層代碼 &#x1f343;單元測試 &#x1f334;前言 在應?分層學習時,我們了解到…

以太網詳解(八)傳輸層協議:TCP/UDP 協議

文章目錄 傳輸層協議概述為什么需要傳輸層&#xff1f;傳輸層功能網絡層與傳輸層在實現 “端到端” 傳輸的異同兩類服務:面向連接/無連接服務 傳輸控制協議 TCPTCP 協議數據單元格式TCP 的重傳機制快重傳和快恢復快重傳舉例快恢復算法 用戶數據報協議 UDPUDP 概述UDP 基本工作過…

Electron 客戶端心跳定時任務調度庫調研文檔 - Node.js 任務調度庫技術調研文檔

Electron 客戶端心跳定時任務調度庫調研文檔 - Node.js 任務調度庫技術調研文檔 本文將對七個流行的定時任務調度庫&#xff1a;node-cron、rxjs、bull、node-schedule、agenda、bree、cron。這些庫都可以用來處理定時任務&#xff0c;但它們的特點和適用場景有所不同。我們將從…

DeepSeek 開放平臺無法充值 改用其他平臺API調用DeepSeek-chat模型方法

近幾天DeepSeek開放平臺無法充值目前已經關閉狀態&#xff0c;大家都是忙著接入DeepSeek模型 &#xff0c;很多人想使用DeepSeek怎么辦&#xff1f; 當然還有改用其他平臺API調用方法&#xff0c;本文以本站的提供chatgpt系統為例&#xff0c;如何修改DeepSeek-chat模型API接口…

pix2text 使用經驗

給同行打雞血 &#x1f60a; 構建結構化的數理領域知識庫&#xff1a; 提高可訪問性和可搜索性 Markdown和LaTeX格式&#xff1a;這兩種格式易于在線發布和共享&#xff0c;有助于提高數學內容的可訪問性。搜索引擎優化&#xff1a;將PDF內容轉換為標記語言&#xff0c;可以…

Linux(centos)系統安裝部署MySQL8.0數據庫(GLIBC版本)

安裝前檢查服務器glibc版本&#xff0c;下載對應版本包 rpm -qa | grep glibc mysql安裝包及依賴包已整理好&#xff0c;下載地址&#xff1a;https://pan.quark.cn/s/3137acc814c0&#xff0c;下載即可安裝 一、下載MySQL mysql安裝包及依賴包已整理好&#xff0c;下載地址…

6.2.圖的存儲結構-鄰接矩陣法

一.鄰接矩陣法存儲不帶權圖&#xff1a; 結點不帶權值&#xff1a; 1.左圖的無向圖中&#xff0c;A到B直達的有一條路&#xff0c;所以A行B列的值為1&#xff1b; 左圖的無向圖中&#xff0c;A到F沒有直達的路&#xff0c;所以A行F列的值為0&#xff1b; 結論&#xff1a;無…