gpt4 book ai didi

python - 对单个句子进行预测时,收到错误 "Number of features of the model must match the input."

转载 作者:行者123 更新时间:2023-11-30 10:00:16 24 4
gpt4 key购买 nike

我是一名数据科学新手,我正在尝试将 TfidfVectorizer 与 RandomForestClassifier 结合使用来预测字符串上的二进制“是/否”结果,如下所示:

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

df = pd.read_csv('~/Downloads/New_Query_2019_12_04.csv', usecols=['statement', 'result'])
df = df.head(100)

# remove non-values
df = df.dropna()

tfidfconverter = TfidfVectorizer(
max_features=1500,
min_df=5,
max_df=0.7,
stop_words=stopwords.words('english'))

X = tfidfconverter.fit_transform(df['statement']).toarray()
y = df['result'].values

X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=0)

classifier = RandomForestClassifier(n_estimators=1000, random_state=0)
classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

所有这些看起来都很有效,但我一直困惑于如何根据模型预测短语。当我做类似的事情时:

good_string = preprocess_string('This is a good sentence')

tfidfconverter = TfidfVectorizer()

X = tfidfconverter.fit_transform([good_string]).toarray()

y_pred = classifier.predict(X)

我收到错误“模型的特征数量必须与输入匹配。”

我还尝试使用之前的 TfidfVectorizer 来拟合字符串:

tfidfconverter = TfidfVectorizer(
max_features=1500,
min_df=5,
max_df=0.7,
stop_words=stopwords.words('english'))

X = tfidfconverter.fit_transform([good_string]).toarray()

但我收到错误“max_df 对应于 < 文档而不是 min_df”。我想我只是对如何适应单个字符串的数组特征以匹配模型中的数字特征有点困惑。任何帮助将不胜感激。

最佳答案

问题是我通过具有相同构造函数参数的不同矢量化器运行它:

tfidfconverter = TfidfVectorizer(
max_features=1500,
min_df=5,
max_df=0.7,
stop_words=stopwords.words('english'))

而不是使用我在此处拟合文档时使用的相同矢量化器:

X = tfidfconverter.fit_transform(df['statement']).toarray()

我也不应该尝试拟合我试图预测的数据,而应该只对其进行转换。

X = tfidfconverter.transform([good_string]).toarray()

关于python - 对单个句子进行预测时,收到错误 "Number of features of the model must match the input.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59312150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com