用SVR模型完成对Boston房价的回归预测

用SVR模型完成对Boston房价的回归预测

实验说明

实验要求:使用SVR模型实现对波士顿房价的预测 (load_boston),并使用r2-score 对回归结果评测。

  • 实验环境:Pycharm
  • Python版本:3.6
  • 需要的第三方库:sklearn

实验代码

同样地,这里 SVR 模型采用的是高斯核函数 kernel=‘rbf’,惩罚系数 C=1,epsilon=0.2。

我们采用以下四项指标来进行评价:

  • 平均绝对误差 MAE
  • 均方误差 MSE
  • 解释方差分 EVS
  • R2得分 R2_Score

有关 SVR 模型的参数以及如何选择, 可以参考这篇博客 sklearn.svm.SVR的参数介绍

from sklearn.datasets import load_boston
from sklearn.svm import SVR
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_absolute_error,mean_squared_error,explained_variance_score,r2_score
from sklearn.model_selection import train_test_split
import numpy as np
#加载数据集
boston=load_boston()
x=boston.data
y=boston.target

# 拆分数据集
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=10)
# 预处理
y_train = np.array(y_train).reshape(-1, 1)
y_test = np.array(y_test).reshape(-1, 1)
x_train = StandardScaler().fit_transform(x_train)
x_test = StandardScaler().fit_transform(x_test)
y_train = StandardScaler().fit_transform(y_train).ravel()
y_test = StandardScaler().fit_transform(y_test).ravel()

#创建svR实例
svr=SVR(C=1, kernel='rbf', epsilon=0.2)
svr=svr.fit(x_train,y_train)
#预测
svr_predict=svr.predict(x_test)
#评价结果
mae = mean_absolute_error(y_test, svr_predict)
mse = mean_squared_error(y_test, svr_predict)
evs = explained_variance_score(y_test, svr_predict)
r2 = r2_score(y_test, svr_predict)
print("MAE:", mae)
print("MSE:", mse)
print("EVS:", evs)
print("R2:", r2)

从结果中可以看到,R2得分还是比较可以的,达到了 0.80。
m1

参数优化

同理,我们继续采用网格参数搜索的方式,核函数依然选择高斯核函数,我们针对 惩罚系数 C 和核函数系数 gamma ,以及 epsilon 进行调参。

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVR
from sklearn.metrics import mean_absolute_error, mean_squared_error, explained_variance_score, r2_score
import numpy as np

# 加载数据集
boston_data = load_boston()
# print(boston_data)

# 拆分数据集
x = boston_data.data
y = boston_data.target
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=10)
# 预处理
y_train = np.array(y_train).reshape(-1, 1)
y_test = np.array(y_test).reshape(-1, 1)
x_train = StandardScaler().fit_transform(x_train)
x_test = StandardScaler().fit_transform(x_test)
y_train = StandardScaler().fit_transform(y_train).ravel()
y_test = StandardScaler().fit_transform(y_test).ravel()

# 设置超参数
C = [0.1, 0.2, 0.5, 0.8, 0.9, 1, 2, 5, 10]
kernel = 'rbf'
gamma = [0.001, 0.01, 0.1, 0.2, 0.5, 0.8]
epsilon = [0.01, 0.05, 0.1, 0.2, 0.5, 0.8]
# 参数字典
params_dict = {
    'C': C,
    'gamma': gamma,
    'epsilon': epsilon
}

# 创建SVR实例
svr = SVR()

# 网格参数搜索
gsCV = GridSearchCV(
    estimator=svr,
    param_grid=params_dict,
    n_jobs=2,
    scoring='r2',
    cv=6
)
gsCV.fit(x_train, y_train)
# 输出参数信息
print("最佳度量值:", gsCV.best_score_)
print("最佳参数:", gsCV.best_params_)
print("最佳模型:", gsCV.best_estimator_)

# 用最佳参数生成模型
svr = SVR(C=gsCV.best_params_['C'], kernel=kernel, gamma=gsCV.best_params_['gamma'],
          epsilon=gsCV.best_params_['epsilon'])

# 获取在训练集的模型
svr.fit(x_train, y_train)

# 预测结果
svr_predict = svr.predict(x_test)

# 模型评测
mae = mean_absolute_error(y_test, svr_predict)
mse = mean_squared_error(y_test, svr_predict)
evs = explained_variance_score(y_test, svr_predict)
r2 = r2_score(y_test, svr_predict)
print("MAE:", mae)
print("MSE:", mse)
print("EVS:", evs)
print("R2:", r2)

从结果上可以看出,调优的参数还是起了一点作用,R2得分变为了 0.84。
m2

  • 17
    点赞
  • 207
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
好的,以下是一个简单的Python示例,使用SVR来做回归预测,并进行模型和效果可视化。 首先,我们需要导入所需的库和数据集。这里我们使用sklearn自带的波士顿房价数据集。 ```python from sklearn.datasets import load_boston from sklearn.svm import SVR from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score import matplotlib.pyplot as plt # 加载数据集 boston = load_boston() # 划分数据集 X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, random_state=42) ``` 接下来,我们使用SVR来训练模型,并进行预测。 ```python # 初始化SVR svr = SVR(kernel='linear', C=1, epsilon=0.1) # 训练模型 svr.fit(X_train, y_train) # 预测结果 y_pred = svr.predict(X_test) ``` 然后,我们可以使用r2_score来评估模型的性能。 ```python # 评估模型性能 r2 = r2_score(y_test, y_pred) print('R2 score: {:.2f}'.format(r2)) ``` 最后,我们可以使用matplotlib来可视化预测结果与真实值的对比。 ```python # 可视化预测结果 plt.scatter(y_test, y_pred) plt.plot([0, 50], [0, 50], '--k') plt.xlabel('True values') plt.ylabel('Predictions') plt.tight_layout() plt.show() ``` 完整代码如下: ```python from sklearn.datasets import load_boston from sklearn.svm import SVR from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score import matplotlib.pyplot as plt # 加载数据集 boston = load_boston() # 划分数据集 X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, random_state=42) # 初始化SVR svr = SVR(kernel='linear', C=1, epsilon=0.1) # 训练模型 svr.fit(X_train, y_train) # 预测结果 y_pred = svr.predict(X_test) # 评估模型性能 r2 = r2_score(y_test, y_pred) print('R2 score: {:.2f}'.format(r2)) # 可视化预测结果 plt.scatter(y_test, y_pred) plt.plot([0, 50], [0, 50], '--k') plt.xlabel('True values') plt.ylabel('Predictions') plt.tight_layout() plt.show() ``` 注意:这只是一个简单的示例,实际应用中需要根据具体情况进行参数调整和模型优化。
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值