发行打印投票分类器的等级,名称和准确性得分的问题

时间:2018-10-17 14:59:04

标签: python class printing scikit-learn classification

我想用三个不同的分类器在SciKit-Learn中训练一个投票分类器。我在最后一步有问题,这是打印分类器的最终准确性得分。

from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

import pandas as pd
import numpy as np 

log_clf=LogisticRegression()
rnd_clf=RandomForestClassifier()
svm_clf=SVC()

voting_clf=VotingClassifier(estimators=[('lr',log_clf),('rf',rnd_clf),('svc',svm_clf)],voting='hard')
voting_clf.fit(X_train, y_train)

运行以下代码时出现错误:

for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    clf.fit(X_train, y_train)
    y_predict=clf.predict(X_test)
    print(clf._class_._name_,accuracy_score(y_test,y_pred))

运行这段代码时,我得到以下信息:

AttributeError: 'LogisticRegression' object has no attribute '_class_'

我假设调用' class '有点过时,所以我将class更改为'classes _':

for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    clf.fit(X_train, y_train)
    y_pred=clf.predict(X_test)
    print(clf.classes_._name_,accuracy_score(y_test,y_pred))

运行这段代码时,我得到以下信息:

AttributeError: 'numpy.ndarray' object has no attribute '_name_'

当我删除“ 名称”并运行以下代码时,仍然出现错误:

for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    clf.fit(X_train, y_train)
    y_pred=clf.predict(X_test)
    print(clf.classes_,accuracy_score(y_test,y_pred))

错误:

 NameError: name 'accuracy_score' is not defined

我不确定为什么看到导入的库后未定义precision_score

1 个答案:

答案 0 :(得分:1)

对于有关 class 的第一个错误,您需要在此处添加两个下划线。

更改

print(clf._class_._name_,accuracy_score(y_test,y_pred))

收件人:

print(clf.__class__.__name__, accuracy_score(y_test,y_pred))

有关在python中获取对象名称的其他方法,请参见此问题:

现在由于未定义关于'accuracy_score'的第二个错误,当您没有正确导入accuracy_score时会发生这种情况。但是我可以看到,在您的代码中,您已经导入了accuracy_score。因此,您确定要在同一文件中执行第print(clf.__class__.__name__, accuracy_score(y_test,y_pred))行吗?或任何其他文件中?