我是机器学习的新手,我刚刚学习了使用sklearn的KNN和SVM。我如何使用SVM或KNN对新数据进行预测?我尝试过这两种方法进行预测。它们只有在数据已知的情况下才能做出良好的预测。但是当我尝试预测新数据时,它们给出的预测是不正确的。
这是我的代码:
import numpy as npfrom sklearn import svmx=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))
输出:
[12.]1.0
只要预测的数据在x_train的范围内,这段代码就能做出良好的预测。但是当我尝试预测例如20,或者任何超过x_train范围的数据时,输出总是12,这是y的最后一个元素。我不知道我在代码中做错了什么。
回答:
你需要使用回归模型而不是分类模型。对于基于svm的回归,请使用svm.SVR()
import numpy as npfrom sklearn import svmx=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