我正在尝试使用单词模型袋进行文本分类。一切正常,直到我使用测试集进行测试和准确性评估,但如何检查单个语句的类。
我有一个带有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 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)
答案 0 :(得分:1)
您需要执行以下操作:
# 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))
您还没有显示如何“ 我尝试使用count矢量化器将语句转换为vector,但是根据单词袋的方法,它只是一个8维矢量。”,但是我我猜你是这样做的:
cout_vect.fit_transform([x])
如果您调用fit()
(或fit_transform()
),则矢量化器将忘记之前的所有训练,而只记住当前的vocab,因此您只会得到大小为8的特征矢量,而先前的矢量尺寸更大。