Skip to content
Happy Programming Guide
Start learning
Python

TfidfVectorizer Object Has No Attribute get_feature_names

scikit-learn renamed the method to get_feature_names_out() in version 1.0 and removed the old name in 1.2. Here is the fix and a version-safe helper.

A computer mouse resting on a wooden table

AttributeError: 'TfidfVectorizer' object has no attribute 'get_feature_names' means you are on scikit-learn 1.2 or later. The method was renamed get_feature_names_out() in version 1.0, deprecated for two releases, and removed in 1.2. Adding the _out suffix is the whole fix.

The fix#

Python
from sklearn.feature_extraction.text import TfidfVectorizer

vectorizer = TfidfVectorizer()
matrix = vectorizer.fit_transform(documents)

# Old - removed in 1.2
features = vectorizer.get_feature_names()

# New
features = vectorizer.get_feature_names_out()
Terminal
python -c "import sklearn; print(sklearn.__version__)"

One difference worth knowing: the old method returned a Python list, the new one returns a NumPy array. Most code does not care, but if you were relying on list methods, wrap it:

Python
features = list(vectorizer.get_feature_names_out())

Why it changed#

scikit-learn standardised the API so every transformer answers the same question the same way: given the input feature names, what feature names come out? For a vectorizer that is the vocabulary; for a one-hot encoder it is the expanded columns; for a pipeline it is whatever the last step produces. The _out suffix makes that meaning explicit.

A version-safe helper#

If your code has to run against several scikit-learn versions:

Python
def feature_names(transformer):
    """Works on scikit-learn before and after 1.0."""
    if hasattr(transformer, "get_feature_names_out"):
        return list(transformer.get_feature_names_out())
    return list(transformer.get_feature_names())


print(feature_names(vectorizer)[:10])

Better still, pin a version in requirements.txt so the environment cannot drift underneath you:

Output
scikit-learn>=1.2,<2.0

Everything else affected#

Class Old New
TfidfVectorizer get_feature_names() get_feature_names_out()
CountVectorizer same same
DictVectorizer same same
OneHotEncoder same same
PolynomialFeatures same same
ColumnTransformer same same
Pipeline same same

If you hit one, you will probably hit the others. A project-wide search and replace is usually safe:

Terminal
grep -rn "get_feature_names()" --include="*.py" .

A working example#

Python
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer

documents = [
    "the cat sat on the mat",
    "the dog sat on the log",
    "cats and dogs are pets",
]

vectorizer = TfidfVectorizer(stop_words="english", min_df=1)
matrix = vectorizer.fit_transform(documents)

df = pd.DataFrame(
    matrix.toarray(),
    columns=vectorizer.get_feature_names_out(),
)
print(df.round(3))

Finding the highest-scoring terms per document is the usual next step:

Python
import numpy as np

names = vectorizer.get_feature_names_out()

for i, row in enumerate(matrix.toarray()):
    top = np.argsort(row)[::-1][:3]
    terms = [(names[j], round(row[j], 3)) for j in top if row[j] > 0]
    print(f"document {i}: {terms}")

Inside a pipeline#

Python
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression

pipeline = Pipeline([
    ("tfidf", TfidfVectorizer(stop_words="english")),
    ("clf", LogisticRegression(max_iter=1000)),
])

pipeline.fit(documents, labels)

# Reach the step by name
names = pipeline.named_steps["tfidf"].get_feature_names_out()

# The most influential terms
coefficients = pipeline.named_steps["clf"].coef_[0]
top = np.argsort(coefficients)[::-1][:10]

for i in top:
    print(f"{names[i]:20s} {coefficients[i]:.3f}")
Python
vectorizer = TfidfVectorizer(max_features=5000, min_df=2, max_df=0.8)

Those three arguments do most of the useful trimming: cap the vocabulary, drop terms appearing in fewer than two documents, and drop terms appearing in more than 80 per cent of them.

Questions people ask#

Which version removed the old name?

It was deprecated in 1.0 and removed in 1.2. Between those versions the old name worked and emitted a warning.

Why does the new method return an array?

Consistency with the rest of the API, which works in NumPy arrays throughout. Wrap it in list() if you need list behaviour.

Does get_feature_names_out take arguments?

It accepts optional input feature names, which matter for transformers that pass names through, such as a ColumnTransformer. For a vectorizer you can call it with no arguments.

How do I stop this happening again?

Pin versions in requirements.txt, and run your tests with deprecation warnings turned into errors so you get years of notice rather than a surprise on upgrade day.

Where to go next#

Machine learning with Python, from data to modelRead next

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *