python - 如何对 Keras 文本分类进行预测?
问题描述
我已经用这个参考训练了一个模型:https ://www.tensorflow.org/tutorials/keras/text_classification_with_hub
这是我的代码:
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")
我已将模型保存为imdb_model.h5。我想对自定义文本进行预测。例如“我看过的最好的电影”。我该怎么做?
解决方案
您可以使用
model.predict(["This is the best movie I have ever seen"])
推荐阅读
- python - 同时使用值列表拆分字符串
- docker - Docker 容器中的 Ansible Playbook 执行跳过任务完成
- html - 如何创建一个以 HTML 格式播放 youtube 视频的按钮?
- python - 如何在 Django DetailView 视图中检索上一个/下一个条目
- java - 从 JAR 记录系统指标
- ios - UILabel 的默认行距
- c# - 让 Microsoft Graph 调用在 .net Web 应用程序中工作时遇到问题
- sql-server - SQL Server - 如何将多行数据放入返回的变量中
- linux - 什么可以使程序在 `strace` 中表现不同?
- html - 韦普和