Python:如何在SVM文本分类器算法中找到多标签类的准确性结果

2024-05-14 22:33:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用了以下代码集: 我需要检查X光列车和X光测试的准确性

下面的代码适用于我在多标签类上的分类问题

import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.multiclass import OneVsRestClassifier

X_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 1
the capital of great britain is london => Class 2
i like london better than new york => Class 3

我想检查一下训练和测试数据集之间的准确性。 Score函数对我不起作用,它显示一个错误,指出不能接受多标签值

>>> classifier.score(X_train, X_test)

不实现错误:多标签分类器不支持分数

请帮助我得到训练和测试数据的准确结果,并为我们的分类案例选择一个算法。


Tags: oftheinfromimportnewistrain
1条回答
网友
1楼 · 发布于 2024-05-14 22:33:35

如果你想得到测试集的准确度分数,你需要创建一个应答键,你可以调用它y_test。除非你知道正确的答案,否则你不知道你的预测是否正确。

一旦你有了答案,你就可以得到准确的答案。你想要的方法是sklearn.metrics.accuracy_score

我写在下面:

from sklearn.metrics import accuracy_score

# ... everything else the same ...

# create an answer key
# I hope this is correct!
y_test = [[1], [2], [3]]

# same as yours...
classifier.fit(X_train, y_train)
predicted = classifier.predict(X_test)

# get the accuracy
print accuracy_score(y_test, predicted)

此外,sklearn除了准确性之外还有其他一些指标。看这里:sklearn.metrics

相关问题 更多 >

    热门问题