支持向量机/逻辑回归:关于波士顿房价数据的基准结果有哪些?

4 投票
1 回答
3142 浏览
提问于 2025-04-17 14:06

我想测试一下我用sklearn库实现的支持向量回归模型,打算用sklearn自带的波士顿房价数据集(sklearn.datasets.load_boston)来跑一跑。

我尝试了好一阵子,调试了不同的正则化和管道参数,还随机选择了一些案例进行交叉验证,但每次预测的结果都是一条平直的线,这让我很困惑。更奇怪的是,当我用同样来自sklearn.datasets包的糖尿病数据集(load_diabetes)时,预测结果却要好得多。

这是我用来测试的代码:

import numpy as np
from sklearn.svm import SVR
from matplotlib import pyplot as plt
from sklearn.datasets import  load_boston
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression

# data = load_diabetes()
data = load_boston()
X = data.data
y = data.target

# prepare the training and testing data for the model
nCases = len(y)
nTrain = np.floor(nCases / 2)
trainX = X[:nTrain]
trainY = y[:nTrain]
testX  = X[nTrain:]
testY = y[nTrain:]

svr = SVR(kernel='rbf', C=1000)
log = LinearRegression()

# train both models
svr.fit(trainX, trainY)
log.fit(trainX, trainY)

# predict test labels from both models
predLog = log.predict(testX)
predSvr = svr.predict(testX)

# show it on the plot
plt.plot(testY, testY, label='true data')
plt.plot(testY, predSvr, 'co', label='SVR')
plt.plot(testY, predLog, 'mo', label='LogReg')
plt.legend()
plt.show()

现在我想问的是:有没有人成功用这个数据集和支持向量回归模型进行过实验,或者知道我哪里出错了?非常感谢大家的建议!

这是我运行上面代码后得到的结果:

运行load_boston数据集的结果

1 个回答

8

把内核从 rbf 改成 linear 可以解决这个问题。如果你想继续使用 rbf,可以尝试调整一些不同的参数,特别是 gamma。默认的 gamma 值(1/# 特征)对你的情况来说太大了。

enter image description here

这是我为线性内核 SVR 使用的参数:

svr = SVR(kernel='linear', C=1.0, epsilon=0.2)

我画出了训练数据标签和测试数据标签的图。你可能会注意到训练数据的分布不均匀。这导致模型在 5 < y < 15 的时候缺少训练数据。所以我对数据进行了随机打乱,并把训练数据设置为使用你数据的66%。

nTrain = np.floor(nCases *2.0 / 3.0)
import random
ids = range(nCases)
random.shuffle(ids)

trainX,trainY,testX,testY = [],[],[],[]
for i, idx in enumerate(ids):
    if i < nTrain:
        trainX.append(X[idx])
        trainY.append(y[idx])
    else:
        testX.append(X[idx])
        testY.append(y[idx])

这是我得到的结果:

enter image description here

从视觉上看,这两个回归模型在预测误差方面看起来更好了。

这里有一个使用 rbf 内核的 SVR 的工作示例:

svr = SVR(kernel='rbf',  C=1.0, epsilon=0.2, gamma=.0001)

结果看起来是这样的:

enter image description here

撰写回答