机器学习项目的核心不是算法本身,而是从数据到模型部署的完整流程。本文以加州房价数据集为例,使用Python和scikit-learn构建一个端到端的回归预测模型,涵盖数据探索、特征工程、模型训练、超参数调优与特征重要性分析。
pip install scikit-learn pandas matplotlib xgboost使用sklearn内置的加州房价数据集:
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
housing = fetch_california_housing()
X = pd.DataFrame(housing.data, columns=housing.feature_names)
y = housing.target # 房价中位数(单位:十万美元)
print(X.shape, y.shape)
print(X.head())检查缺失值、统计信息,并进行数据分割:
print(X.isnull().sum()) # 无缺失
print(X.describe())
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)观察目标变量分布:
import matplotlib.pyplot as plt
plt.hist(y, bins=50)
plt.title("房价分布")
plt.show()房价分布右偏,可对目标进行对数变换(可选,本示例保持原样以简化)。
创建几个组合特征以提升模型表现:
# 构造新特征:每间房的平均房间数、人口密度等
X_train['rooms_per_household'] = X_train['AveRooms'] / X_train['AveOccup']
X_train['bedrooms_per_room'] = X_train['AveBedrms'] / X_train['AveRooms']
X_train['population_per_household'] = X_train['Population'] / X_train['AveOccup']
X_test['rooms_per_household'] = X_test['AveRooms'] / X_test['AveOccup']
X_test['bedrooms_per_room'] = X_test['AveBedrms'] / X_test['AveRooms']
X_test['population_per_household'] = X_test['Population'] / X_test['AveOccup']训练三种模型并对比交叉验证分数:
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score
models = {
"线性回归": LinearRegression(),
"决策树": DecisionTreeRegressor(random_state=42),
"随机森林": RandomForestRegressor(n_estimators=100, random_state=42)
}
for name, model in models.items():
scores = cross_val_score(model, X_train, y_train, cv=5,
scoring='neg_mean_squared_error')
rmse = np.sqrt(-scores.mean())
print(f"{name}: RMSE = {rmse:.4f}")输出表明随机森林通常优于线性回归和单棵决策树。由于数据集规模不大,也可尝试XGBoost:
from xgboost import XGBRegressor
xgb = XGBRegressor(n_estimators=100, learning_rate=0.1, random_state=42)
scores = cross_val_score(xgb, X_train, y_train, cv=5, scoring='neg_mean_squared_error')
print(f"XGBoost: RMSE = {np.sqrt(-scores.mean()):.4f}")使用GridSearchCV对随机森林进行调优:
from sklearn.model_selection import GridSearchCV
param_grid = {
'n_estimators': [100, 200],
'max_depth': [None, 10, 20],
'min_samples_split': [2, 5]
}
rf = RandomForestRegressor(random_state=42)
grid_search = GridSearchCV(rf, param_grid, cv=3,
scoring='neg_mean_squared_error', n_jobs=-1)
grid_search.fit(X_train, y_train)
print("最佳参数:", grid_search.best_params_)
best_model = grid_search.best_estimator_在测试集上评估最终模型:
from sklearn.metrics import mean_squared_error, r2_score
y_pred = best_model.predict(X_test)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
print(f"测试集 RMSE: {rmse:.4f}, R²: {r2:.4f}")分析特征重要性:
feature_importances = pd.Series(
best_model.feature_importances_, index=X_train.columns
).sort_values(ascending=False)
print(feature_importances.head(10))
plt.figure(figsize=(8,5))
feature_importances.head(10).plot(kind='bar')
plt.title('特征重要性 Top 10')
plt.show()本文展示了机器学习项目的完整流程:数据加载与探索、特征工程、模型比较、超参数调优和评估。实际项目中还需注意数据泄漏、特征缩放(对线性模型)、模型可解释性等问题。掌握这一套流程后,开发者可以将同一框架应用于分类、时间序列预测等更广泛的业务场景。机器学习的关键在于严谨的实验设计和持续迭代,而不是盲目堆砌算法。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。