简体   繁体   English

如何对 Keras 文本分类进行预测?

[英]How to make prediction on Keras Text classification?

I've trained a model with this reference: https://www.tensorflow.org/tutorials/keras/text_classification_with_hub我已经用这个参考训练了 model: https://www.tensorflow.org/tutorials/keras/text_classification_with_hub

Here is my code:这是我的代码:

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds

train_data, validation_data, test_data = tfds.load(
    name="imdb_reviews", 
    split=('train[:60%]', 'train[60%:]', 'test'),
    as_supervised=True)

train_examples_batch, train_labels_batch = next(iter(train_data.batch(10)))

embedding = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(embedding, input_shape=[], 
                        dtype=tf.string, trainable=True)
hub_layer(train_examples_batch[:3])

model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))

model.summary()

model.compile(optimizer='adam',
    loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
    metrics=['accuracy'])

history = model.fit(train_data.shuffle(10000).batch(512),
    epochs=20,
    validation_data=validation_data.batch(512),
    verbose=1)

results = model.evaluate(test_data.batch(512), verbose=2)

model.save("imdb_model.h5")

I've saved the model as imdb_model.h5 .我已将 model 保存为imdb_model.h5 I want to make a prediction on a custom text.我想对自定义文本进行预测。 For example "The best movie, I have ever seen" .例如“我看过的最好的电影” How can I do it?我该怎么做?

You can use您可以使用

model.predict(["This is the best movie I have ever seen"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM