我正在尝试使用生成的数据集运行SVM线性内核。我的数据集有5000行和4列:
CL_scaled.head()[screenshot of data frame][1]
我把数据分成20%的测试和80%的训练:
train, test = train_test_split(CL_scaled, test_size=0.2)
对于列车和测试,分别得到(4000,4(和(1000,4(的形状
然而,当我在训练和测试数据上运行svm时,我会得到以下错误:
svclassifier = SVC(kernel='linear', C = 5)
svclassifier.fit(train, test)
ValueError Traceback (most recent call last)
<ipython-input-81-4c4a7bdcbe85> in <module>
----> 1 svclassifier.fit(train, test)
~/anaconda3/lib/python3.7/site-packages/sklearn/svm/base.py in fit(self, X, y, sample_weight)
144 X, y = check_X_y(X, y, dtype=np.float64,
145 order='C', accept_sparse='csr',
--> 146 accept_large_sparse=False)
147 y = self._validate_targets(y)
148
~/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, warn_on_dtype, estimator)
722 dtype=None)
723 else:
--> 724 y = column_or_1d(y, warn=True)
725 _assert_all_finite(y)
726 if y_numeric and y.dtype.kind == 'O':
~/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in column_or_1d(y, warn)
758 return np.ravel(y)
759
--> 760 raise ValueError("bad input shape {0}".format(shape))
761
762
ValueError: bad input shape (1000, 4)
有人能告诉我我的代码或数据出了什么问题吗?提前感谢!
train.head()
0 1 2 3
2004 1.619999 1.049560 1.470708 -1.323666
1583 1.389370 -0.788002 -0.320337 -0.898712
1898 -1.436903 0.994719 0.326256 0.495565
892 1.419123 1.522091 1.378514 -1.731400
4619 0.063095 1.527875 -1.285816 -0.823347
test.head()
0 1 2 3
1118 -1.152435 -0.484851 -0.996602 1.617749
4347 -0.519430 -0.479388 1.483582 -0.413985
2220 -0.966766 -1.459475 -0.827581 0.849729
204 1.759567 -0.113363 -1.618555 -1.383653
3578 0.329069 1.151323 -0.652328 1.666561
print(test.shape)
print(train.shape)
(1000, 4)
(4000, 4)
错误是因为train, test = train_test_split(CL_scaled, test_size=0.2)
首先需要分离数据和输出变量,并将其传递到train_test_split
。
# I am assuming your last column is output variable
train_test_split(CL_scaled[:-1], CL_scaled[-1], test_size=0.2).
train_test_split
将您的数据分成4部分X_train, X_test, y_train, y_test
此外,svclassifier.fit
取参数自变量和输出变量。所以你需要通过X_train
和y_train
所以你的代码应该是
X_train, X_test, y_train, y_test = train_test_split(CL_scaled[:-1], CL_scaled[-1], test_size=0.2)
svclassifier = SVC(kernel='linear', C = 5)
svclassifier.fit(X_train, y_train)
有关更多详细信息,请参阅文件
您缺少监督机器学习的基本概念。
在分类问题中,您有X的特征,并且您希望用它们来预测类Y。例如,这可能看起来像这样:
X y
Height Weight class
170 50 1
180 60 1
10 10 0
算法的想法是,它们有一个训练部分(你去足球训练(和一个测试部分(你周末在球场上测试你的技能(。
因此,您需要将数据拆分为训练集和测试集。
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(CL_scaled[:-1], CL_scaled[-1], test_size=0.2)
CL_scaled[:-1]
是你的X,CL_scalded[-1]
是你的Y。
然后你使用这个来适应你的分类器(训练部分(:
svclassifier = SVC(kernel='linear', C = 5)
svclassifier.fit(X_train, y_train)
然后你可以测试它:
prediction = svcclassifier.predict(X_test, y_test)
这将返回您对测试部件(y_predict(的预测,您可以根据y_test进行测量。