基于线性回归的二手车售价预测模型

Author Avatar
小包
发表:2025-09-11 15:31:00
修改:2025-09-11 15:31:00

文档目标: 本指南旨在通过一个实际案例,指导用户使用 Python 中的 pandasscikit-learn 库,完成一个基础的机器学习项目。我们将从数据加载、预处理开始,一直到模型训练和评估。

项目背景: 我们将使用 CarResale.csv 数据集,该数据集包含了二手车的各项属性(如年份、行驶里程、燃料类型等)及其最终售价。我们的任务是构建一个线性回归模型,根据车辆的属性来预测其售价。

技术栈:

  • Python 3.x
  • Jupyter Notebook (在 VS Code 或其他环境中)
  • 核心库:pandas, numpy, scikit-learn

步骤 1:环境设置与数据导入 (Setup and Data Import)

在开始之前,请确保你的 Python 环境中已安装必要的库。如果尚未安装,请在终端中执行以下命令:

pip install pandas numpy scikit-learn

1.1 导入库 (Import Libraries) 在 Notebook 的第一个单元格中,导入所有本项目需要的模块。

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline

1.2 加载数据集 (Load the Dataset) 使用 pandasread_csv 函数将数据集加载到一个 DataFrame 对象中。请确保 .csv 文件与你的 .ipynb 文件位于同一目录下。使用 .head() 方法可以快速预览数据的前几行,以验证数据是否加载正确。

# Load data from the CSV file
df = pd.read_csv('CarResale.csv')

# Display the first 5 rows of the dataframe
df.head()

步骤 2:数据探索与预处理 (Data Exploration and Preprocessing)

这是机器学习项目中至关重要的一步。我们需要理解数据、清理数据,并为模型训练做好准备。

2.1 数据勘查 (Data Inspection) 使用 .info() 方法可以获取数据集的概览,包括每列的名称、非空值的数量以及数据类型。这能帮助我们快速识别存在缺失值的列。

# Get a concise summary of the dataframe
df.info()

2.2 处理缺失值 (Handling Missing Values).info() 的输出中,我们可以发现某些列(如 mileage, seats 等)存在缺失值。机器学习模型通常无法处理缺失数据。对于这个基础项目,我们采取最简单的策略:删除任何包含缺失值的行

# Drop rows with any missing values
df.dropna(inplace=True)

注:inplace=True 表示直接在原始 DataFrame 上进行修改。

2.3 定义特征与目标 (Define Features and Target) 我们需要明确地告诉模型,哪些数据是用来进行预测的“输入”(特征, X),哪个数据是我们想要预测的“输出”(目标, y)。

# Define the columns to be used as features
features = ['year', 'km_driven', 'fuel', 'seller_type', 'transmission', 'owner', 'seats', 'mileage', 'engine_size', 'brake_horsepower']
# Define the target variable
target = 'selling_price'

# Create the feature matrix (X) and target vector (y)
X = df[features]
y = df[target]

2.4 区分特征类型 (Separate Feature Types) 特征可以分为数值型(可以直接用于计算)和类别型(文本类型,需要转换)。我们需要将它们分开,以便后续进行不同的预处理。

# Identify categorical and numerical feature names
categorical_features = ['fuel', 'seller_type', 'transmission', 'owner']
numerical_features = ['year', 'km_driven', 'seats', 'mileage', 'engine_size', 'brake_horsepower']

步骤 3:构建模型流水线 (Building the Model Pipeline)

为了使预处理步骤和模型训练过程更加规范和高效,我们使用 scikit-learnPipeline

3.1 创建预处理器 (Create Preprocessor) ColumnTransformer 是一个强大的工具,它允许我们对不同的列应用不同的转换。

  • 对于数值型特征,我们保持原样 ('passthrough')。
  • 对于类别型特征,我们应用 OneHotEncoder。这个编码器会将每个类别(例如 fuel 列中的 'Petrol' 和 'Diesel')转换成新的二进制列。handle_unknown='ignore' 参数确保在测试数据中遇到训练时未见过的类别时,程序不会报错。
preprocessor = ColumnTransformer(
    transformers=[
        ('num', 'passthrough', numerical_features),
        ('cat', OneHotEncoder(handle_unknown='ignore'), categorical_features)
    ])

3.2 组装流水线 (Assemble the Pipeline) Pipeline 将预处理步骤和最终的模型(这里是 LinearRegression)串联起来。当我们对 Pipeline 调用 .fit() 时,数据会依次通过每个步骤。

model_pipeline = Pipeline(steps=[('preprocessor', preprocessor),
                                 ('regressor', LinearRegression())])

步骤 4:模型训练 (Model Training)

4.1 划分数据集 (Split the Data) 将数据划分为训练集和测试集是评估模型性能的标准做法。我们使用 80% 的数据来训练模型,剩下 20% 的数据用来测试其泛化能力。random_state 参数用于确保每次划分的结果都一样,保证了实验的可复现性。

# Split the data into training (80%) and testing (20%) sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

4.2 训练模型 (Fit the Model) 调用流水线的 .fit() 方法,传入训练数据 X_trainy_train。流水线会自动处理所有预处理步骤并训练线性回归模型。

# Train the entire pipeline on the training data
model_pipeline.fit(X_train, y_train)

print("Model training completed!")

步骤 5:模型评估 (Model Evaluation)

模型训练完成后,我们需要检验它在“新”数据(即测试集)上的表现。

5.1 进行预测 (Make Predictions) 使用训练好的流水线对测试集 X_test 进行预测。

# Use the trained pipeline to make predictions on the test set
y_pred = model_pipeline.predict(X_test)

5.2 计算性能指标 (Calculate Performance Metrics) 均方根误差 (RMSE) 是回归任务中最常用的评估指标之一。它表示模型预测值与真实值之间误差的平方和的均值的平方根。RMSE 的值越小,说明模型的预测越精确。

# Calculate the Root Mean Squared Error (RMSE)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
print(f"Root Mean Squared Error (RMSE): {rmse}")

5.3 结果可视化 (Visualize Results) 为了更直观地感受模型的效果,我们可以创建一个新的 DataFrame,将真实价格和模型的预测价格并列进行比较。

# Create a DataFrame to compare actual and predicted prices
results_df = pd.DataFrame({'Actual Price': y_test, 'Predicted Price': y_pred})

# Display the first 10 rows of the comparison
print("\nComparison of Predictions (first 10 rows):")
results_df.head(10)

总结 (Conclusion):

至此,你已经成功构建、训练并评估了一个二手车售价预测模型。请确保你的 .ipynb 文件中包含了以上所有步骤的代码和输出结果,然后将其保存并提交。

这个项目是一个入门级的实例,你可以基于此进行更深入的探索,例如尝试更复杂的模型(如 RandomForestRegressor)、进行更精细的特征工程或处理数据中的异常值。

评论