scikit learn回归算法案例教程从零开始掌握线性回归逻辑回归与决策树在房价预测与数据分析中的实战应用技巧

引言:机器学习回归算法在数据分析中的核心地位
在当今数据驱动的时代,机器学习算法已经成为数据分析和预测建模的核心工具。Scikit-learn作为Python生态中最受欢迎的机器学习库,提供了丰富且高效的算法实现,其中回归算法在房价预测、销售预测、风险评估等实际业务场景中发挥着不可替代的作用。
回归分析是统计学中用于研究变量间关系的建模技术,它通过建立数学模型来预测连续型目标变量。在房价预测任务中,我们通常拥有房屋的面积、位置、房龄、房间数量等特征数据,通过回归算法可以建立这些特征与房价之间的映射关系,从而实现对新房屋的准确估值。
本文将从零开始,详细讲解如何使用scikit-learn实现三种经典的回归算法:线性回归、逻辑回归和决策树。我们将通过波士顿房价数据集和合成数据集,完整展示从数据准备、模型训练、参数调优到结果评估的全流程,并深入剖析每种算法的原理、适用场景和实战技巧。
第一部分:环境准备与数据探索
1.1 环境配置与库的导入
在开始之前,我们需要确保安装了必要的Python库。推荐使用Anaconda环境,它已经预装了大部分数据科学所需的包。
# 导入核心库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier
from sklearn.metrics import mean_squared_error, r2_score, accuracy_score, classification_report
from sklearn.model_selection import cross_val_score, GridSearchCV

# 设置绘图风格
plt.style.use(‘seaborn-v0_8-whitegrid’)
sns.set_palette(“husl”)
%matplotlib inline
1.2 数据集加载与探索
我们将使用scikit-learn内置的波士顿房价数据集作为回归任务的示例。该数据集包含506个样本,每个样本有13个特征和1个目标变量(房价中位数)。
# 加载波士顿房价数据集
boston = datasets.load_boston()
X = boston.data
y = boston.target
feature_names = boston.feature_names

# 创建DataFrame便于分析
df = pd.DataFrame(X, columns=feature_names)
df[‘PRICE’] = y

print(“数据集形状:”, df.shape)
print(“\n特征名称:”, feature_names)
print(“\n数据集前5行:”)
print(df.head())
print(“\n数据集统计描述:”)
print(df.describe())
1.3 数据可视化分析
在建模之前,理解数据的分布和特征之间的关系至关重要。我们将通过多种可视化手段进行探索。
# 1. 目标变量分布
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
sns.histplot(df[‘PRICE’], kde=True, bins=30)
plt.title(‘房价分布直方图’)
plt.xlabel(‘房价中位数(千美元)’)
plt.ylabel(‘频数’)

# 2. 特征与目标变量关系
plt.subplot(1, 2, 2)
sns.scatterplot(data=df, x=’RM’, y=’PRICE’, alpha=0.6)
plt.title(‘房间数(RM) vs 房价(PRICE)’)
plt.xlabel(‘平均房间数’)
plt.ylabel(‘房价中位数’)
plt.tight_layout()
plt.show()

# 3. 特征相关性热力图
plt.figure(figsize=(10, 8))
correlation_matrix = df.corr()
sns.heatmap(correlation_matrix, annot=True, cmap=’coolwarm’, fmt=”.2f”, linewidths=0.5)
plt.title(‘特征相关性热力图’)
plt.show()
通过可视化分析,我们可以发现:
RM(房间数)与PRICE呈强正相关(约0.7)
LSTAT(低收入人群比例)与PRICE呈强负相关(约-0.74)
数据分布可能存在异常值,需要在建模前进行处理
第二部分:线性回归算法详解与实战
2.1 线性回归原理与数学基础
线性回归(Linear Regression)是机器学习中最基础的回归算法,它假设目标变量与特征之间存在线性关系。其数学模型为:
\[ y = w_1x_1 + w_2x_2 + … + w_nx_n + b \]
其中,
\(w\)
是权重系数,
\(b\)
是偏置项。模型的目标是找到最优的
\(w\)
和
\(b\)
,使得预测值与真实值之间的误差最小。scikit-learn使用最小二乘法(Ordinary Least Squares)来求解这个优化问题。
2.2 线性回归完整代码实现
# 数据准备:选择RM和LSTAT两个特征进行演示
X_simple = df[[‘RM’, ‘LSTAT’]].values
y_simple = df[‘PRICE’].values

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
X_simple, y_simple, test_size=0.2, random_state=42
)

# 特征标准化(线性回归通常不需要,但对某些情况有帮助)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.fit_transform(X_test)

# 创建并训练线性回归模型
lin_reg = LinearRegression()
lin_reg.fit(X_train, y_train)

# 预测
y_pred = lin_reg.predict(X_test)

# 评估模型
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f”线性回归模型评估:”)
print(f”均方误差 (MSE): {mse:.2f}”)
print(f”决定系数 (R²): {r2:.2f}”)
print(f”模型系数: {lin_reg.coef_}”)
print(f”模型截距: {lin_reg.intercept_}”)

# 可视化预测结果
plt.figure(figsize=(8, 6))
plt.scatter(y_test, y_pred, alpha=0.6)
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], ‘r–‘, lw=2)
plt.xlabel(‘真实房价’)
plt.ylabel(‘预测房价’)
plt.title(‘线性回归预测结果 vs 真实值’)
plt.show()
2.3 线性回归的优缺点与适用场景
优点
:
计算效率高,训练速度快
模型可解释性强,系数直接反映特征重要性
对小数据集表现稳定
缺点
:
无法处理非线性关系
对异常值敏感
假设特征之间相互独立(多重共线性问题)
适用场景
:
需要快速建立基线模型
需要解释特征对目标的影响方向
数据关系近似线性
2.4 线性回归的高级技巧:多项式特征扩展
当数据存在非线性关系时,可以通过引入多项式特征来增强线性回归的表达能力。
from sklearn.preprocessing import PolynomialFeatures

# 创建多项式特征(2次)
poly = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly.fit_transform(X_simple)

# 重新划分数据集
X_train_poly, X_test_poly, y_train_poly, y_train_test = train_test_split(
X_poly, y_simple, test_size=0.2, random_state=42
)

# 训练多项式回归模型
poly_reg = LinearRegression()
poly_reg.fit(X_train_poly, y_train_poly)

# 预测与评估
y_pred_poly = poly_reg.predict(X_test_poly)
mse_poly = mean_squared_error(y_train_test, y_pred_poly)
r2_poly = r2_score(y_train_test, y_pred_poly)

print(f”多项式回归(2次)评估:”)
print(f”均方误差 (MSE): {mse_poly:.2f}”)
print(f”决定系数 (R²): {r2_poly:.2f}”)
第三部分:逻辑回归算法详解与实战
3.1 逻辑回归原理与数学基础
逻辑回归(Logistic Regression)虽然名字中包含”回归”,但实际上是用于
分类
任务的算法。它通过Sigmoid函数将线性回归的输出映射到[0,1]区间,表示样本属于某个类别的概率。
Sigmoid函数:
$
\( \sigma(z) = \1 / (1 + e^{-z}) \)
$
逻辑回归模型:
$
\( P(y=1|x) = \sigma(w^Tx + b) \)
$
3.2 逻辑回归完整代码实现(房价分类任务)
为了演示逻辑回归,我们将连续的房价转换为二分类问题:高于中位数的房价为1(贵),低于中位数的为0(便宜)。
# 创建二分类目标变量
median_price = df[‘PRICE’].median()
df[‘PRICE_CLASS’] = (df[‘PRICE’] > median_price).astype(int)

X_class = df[[‘RM’, ‘LSTAT’, ‘PTRATIO’]].values
y_class = df[‘PRICE_CLASS’].values

# 划分数据集
X_train_clf, X_test_clf, y_train_clf, y_test_clf = train_test_split(
X_class, y_class, test_size=0.2, random_state=42, stratify=y_class
)

# 特征标准化(逻辑回归通常需要标准化)
scaler_clf = StandardScaler()
X_train_clf_scaled = scaler_clf.fit_transform(X_train_clf)
X_test_clf_scaled = scaler_clf.transform(X分类测试集)

# 创建并训练逻辑回归模型
log_reg = LogisticRegression(random_state=42, max_iter=1000)
log_reg.fit(X_train_clf_scaled, y_train_clf)

# 预测
y_pred_clf = log_reg.predict(X_test_clf_scaled)
y_pred_proba = log_reg.predict_proba(X_test_clf_scaled)

# 评估模型
accuracy = accuracy_score(y_test_clf, y_pred_clf)
print(f”逻辑回归分类准确率: {accuracy:.4f}”)
print(“\n分类报告:”)
print(classification_report(y_test_clf, y_pred_clf, target_names=[‘便宜’, ‘贵’]))

# 特征重要性分析
feature_importance = pd.DataFrame({
‘feature’: [‘RM’, ‘LSTAT’, ‘PTRATIO’],
‘coefficient’: log_reg.coef_[0]
})
print(“\n特征系数(重要性):”)
print(feature_importance.sort_values(‘coefficient’, ascending=False))
3.3 逻辑回归的参数调优
# 使用GridSearchCV进行参数调优
param_grid = {
‘C’: [0.001, 0.01, 1, 10, 100], # 正则化强度
‘penalty’: [‘l1’, ‘l2’], # 正则化类型
‘solver’: [‘liblinear’] # 适用于小数据集的求解器
}

grid_search = GridSearchCV(
LogisticRegression(random_state=42, max_iter=1000),
param_grid,
cv=5,
scoring=’accuracy’
)

grid_search.fit(X_train_clf_scaled, y_train_clf)

print(“最佳参数:”, grid_search.best_params_)
print(“最佳交叉验证分数:”, grid_search.best_score_)

# 使用最佳模型
best_log_reg = grid_search.best_estimator_
y_pred_best = best_log_reg.predict(X_test_clf_scaled)
print(f”调优后准确率: {accuracy_score(y_test_clf, y_pred_best):.4f}”)
3.4 逻辑回归的优缺点与适用场景
优点
:
输出概率,可解释性强
计算效率高,适合大规模数据
对特征工程要求相对较低
缺点
:
只能处理线性决策边界
对多重共线性敏感
需要特征标准化
适用场景
:
二分类/多分类任务
需要概率输出的场景(如信用评分)
特征与目标存在线性关系
第四部分:决策树算法详解与实战
4.1 决策树原理与数学基础
决策树(Decision Tree)是一种非参数的监督学习算法,通过递归地选择最优特征并划分数据来构建树结构。决策树既可以用于回归也可以用于分类。
关键概念
:
信息增益/基尼不纯度
:用于分类任务的特征选择标准
均方误差/平均绝对误差
:用于回归任务的特征选择标准
剪枝
:防止过拟合的技术
4.2 决策树回归完整代码实现
# 使用决策树回归预测房价
X_train, X_test, y_train, y_test = train_test_split(
X_simple, y_simple, test_size=0.2, random_state=42
)

# 创建决策树回归模型
tree_reg = DecisionTreeRegressor(
max_depth=5, # 树的最大深度
min_samples_split=10, # 分裂所需最小样本数
random_state=42
)

# 训练模型
tree_reg.fit(X_train, y_train)

# 预测与评估
y_pred_tree = tree_reg.predict(X_test)
mse_tree = mean_squared_error(y_test, y_pred_tree)
r2_tree = r2_score(y_test, y_pred_tree)

print(f”决策树回归模型评估:”)
print(f”均方误差 (MSE): {mse_tree:.2f}”)
print(f”决定系数 (R²): {r2_tree:.2f}”)

# 可视化决策树结构
from sklearn.tree import plot_tree
plt.figure(figsize=(20, 10))
plot_tree(tree_reg,
feature_names=[‘RM’, ‘LSTAT’],
filled=True,
rounded=True,
fontsize=10)
plt.title(‘决策树回归结构可视化’)
plt.show()
4.3 决策树分类完整代码实现
# 决策树分类
tree_clf = DecisionTreeClassifier(
max_depth=3,
min_samples_split=20,
random_state=42
)

tree_clf.fit(X_train_clf_scaled, y_train_clf)
y_pred_tree_clf = tree_clf.predict(X_test_clf_scaled)

print(f”决策树分类准确率: {accuracy_score(y_test_clf, y_pred_tree_clf):.4f}”)
print(“\n决策树分类报告:”)
print(classification_report(y_test_clf, y_pred_tree_clf, target_names=[‘便宜’, ‘贵’]))

# 特征重要性
importance_df = pd.DataFrame({
‘feature’: [‘RM’, ‘LSTAT’, ‘PTRATIO’],
‘importance’: tree_clf.feature_importances_
})
print(“\n特征重要性:”)
print(importance_df.sort_values(‘importance’, ascending=False))
4.4 决策树的参数调优与剪枝策略
# 决策树参数网格搜索
param_grid_tree = {
‘max_depth’: [3, 5, 7, 10, None],
‘min_samples_split’: [2, 5, 10, 20],
‘min_samples_leaf’: [1, 2, 5, 10],
‘max_features’: [None, ‘sqrt’, ‘log2′]
}

grid_tree = GridSearchCV(
DecisionTreeClassifier(random_state=42),
param_grid_tree,
cv=5,
scoring=’accuracy’
)

grid_tree.fit(X_train_clf_scaled, y_train_clf)

print(“决策树最佳参数:”, grid_tree.best_params_)
print(“最佳交叉验证分数:”, grid_tree.best_score_)

# 复杂度曲线:展示参数对模型的影响
max_depth_range = range(1, 15)
train_scores = []
cv_scores = []

for depth in max_depth_range:
tree = DecisionTreeClassifier(max_depth=depth, random_state=42)
tree.fit(X_train_clf_scaled, y_train_clf)
train_scores.append(tree.score(X_train_clf_scaled, y_train_clf))
cv_scores.append(cross_val_score(tree, X_train_clf_scaled, y_train_clf, cv=5).mean())

plt.figure(figsize=(8, 5))
plt.plot(max_depth_range, train_scores, label=’训练准确率’)
plt.plot(max_depth_range, cv_scores, label=’交叉验证准确率’)
plt.xlabel(‘树的最大深度’)
plt.ylabel(‘准确率’)
plt.title(‘决策树复杂度曲线’)
plt.legend()
plt.show()
4.5 决策树的优缺点与适用场景
优点
:
可解释性强,规则清晰
无需特征标准化
能处理非线性关系和混合数据类型
自动特征选择
缺点
:
容易过拟合,需要剪枝
对数据微小变化敏感(不稳定)
偏向于优先选择具有更多取值的特征
适用场景
:
需要清晰决策规则的业务场景
特征包含数值和类别混合数据
数据关系复杂,非线性明显
第五部分:模型评估与选择策略
5.1 回归模型评估指标详解
# 综合评估三种回归模型
models = {
‘线性回归’: lin_reg,
‘决策树回归’: tree_reg
}

# 由于逻辑回归是分类模型,这里只比较回归模型
print(“回归模型综合评估:”)
for name, model in models.items():
if name == ‘线性回归’:
y_pred = model.predict(X_test)
else:
y_pred = model.predict(X_test)

mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
rmse = np.sqrt(mse)

print(f”\n{name}:”)
print(f” 均方误差 (MSE): {mse:.2f}”)
1. **均方误差 (MSE)**:预测值与真实值差的平方的均值,越小越好
2. **均方根误差 (RMSE)**:MSE的平方根,与目标变量同单位
1. **决定系数 (R²)**:模型解释的方差比例,越接近1越好
5.2 交叉验证与模型稳定性分析
# 交叉验证评估模型稳定性
print(“\n交叉验证评估(5折):”)
for name, model in models.items():
if name == ‘线性回归’:
X_data = X_simple
else:
X_data = X_simple

scores = cross_val_score(model, X_data, y_simple, cv=5, scoring=’r2′)
print(f”{name} R²分数: {scores.mean():.3f} (+/- {scores.std() * 2:.3f})”)
5.3 模型选择决策树
算法类型
适用任务
优点
缺点
推荐场景
线性回归
连续值预测
快速、可解释
只能处理线性关系
基线模型、需要解释性
逻辑回归
分类任务
输出概率、高效
只能线性边界
二分类、概率预测
决策树
回归/分类
可解释、非线性
易过拟合
规则提取、复杂关系
第六部分:完整项目实战:端到端房价预测系统
6.1 完整数据预处理流程
# 加载完整数据集并进行完整预处理
boston = datasets.load_boston()
X_full = boston.data
y_full = boston.target
feature_names = boston.feature_names

# 创建DataFrame
df_full = pd.DataFrame(X_full, columns=feature_names)
df_full[‘PRICE’] = y_full

# 1. 缺失值处理(虽然本数据集没有缺失,但展示方法)
print(“缺失值检查:”)
print(df_full.isnull().sum())

# 2. 异常值处理(使用IQR方法)
def remove_outliers_iqr(df, column):
Q1 = df[column].quantile(0.25)
Q3 = df[column].25
IQR = Q3 – Q1
lower_bound = Q1 – 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
return df[(df[column] >= lower_bound) & (df[column] <= upper_bound)] # 对PRICE进行异常值处理 df_clean = remove_outliers_iqr(df_full, 'PRICE') print(f"\n异常值处理前: {len(df_full)} 条数据") print(f"异常值处理后: {len(df_clean)} 条数据") # 3. 特征工程:创建新特征 df_clean['ROOM_RATIO'] = df_clean['RM'] / df_clean['AGE'] df_clean['TAX_PTRATIO'] = df_clean['TAX'] / df_clean['PTRATIO'] # 4. 特征选择 X_processed = df_clean.drop(['PRICE'], axis=1).values y_processed = df_clean['PRICE'].values # 5. 特征标准化 scaler_final = StandardScaler() X_processed_scaled = scaler_final.fit_transform(X_processed) # 6. 划分数据集 X_train_final, X_test_final, y_train_final, y_test_final = train_test_split( X_processed_scaled, y_processed, test_size=0.2, random_state=42 ) 6.2 多模型对比与集成策略 # 多模型对比 from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor models_final = { '线性回归': LinearRegression(), '决策树': DecisionTreeRegressor(random_state=42, max_depth=5), '随机森林': RandomForestRegressor(n_estimators=100, random_state=42), '梯度提升': GradientBoostingRegressor(n_estimators=100, random_state=42) } results = [] for name, model in models_final.items(): model.fit(X_train_final, y_train_final) y_pred = model.predict(X_test_final) mse = mean_squared_error(y_test_final, y_pred) r2 = r2_score(y_test_final, y_pred) rmse = np.sqrt(mse) results.append({ '模型': name, 'MSE': mse, 'RMSE': rmse, 'R²': r2 }) results_df = pd.DataFrame(results) print("\n模型对比结果:") print(results_df.round(4)) 6.3 模型部署与预测函数 # 创建一个完整的预测函数 def predict_house_price(rm, lstat, ptratio, tax, age, scaler, model): """ 预测房价的完整函数 参数: rm: 平均房间数 lstat: 低收入人群比例 ptratio: 学生教师比例 tax: 物业税率 age: 1940年前建成的房屋比例 scaler: 标准化器 model: 训练好的模型 返回: 预测房价 """ # 创建特征数组 features = np.array([[rm, lstat, ptratio, tax, age, rm/age if age != 0 else 0, tax/ptratio if ptratio != 0 else 0]]) # 标准化 features_scaled = scaler.transform(features) # 预测 predicted_price = model.predict(features_scaled)[0] return predicted_price # 使用示例 # 假设有一套房子:RM=6.5, LSTAT=10, PTRATIO=15, TAX=300, AGE=50 sample_house = { 'rm': 6.5, 'lstat': 10, 'ptratio': 15, 'tax': 300, 'age': 50 } # 使用随机森林模型预测 rf_model = models_final['随机森林'] predicted_price = predict_house_price( sample_house['rm'], sample_house['lstat'], sample_house['ptratio'], sample_house['tax'], sample_house['age'], scaler_final, rf_model ) print(f"\n示例房屋预测价格: ${predicted_price:.2f}千美元") 第七部分:常见问题与解决方案 7.1 过拟合与欠拟合的识别与处理 # 通过学习曲线诊断过拟合/欠拟合 from sklearn.model_selection import learning_curve def plot_learning_curve(model, X, y, title): train_sizes, train_scores, val_scores = learning_curve( model, X, y, cv=5, scoring='r2', train_sizes=np.linspace(0.1, 1.0, 10) ) train_mean = np.mean(train_scores, axis=1) train_std = np.std(train_scores, axis=1) val_mean = np.mean(val_scores, axis=1) val_std = np.std(val_scores, axis=1) plt.figure(figsize=(8, 5)) plt.plot(train_sizes, train_mean, label='训练分数') plt.fill_between(train_sizes, train_mean - train_std, train_mean + train_std, alpha=0.2) plt.plot(train_sizes, val_mean, label='验证分数') plt.fill_between(train_sizes, val_mean - val_std, val_mean + val_std, alpha=0.2) plt.xlabel('训练样本数量') plt.ylabel('R²分数') plt.title(title) plt.legend() plt.show() # 分别绘制三种模型的学习曲线 plot_learning_curve(LinearRegression(), X_simple, y_simple, '线性回归学习曲线') plot_learning_curve(DecisionTreeRegressor(max_depth=5), X_simple, y_simple, '决策树学习曲线') 7.2 特征重要性分析与业务洞察 # 随机森林特征重要性分析(更稳健) rf = RandomForestRegressor(n_estimators=100, random_state=42) rf.fit(X_train_final, y_train_final) importance_df = pd.DataFrame({ 'feature': df_clean.drop(['PRICE'], axis=1).columns.tolist(), 'importance': rf.feature_importances_ }).sort_values('importance', ascending=False) plt.figure(figsize=(10, 6)) sns.barplot(data=importance_df, x='importance', y='feature') plt.title('随机森林特征重要性排序') plt.xlabel('重要性得分') plt.show() print("特征重要性排序:") print(importance_df) 7.3 处理类别特征与文本特征 # 演示类别特征处理:创建一个包含类别特征的合成数据集 np.random.seed(42) n_samples = 1000 # 数值特征 area = np.random.normal(100, 30, n_samples) rooms = np.random.randint(2, 6, n_samples) age = np.random.normal(30, 10, n_samples) # 类别特征 neighborhood = np.random.choice(['A', 'B', 'C'], n_samples, p=[0.3, 0.4, 0.3]) house_type = np.random.choice(['apartment', 'house', 'townhouse'], n_samples) # 目标变量(房价) price = 50 * area + 100 * rooms - 2 * age + \ np.where(neighborhood == 'A', 200, np.where(neighborhood == 'B', 100, 0)) + \ np.where(house_type == 'house', 150, np.where(house_type == 'townhouse', 80, 0)) + \ np.random.normal(0, 50, n_samples) # 创建DataFrame df_synth = pd.DataFrame({ 'area': area, 'rooms': rooms, 'age': age, 'neighborhood': neighborhood, 'house_type': house_type, 'price': price }) # 类别特征编码 from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer # 定义数值和类别特征 numeric_features = ['area', 'rooms', 'age'] categorical_features = ['neighborhood', 'house_type'] # 创建预处理管道 preprocessor = ColumnTransformer( transformers=[ ('num', StandardScaler(), numeric_features), ('cat', OneHotEncoder(drop='first'), categorical_features) ]) # 准备数据 X_synth = df_synth.drop('price', axis=1) y_synth = df_synth['price'] # 划分数据集 X_train_synth, X_test_synth, y_train_synth, y_test_synth = train_test_split( X_synth, y_synth, test_size=0.2, random_state=42 ) # 应用预处理 X_train_processed = preprocessor.fit_transform(X_train_synth) X_test_processed = preprocessor.transform(X_test_synth) # 训练模型 model_synth = LinearRegression() model_synth.fit(X_train_processed, y_train_synth) # 预测与评估 y_pred_synth = model_synth.predict(X_test_processed) print(f"\n处理类别特征后的模型R²: {r2_score(y_test_synth, y_pred_synth):.4f}") # 查看处理后的特征名称 cat_feature_names = preprocessor.named_transformers_['cat'].get_feature_names_out(categorical_features) all_features = numeric_features + list(cat_feature_names) print("\n处理后的特征:", all_features) print("模型系数:", model_synth.coef_) 第八部分:总结与最佳实践 8.1 算法选择决策指南 在实际项目中,选择哪种算法应基于以下考虑: 数据规模 :小数据集(<1000样本)优先考虑线性回归或决策树;大数据集可考虑梯度提升或神经网络 可解释性要求 :需要向业务方解释模型逻辑时,决策树或线性回归更合适 特征类型 :类别特征多时,决策树或经过编码的线性模型 预测精度 :精度优先时,集成方法(随机森林、梯度提升)通常表现更好 8.2 端到端项目流程总结 一个完整的机器学习项目应包含以下步骤: 问题定义 :明确预测目标和评估指标 数据收集与探索 :理解数据分布、缺失值、异常值 数据预处理 :清洗、特征工程、编码、标准化 模型选择与训练 :尝试多种算法,建立基线模型 模型评估 :使用合适的评估指标和交叉验证 参数调优 :网格搜索或随机搜索优化超参数 模型部署 :保存模型,构建预测API 监控与维护 :持续监控模型性能,定期重新训练 8.3 性能优化技巧 # 1. 使用Pipeline简化流程 from sklearn.pipeline import Pipeline # 创建完整的处理和建模管道 pipeline = Pipeline([ ('scaler', StandardScaler()), ('regressor', RandomForestRegressor(random_state=42)) ]) # 2. 使用RandomizedSearchCV进行更高效的参数搜索 from sklearn.model_selection import RandomizedSearchCV from scipy.stats import randint param_dist = { 'regressor__n_estimators': randint(50, 200), 'regressor__max_depth': randint(3, 15), 'regressor__min_samples_split': randint(2, 20) } random_search = RandomizedSearchCV( pipeline, param_distributions=param_dist, n_iter=20, cv=5, scoring='r2', random_state=42 ) random_search.fit(X_train_final, y_train_final) print("随机搜索最佳参数:", random_search.best_params_) print("最佳分数:", random_search.best_score_) 8.4 生产环境部署建议 模型持久化 :使用joblib或pickle保存模型 版本控制 :记录模型版本和训练数据版本 API构建 :使用Flask或FastAPI构建预测服务 性能监控 :记录预测延迟和准确率 数据漂移检测 :监控输入数据分布变化 # 模型持久化示例 import joblib # 保存模型和预处理器 joblib.dump(rf_model, 'house_price_model.pkl') joblib.dump(scaler_final, 'scaler.pkl') # 加载模型进行预测 loaded_model = joblib.load('house_price_model.pkl') loaded_scaler = joblib.load('scaler.pkl') 通过本文的详细讲解和完整代码示例,您应该已经掌握了使用scikit-learn进行回归分析的核心技能。从数据准备到模型部署的完整流程,以及三种经典算法的原理和实战技巧,将为您在实际工作中解决预测建模问题提供坚实的基础。记住,优秀的机器学习模型不仅需要算法知识,更需要对业务场景的深入理解和持续的实践优化。