【问题标题】:AttributeError: 'TfidfVectorizer' object has no attribute 'get_feature_names_out'AttributeError:\'TfidfVectorizer\' 对象没有属性 \'get_feature_names_out\'
【发布时间】:2023-01-19 18:37:58
【问题描述】:

为什么我不断收到此错误?我也尝试了其他代码,但是一旦它使用get_feature_names_out 函数就会弹出这个错误。

下面是我的代码:

from sklearn.datasets._twenty_newsgroups import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB  # fast to train and achieves a decent F-score
from sklearn import metrics
import numpy as np

def show_top10(classifier, vectorizer, categories):
    feature_names = vectorizer.get_feature_names_out()
    for i, category in enumerate(categories):
        top10 = np.argsort(classifier.coef_[i])[-10:]
        print("%s: %s" % (category, " ".join(feature_names[top10])))

newsgroups_train = fetch_20newsgroups(subset='train')
print(list(newsgroups_train.target_names))

cats = ['alt.atheism', 'sci.space', 'rec.sport.baseball', 'rec.sport.hockey']
newsgroups_train = fetch_20newsgroups(subset='train', categories=cats)
print(list(newsgroups_train.target_names))
print(newsgroups_train.filenames.shape)

vectorizer = TfidfVectorizer()
vectors = vectorizer.fit_transform(newsgroups_train.data)
print(vectors.shape)

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    这可能是因为您使用的 scikit-learn 版本比编写此代码的版本要旧。

    get_feature_names_out 是自 scikit-learn 1.0 以来类 sklearn.feature_extraction.text.TfidfVectorizer 的一个方法。之前有一个类似的方法叫get_feature_names

    所以你应该更新你的 scikit-learn 包,或者使用旧方法(不推荐)。

    【讨论】:

    • 谢谢,我刚刚意识到我的 pycharm 使用旧版本的 sklearn。
    【解决方案2】:

    sklearn.__version__ <= 0.24.x使用以下方法

    get_feature_names() 
    

    sklearn.__version__ >= 1.0.x使用下面的方法

    get_feature_names_out() 
    

    参考:

    1. https://github.com/scikit-learn/scikit-learn/blob/0.24.X/sklearn/feature_extraction/text.py

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-01
      • 2012-12-01
      • 2021-04-19
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      相关资源
      最近更新 更多