Python 用词袋法预测文本
我正在尝试使用单词袋模型进行文本分类。在我使用测试集测试和评估准确性之前,一切都正常,但我们如何检查单个语句的类 我有一个带有2个类标签和主体的数据框Python 用词袋法预测文本,python,machine-learning,scikit-learn,keras,text-classification,Python,Machine Learning,Scikit Learn,Keras,Text Classification,我正在尝试使用单词袋模型进行文本分类。在我使用测试集测试和评估准确性之前,一切都正常,但我们如何检查单个语句的类 我有一个带有2个类标签和主体的数据框 cout_vect = CountVectorizer() final_count = cout_vect.fit_transform(df['body'].values.astype('U')) from sklearn.model_selection import train_test_split from keras.models imp
cout_vect = CountVectorizer()
final_count = cout_vect.fit_transform(df['body'].values.astype('U'))
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
X_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)
您需要这样做:
# First transform the sentence to bag-of-words according to the already learnt vocabulary
x = cout_vect.transform([x])
# Then send the feature vector to the predict
print(model.predict(x, batch_size=None, verbose=0, steps=None))
您还没有展示如何“我尝试使用计数向量器将我的语句转换为向量,但根据单词袋方法,它只是一个8维向量”,但我猜您是这样做的:
cout_vect.fit_transform([x])
如果调用fit()
(或fit\u transform()
),矢量器将忘记所有以前的训练,只记住当前的vocab,因此您只得到大小为8的特征向量,而以前的向量大小更大