为什么我不能使用 SVM 和 KNN 预测新数据?

Why can't I predict new data using SVM and KNN?

我是机器学习的新手,我刚刚用 sklearn 学习了 KNN 和 SVM。如何使用 SVM 或 KNN 对新数据进行预测?我都尝试过做出预测。只有当数据已知时,他们才能做出好的预测。但是当我尝试预测新数据时,他们给出了错误的预测。

这是我的代码:

import numpy as np
from sklearn import svm

x=np.array([[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11]], dtype=np.float64)
y=np.array([2,3,4,5,6,7,8,9,10,11,12], dtype=np.float64)

clf = svm.SVC(kernel='linear')
clf.fit(x, y)
print(clf.predict([[20]]))
print(clf.score(x, y))

0输出:

[12.]
1.0

只要要预测的数据在 x_train 范围内,此代码就能做出很好的预测。但是当我尝试预测例如 20 或超出范围 x_train 的任何值时,输出将始终为 12,即 y 的最后一个元素。我不知道我在代码中做错了什么。

您必须使用回归模型而不是分类模型。对于基于 svm 的回归,使用 svm.SVR()

import numpy as np
from sklearn import svm

x=np.array([[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11]], dtype=np.float64)
y=np.array([2,3,4,5,6,7,8,9,10,11,12], dtype=np.float64)

clf = svm.SVR(kernel='linear')
clf.fit(x, y)
print(clf.predict([[50]]))
print(clf.score(x, y))

输出:

[50.12]
0.9996

代码的行为与支持向量机在数学上描述的一样。

您必须了解算法如何解释您的数据。你有 11 个数据点,你给每个数据点一个不同的 class。 SVM 最终基本上将数字线分成 11 段(对于您定义的 11 classes):

data = [(x, clf.predict([[x]])[0]) for x in np.linspace(1, 20, 300)] plt.scatter([p[0] for p in data], [p[1] for p in data]) plt.show()

AILearning 的答案告诉您如何解决您给定的玩具问题,但请确保您也理解为什么您的代码没有按照您认为的那样进行。对于任何有限的示例集,都有无限多的函数可以拟合数据。您的根本问题是混淆了回归和 class化。从它的声音来看,你想要一个简单的回归模型来从数据点推断一个拟合函数,但是你的代码是一个class化模型。