房价预测模型:使用加州或埃姆斯房价数据集
如何修改房价预测模型代码
如果你想使用提供的替代数据集(加利福尼亚房价数据集或埃姆斯房价数据集)来进行房价预测,可以修改代码如下:
使用加利福尼亚房价数据集
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error, mean_absolute_error
import matplotlib.pyplot as plt
# 加载加利福尼亚房价数据集
housing = fetch_california_housing(as_frame=True)
# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(housing.data, housing.target, test_size=0.2, random_state=42)
# 创建SVR模型并进行训练
model = SVR(kernel='poly')
model.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = model.predict(X_test)
# 计算均方误差和平均绝对误差
mse = mean_squared_error(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
print('均方误差:', mse)
print('平均绝对误差:', mae)
# 绘制实际值和预测值的图表
plt.scatter(range(len(y_test)), y_test, color='b', label='Actual')
plt.scatter(range(len(y_pred)), y_pred, color='r', label='Predict')
plt.xlabel('Samples')
plt.ylabel('Price')
plt.legend()
plt.show()
使用埃姆斯房价数据集
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error, mean_absolute_error
import matplotlib.pyplot as plt
# 加载埃姆斯房价数据集
housing = fetch_openml(name='house_prices', as_frame=True)
# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(housing.data, housing.target, test_size=0.2, random_state=42)
# 创建SVR模型并进行训练
model = SVR(kernel='poly')
model.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = model.predict(X_test)
# 计算均方误差和平均绝对误差
mse = mean_squared_error(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
print('均方误差:', mse)
print('平均绝对误差:', mae)
# 绘制实际值和预测值的图表
plt.scatter(range(len(y_test)), y_test, color='b', label='Actual')
plt.scatter(range(len(y_pred)), y_pred, color='r', label='Predict')
plt.xlabel('Samples')
plt.ylabel('Price')
plt.legend()
plt.show()
使用上述代码,你可以使用加利福尼亚房价数据集或埃姆斯房价数据集来进行房价预测,并计算预测结果的均方误差和平均绝对误差。同时,将绘制实际值和预测值的图表。
请注意,埃姆斯房价数据集可能需要一些时间来下载和加载。如果出现下载失败或加载错误,请确保你的网络连接正常,并尝试重新运行代码。
原文地址: https://www.cveoy.top/t/topic/7fz 著作权归作者所有。请勿转载和采集!