【问题标题】:Issues printing the class, name and accuracy score of the voting classifier打印投票分类器的类、名称和准确度分数的问题
【发布时间】:2019-03-22 07:29:45
【问题描述】:

我想用三个不同的分类器在 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_'

当我删除 '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

看到导入的库,我不确定为什么没有定义 accuracy_score

【问题讨论】:

    标签: python class printing scikit-learn classification


    【解决方案1】:

    关于类 em>的第一个错误,您需要在此处有两个下划线。

    改变

    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))吗?或在任何不同的文件中?

    【讨论】:

      猜你喜欢
      • 2018-04-30
      • 1970-01-01
      • 2021-12-26
      • 2020-08-02
      • 2020-08-06
      • 2020-05-13
      • 2020-04-01
      • 2014-05-09
      • 2016-01-12
      相关资源
      最近更新 更多