Python使用Scikit-learn线性回归实战
准备工作和环境搭建:
1. 安装Python:在Python官网(https://www.python.org/downloads/)下载适合你操作系统的Python版本,并进行安装。
2. 安装Scikit-learn:打开命令提示符,输入以下命令以安装Scikit-learn:
pip install -U scikit-learn
3. 安装其他必要的类库:在本次实战中,我们还需要使用numpy、pandas和matplotlib类库,输入以下命令进行安装:
pip install numpy pandas matplotlib
依赖的类库:
1. numpy:用于进行数值计算和数组操作。
2. pandas:用于数据预处理和分析。
3. matplotlib:用于数据可视化。
4. scikit-learn:用于构建和训练机器学习模型。
数据集介绍:
本次实战使用的是Scikit-learn自带的波士顿房价数据集(Boston Housing Dataset),它是一个用于回归问题的经典数据集。
该数据集包含506个样本,每个样本有13个特征,如犯罪率、平均房间数等,目标变量是该地区房屋的中位数价格。
数据集下载网址:
Scikit-learn自带的数据集可以直接从它的服务器上下载,无需额外的下载链接。
样例数据和代码:
下面是一个使用Scikit-learn进行线性回归的完整样例代码:
python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# 加载波士顿房价数据集
boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['PRICE'] = boston.target
# 提取特征和目标变量
X = df.drop('PRICE', axis=1).values
y = df['PRICE'].values
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 构建线性回归模型
model = LinearRegression()
# 训练模型
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
# 评估
mse = mean_squared_error(y_test, y_pred)
print('Mean Squared Error:', mse)
# 可视化结果
plt.scatter(y_test, y_pred)
plt.plot([y.min(), y.max()], [y.min(), y.max()], '--', color='red', linewidth=2)
plt.xlabel('True Price')
plt.ylabel('Predicted Price')
plt.title('Boston Housing Dataset - Linear Regression')
plt.show()
运行以上代码,即可进行线性回归实战并得到结果的可视化展示。
总结:
本次实战介绍了如何使用Scikit-learn进行线性回归,并以波士顿房价数据集为例进行了模型训练、预测和评估。通过这个实例,我们可以学习到如何使用Scikit-learn构建机器学习模型的基本流程,以及使用相关类库进行数据处理和可视化。