使用保存的CNN模型从输入文本中对单个评论进行预测



我正在Keras中制作一个基于CNN模型的分类器。

我将在应用程序中使用它,用户可以加载应用程序并输入文本,模型将从权重中加载并进行预测。

问题是我也在使用GloVe嵌入,CNN模型也使用填充文本序列。

我使用Keras tokenizer如下:

tokenizer = text.Tokenizer(num_words=max_features, lower=True, char_level=False)
tokenizer.fit_on_texts(list(train_x))
train_x = tokenizer.texts_to_sequences(train_x)
test_x = tokenizer.texts_to_sequences(test_x)
train_x = sequence.pad_sequences(train_x, maxlen=maxlen)
test_x = sequence.pad_sequences(test_x, maxlen=maxlen)

我训练了模型并根据测试数据进行了预测,但现在我想用我加载并工作的加载模型进行测试。

但我在这里的问题是,如果我提供一个单独的回顾,它必须通过返回2D阵列的tokeniser.text_to_sequences(),其形状为(num_chars, maxlength),因此后面是num_chars预测,但我需要它为(1, max_length)形状。

我使用以下代码进行预测:

review = 'well free phone cingular broke stuck not abl offer kind deal number year contract up realli want razr so went look cheapest one could find so went came euro charger small adpat made fit american outlet, gillett fusion power replac cartridg number count packagemay not greatest valu out have agillett fusion power razor'
xtest = tokenizer.texts_to_sequences(review)
xtest = sequence.pad_sequences(xtest, maxlen=maxlen)
model.predict(xtest)

输出为:

array([[0.29289   , 0.36136267, 0.6205081 ],
[0.362869  , 0.31441122, 0.539749  ],
[0.32059124, 0.3231736 , 0.5552745 ],
...,
[0.34428033, 0.3363668 , 0.57663095],
[0.43134686, 0.33979046, 0.48991954],
[0.22115968, 0.27314988, 0.6188136 ]], dtype=float32)

我需要一个单独的预测array([0.29289 , 0.36136267, 0.6205081 ]),因为我有一个单一的评论。

问题是需要将字符串列表传递给texts_to_sequences方法。所以你需要把单个评论放在这样的列表中:

xtest = tokenizer.texts_to_sequences([review])

如果你不这样做(即传递一个字符串,而不是一个字符串列表(,考虑到Python中的字符串是可迭代的,它会迭代给定字符串的字符,并将字符而不是单词视为令牌:

oov_token_index = self.word_index.get(self.oov_token)
for text in texts:  # <-- it would iterate over the string instead
if self.char_level or isinstance(text, list):

这就是为什么要得到一个形状为(num_chars, maxlength)的数组作为texts_to_sequences方法的返回值。

最新更新