一、题目说明:
1)根据训练样本训练“微型车”售价预测模型,预测目标字段为“price”,算法模型可自由选择;
2)使用tran_test_split方法将train_price.csv划分成训练样本和测试样本,且train_test_split方法中的random_state参数用自己的学号的后4位;
3)只需筛选训练样本中车身类型(bodyType字段)为“微型车”的样本训练模型;其余特征可自由选择;
4)用R2评估模型在测试样本上的效果 - sklearn.metrics.r2_score;
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
df = pd.read_csv('train_price.csv')
# 筛选bodyType为'微型车'的样本
df = df[df['bodyType'] == '微型车']
# 选择price作为目标变量,yearMade、modelId作为特征变量
X = df[['yearMade', 'modelId']]
y = df['price']
# 使用train_test_split划分,random_state为学号后4位
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=1234)
# 训练线性回归模型
lr = LinearRegression()
lr.fit(X_train, y_train)
# 预测测试样本并计算R2
y_pred = lr.predict(X_test)
r2 = r2_score(y_test, y_pred)
print('R2值为:', r2)