Scikit-learn 线性回归

scikit-learnBeginner
立即练习

介绍

在本实验中,你将学习使用最流行的 Python 库之一 scikit-learn 构建机器学习模型的基础知识。我们将重点关注线性回归(Linear Regression),这是一种基础但强大的算法,用于预测连续值,例如价格或温度。

我们的目标是构建一个能够预测加利福尼亚州各区域房价中位数的模型。我们将使用加利福尼亚州住房数据集(California housing dataset),该数据集已包含在 scikit-learn 中,非常方便。

在本实验中,你将学习如何:

  • scikit-learn 加载数据集。
  • 准备和拆分数据以进行训练和测试。
  • 创建并训练一个线性回归模型。
  • 使用训练好的模型进行预测。

你将在 WebIDE 中完成所有任务。让我们开始吧!

这是一个实验(Guided Lab),提供逐步指导来帮助你学习和实践。请仔细按照说明完成每个步骤,获得实际操作经验。根据历史数据,这是一个 中级 级别的实验,完成率为 59%。获得了学习者 92% 的好评率。

使用 datasets.fetch_california_housing() 加载加州房价数据集

在此步骤中,我们将开始加载模型所需的数据集。scikit-learn 附带了几个内置数据集,非常适合学习和练习。我们将使用加利福尼亚州住房数据集。

首先,我们需要创建一个 Python 脚本。一个名为 main.py 的文件已在 ~/project 目录中为你创建。你可以在 WebIDE 左侧的文件浏览器中找到它。

打开 main.py 并添加以下代码。此代码导入了必要的库(来自 sklearn.datasetsfetch_california_housingpandas)并加载了数据集。我们将使用 pandas 将数据转换为 DataFrame,这是一种易于查看和操作的表格数据结构。

请将以下代码添加到 main.py

import pandas as pd
from sklearn.datasets import fetch_california_housing

## Load the California housing dataset
california = fetch_california_housing()

## Create a DataFrame
california_df = pd.DataFrame(california.data, columns=california.feature_names)
california_df['MedHouseVal'] = california.target

## Print the first 5 rows of the DataFrame
print("California Housing Dataset:")
print(california_df.head())

现在,让我们运行脚本以查看输出。在 WebIDE 中打开一个终端(你可以使用 "Terminal" -> "New Terminal" 菜单)并执行以下命令:

python3 main.py

你应该会在控制台中看到数据集的前五行打印出来。MedHouseVal 列是我们的目标变量,代表加利福尼亚州各区域的房价中位数,以十万美元为单位($100,000)。

California Housing Dataset:
   MedInc  HouseAge  AveRooms  AveBedrms  Population  AveOccup  Latitude  Longitude  MedHouseVal
0  8.3252      41.0  6.984127   1.023810       322.0  2.555556     37.88    -122.23        4.526
1  8.3014      21.0  6.238137   0.971880      2401.0  2.109842     37.86    -122.22        3.585
2  7.2574      52.0  8.288136   1.073446       496.0  2.802260     37.85    -122.24        3.521
3  5.6431      52.0  5.817352   1.073059       558.0  2.547945     37.85    -122.25        3.413
4  3.8462      52.0  6.281853   1.081081       565.0  2.181467     37.85    -122.25        3.422

使用 sklearn.model_selection 中的 train_test_split 将数据划分为训练集和测试集

在此步骤中,我们将准备数据以进行训练过程。机器学习的一个关键部分是在模型从未见过的数据上进行评估。为此,我们将数据集拆分为两部分:训练集和测试集。模型将从训练集中学习,然后我们将使用测试集来查看其性能如何。

首先,我们需要将特征(输入变量,X)与目标(我们想要预测的值,y)分开。在我们的例子中,X 将是除 MedHouseVal 之外的所有列,而 y 将是 MedHouseVal 列。

然后,我们将使用 sklearn.model_selection 中的 train_test_split 函数来执行拆分。

将以下代码追加到你的 main.py 文件中。

from sklearn.model_selection import train_test_split

## Prepare the data
X = california_df.drop('MedHouseVal', axis=1)  ## Features (input variables)
y = california_df['MedHouseVal']  ## Target variable (what we want to predict)

## Split the data into training and testing sets
## test_size=0.2: Reserve 20% of data for testing, 80% for training
## random_state=42: Ensures reproducible splits (same result every run)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

## Print the shapes of the new datasets to confirm the split
print("\n--- Data Split ---")
print("X_train shape:", X_train.shape)  ## Training features
print("X_test shape:", X_test.shape)    ## Test features
print("y_train shape:", y_train.shape)  ## Training target values
print("y_test shape:", y_test.shape)    ## Test target values

现在,请再次从终端运行脚本:

python3 main.py

你将在 DataFrame 下方看到新创建的训练集和测试集的形状打印出来。这证实了数据已正确拆分。

--- Data Split ---
X_train shape: (16512, 8)
X_test shape: (4128, 8)
y_train shape: (16512,)
y_test shape: (4128,)

初始化 sklearn.linear_model 中的 LinearRegression 模型

在此步骤中,我们将创建我们的线性回归模型。scikit-learn 使此过程变得异常简单。我们只需要从 sklearn.linear_model 模块导入 LinearRegression 类,然后创建一个该类的实例。

这个实例是一个包含线性回归算法的对象。线性回归通过数据点找到最佳拟合线,使用公式:y = mx + b,其中 m 是每个特征的系数(权重),b 是截距。这里我们使用默认参数,它们在大多数基本情况下效果都很好。

Linear Regression Formula
图 1:线性回归公式 y = mx + b,其中 m 是斜率,b 是截距

将以下代码添加到你的 main.py 文件中。这将导入 LinearRegression 类并创建一个模型对象。

from sklearn.linear_model import LinearRegression

## 初始化线性回归模型
model = LinearRegression()

## 打印模型以确认其已创建
print("\n--- Model Initialized ---")
print(model)

再次从终端运行你的 main.py 脚本:

python3 main.py

输出现在将包含一行显示 LinearRegression 对象。这确认了模型已成功初始化。

--- Model Initialized ---
LinearRegression()

使用 model.fit(X_train, y_train) 拟合模型

在此步骤中,我们将训练我们的模型。这个过程通常被称为将模型“拟合”到数据。在拟合过程中,模型学习特征(X_train)与目标变量(y_train)之间的关系。对于线性回归,这意味着找到每个特征的最佳系数,以最好地预测目标。

我们将使用模型对象的 fit() 方法,并将我们的训练数据作为参数传递。

将以下代码追加到你的 main.py 文件中。

## Fit (train) the model on the training data
## The fit() method learns the relationship between features (X_train) and target (y_train)
## It calculates optimal coefficients for each feature and the intercept using least squares optimization
model.fit(X_train, y_train)

## After fitting, the model has learned the coefficients and intercept.
## The intercept represents the predicted value when all features are zero
print("\n--- Model Trained ---")
print("Intercept:", model.intercept_)

现在,请在终端执行脚本:

python3 main.py

脚本运行后,你将在输出中看到一个新部分,显示线性回归模型的截距。截距是在所有特征值为零时预测的值。看到这里有一个数值确认模型已成功在数据上训练。

--- Model Trained ---
Intercept: -37.023277706064185

使用 model.predict(X_test) 在测试数据上进行预测

在最后这个步骤中,我们将使用我们训练好的模型进行预测。这是构建预测模型的最终目标。我们将使用模型在训练期间未见过的数据(X_test)来评估其性能。

我们将使用我们训练好的模型对象的 predict() 方法,并将测试特征(X_test)作为参数传递。该方法将返回一个目标变量的预测值数组。

将以下代码追加到你的 main.py 文件中。

## Make predictions on the test data
## The predict() method uses the learned coefficients and intercept to calculate predictions
## Formula: prediction = intercept + (coeff1 * feature1) + (coeff2 * feature2) + ...
predictions = model.predict(X_test)

## Print the first 5 predictions (values are in $100,000 units)
print("\n--- Predictions ---")
print(predictions[:5])

现在,请最后一次从终端运行完整的脚本:

python3 main.py

输出现在将包括测试集的前五个预测房价。这些值是我们模型根据 X_test 中的特征认为中位数房价应该是什么。你可以将这些预测值与 y_test 中的实际值进行概念上的比较,以评估模型的准确性。

--- Predictions ---
[0.71912284 1.76401657 2.70965883 2.83892593 2.60465725]

恭喜!你已成功使用 scikit-learn 构建、训练并使用了线性回归模型。

总结

在本实验中,你已完成了使用 scikit-learn 构建基础机器学习模型的整个工作流程。

你首先加载了加州房价数据集,并使用 pandas 对其进行了准备。然后,你学习了将数据分割为训练集和测试集的重要性,并使用 train_test_split 执行了分割。

之后,你初始化了一个 LinearRegression 模型,使用 fit() 方法在训练数据上对其进行了训练,最后使用训练好的模型通过 predict() 方法在未见过的数据上进行预测。

本次实验为你打下了坚实的 scikit-learn 基础。接下来,你可以探索更高级的主题,例如:

  • 模型评估:计算均方误差(MSE)或 R 方等指标来衡量模型准确性
  • 特征缩放:标准化或归一化特征以获得更好的性能
  • 正则化:使用 Ridge 或 Lasso 回归来防止过拟合
  • 交叉验证:使用 k 折交叉验证进行更稳健的评估
  • 其他算法:尝试随机森林(Random Forest)、支持向量机(Support Vector Machines)或神经网络(Neural Networks)

Summary

In this lab, you have completed the entire workflow for building a basic machine learning model using scikit-learn.

You started by loading the California housing dataset and preparing it using pandas. Then, you learned the importance of splitting your data into training and testing sets and performed the split using train_test_split.

Following that, you initialized a LinearRegression model, trained it on your training data using the fit() method, used the trained model to make predictions on unseen test data with the predict() method, and finally visualized the results to understand your model's performance.

This lab provides a solid foundation in scikit-learn. From here, you can explore more advanced topics such as:

  • Model evaluation: Calculate metrics like Mean Squared Error (MSE) or R-squared to measure model accuracy
  • Data visualization: Create more advanced plots like residual plots, feature importance charts, or correlation matrices
  • Feature scaling: Standardize or normalize features for better performance
  • Regularization: Use Ridge or Lasso regression to prevent overfitting
  • Cross-validation: More robust evaluation using k-fold cross-validation
  • Other algorithms: Try Random Forest, Support Vector Machines, or Neural Networks