更新
我正在进行机器学习文本分类工作,使用的是线性核的SVC,整个代码都能正常运行,除了最后一行代码(print (svm_model_linear.predict_proba(test)))。实际上,我正在构建一个分类器,包含三个类别:自行车、足球和羽毛球,我有一些标记为这些类别的脸书状态。我已经训练并测试了分类器,使用了train_test_split,之后我有一些未标记的状态,我想对它们进行分类,但最后一行代码出现了错误
from sklearn.feature_extraction.text import CountVectorizercv = CountVectorizer(max_features = 700)X = cv.fit_transform(corpus).toarray()print Xy = dataset.iloc[:, 1].valuesprint y# 将数据集拆分为训练集和测试集from sklearn.cross_validation import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)from sklearn.svm import SVCsvm_model_linear = SVC(kernel ='linear', C = 1, probability=True).fit(X_train, y_train)svm_predictions = svm_model_linear.predict(X_test)# 模型在X_test上的准确率 accuracy = svm_model_linear.score(X_test, y_test)# 创建混淆矩阵cm = confusion_matrix(y_test, svm_predictions)
从这里开始对未标记数据进行分类
data = pd.read_csv('sentence.csv', delimiter = '\t', quoting = 3)test = []for j in range(0, 5): review = re.sub('[^a-zA-Z]', ' ', data['Sentence'][j]) review = review.lower() review = review.split() ps = PorterStemmer() review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))] review = ' '.join(review) test.append(review)pred = cv.fit_transform(test).toarray()print (svm_model_linear.predict_proba(test))
错误
print (svm_model_linear.predict_proba(test))Traceback (most recent call last): File "<ipython-input-7-5fa676a0fc00>", line 1, in <module>print (svm_model_linear.predict_proba(test)) File "/home/letsperf/.local/lib/python2.7/site-packages/sklearn/svm/base.py", line 594, in _predict_probaX = self._validate_for_predict(X) File "/home/letsperf/.local/lib/python2.7/site-packages/sklearn/svm/base.py", line 439, in _validate_for_predictX = check_array(X, accept_sparse='csr', dtype=np.float64, order="C") File "/home/letsperf/.local/lib/python2.7/site-packages/sklearn/utils/validation.py", line 402, in check_arrayarray = np.array(array, dtype=dtype, order=order, copy=copy)ValueError: X.shape[1] = 15 should be equal to 700, the number of features at training time
回答:
Scikit估计器不能处理字符串,只能处理数值数据。你的训练部分能够成功完成是因为你使用了CountVectorizer将语料库从字符串转换为数值。你在测试数据上没有这样做。
你需要在测试数据上调用cv.transform(test)
,使其与用于训练模型的X类似。这样才能成功并有意义。
还要确保你使用的是转换原始训练corpus
为数值形式的同一个cv
对象。
更新:
你不应该在测试数据上调用fit_transform()
,始终只调用transform()
,如我上面建议的。你当前所做的是:
pred = cv.fit_transform(test).toarray()
这会忘记之前的训练并重新拟合计数向量化器,这将改变pred
的形状。改为:
pred = cv.transform(test).toarray()