我使用了以下代码集:并且我需要检查X_train和X_test的准确率
以下代码在我的多标签分类问题中对我有效
import numpy as npfrom sklearn.pipeline import Pipelinefrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.svm import LinearSVCfrom sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.multiclass import OneVsRestClassifierX_train = np.array(["new york is a hell of a town", "new york was originally dutch", "the big apple is great", "new york is also called the big apple", "nyc is nice", "people abbreviate new york city as nyc", "the capital of great britain is london", "london is in the uk", "london is in england", "london is in great britain", "it rains a lot in london", "london hosts the british museum", "new york is great and so is london", "i like london better than new york"])y_train = [[0],[0],[0],[0] ,[0],[0],[1],[1] ,[1],[1],[1],[1] ,[2],[2]]X_test = np.array(['nice day in nyc', 'the capital of great britain is london', 'i like london better than new york', ]) target_names = ['Class 1', 'Class 2','Class 3']classifier = Pipeline([ ('vectorizer', CountVectorizer(min_df=1,max_df=2)), ('tfidf', TfidfTransformer()), ('clf', OneVsRestClassifier(LinearSVC()))])classifier.fit(X_train, y_train)predicted = classifier.predict(X_test)for item, labels in zip(X_test, predicted): print '%s => %s' % (item, ', '.join(target_names[x] for x in labels))
输出
nice day in nyc => Class 1the capital of great britain is london => Class 2i like london better than new york => Class 3
我想检查训练数据集和测试数据集之间的准确率。Score函数对我不起作用,它显示了一个错误,指出不能接受多标签值
>>> classifier.score(X_train, X_test)
NotImplementedError: score不支持多标签分类器
请帮助我获取训练和测试数据的准确率结果,并为我们的分类案例选择一个算法。
回答:
如果你想获取测试集的准确率分数,你需要创建一个答案键,你可以称之为y_test
。除非你知道正确答案,否则你无法知道你的预测是否正确。
一旦你有了答案键,你就可以获取准确率。你想要的方法是sklearn.metrics.accuracy_score。
我已经在下面写出来了:
from sklearn.metrics import accuracy_score# ... 其他一切保持不变 ...# 创建答案键# 我希望这是正确的!y_test = [[1], [2], [3]]# 与你的一样...classifier.fit(X_train, y_train)predicted = classifier.predict(X_test)# 获取准确率print accuracy_score(y_test, predicted)
此外,sklearn除了准确率之外还有其他几种度量方法。请参见这里:sklearn.metrics