使用词袋模型预测文本

我正在尝试使用词袋模型进行文本分类。一切正常,直到我使用测试集进行测试和准确性评估。但是,如何检查单个语句的类别呢?

我有一个包含两个类别标签和正文的数据框架。

cout_vect = CountVectorizer()final_count = cout_vect.fit_transform(df['body'].values.astype('U'))from sklearn.model_selection import train_test_splitfrom keras.models import Sequentialfrom keras.layers import Densefrom keras.wrappers.scikit_learn import KerasClassifierfrom keras.utils import np_utilsX_train, X_test, y_train, y_test = train_test_split(final_count, df['label'], test_size = .3, random_state=25)model = Sequential()model.add(Dense(264, input_dim=X_train.shape[1], activation='relu'))model.add(Dense(128, activation='relu'))model.add(Dense(64, activation='relu'))model.add(Dense(32, activation='relu'))model.add(Dense(16, activation='relu'))model.add(Dense(8, activation='relu'))model.add(Dense(3, activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])y_train = np_utils.to_categorical(y_train, num_classes=3)y_test = np_utils.to_categorical(y_test, num_classes=3)model.fit(X_train, y_train, epochs=50, batch_size=32)model.evaluate(x=X_test, y=y_test, batch_size=None, verbose=1, sample_weight=None)

现在我想使用我的模型来预测这个语句。我尝试过使用计数向量器将我的语句转换为向量,但根据词袋方法,它只是一个8维向量。

x = "Your account balance has been deducted for 4300"model.predict(x, batch_size=None, verbose=0, steps=None)

回答:

你需要这样做:

# 首先根据已经学习到的词汇表将句子转换为词袋x = cout_vect.transform([x])# 然后将特征向量发送到预测print(model.predict(x, batch_size=None, verbose=0, steps=None))

你没有展示你是如何“尝试使用计数向量器将我的语句转换为向量,但根据词袋方法,它只是一个8维向量。”的,但我猜你是这样做的:

cout_vect.fit_transform([x])

如果你调用fit()(或fit_transform()),向量器将忘记所有之前的训练,只记住当前的词汇表,因此你只得到了一个大小为8的特征向量,而你之前的向量是更大的尺寸。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注