【问题标题】:How to make prediction on Keras Text classification?如何对 Keras 文本分类进行预测?
【发布时间】:2020-04-27 00:08:39
【问题描述】:

我已经用这个参考训练了一个模型: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。我想对自定义文本进行预测。例如“我看过的最好的电影”。我该怎么做?

【问题讨论】:

    标签: python tensorflow keras text-classification


    【解决方案1】:

    你可以使用

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

    【讨论】:

    • 结果浮点数是什么意思?
    • 数字高表示可能,数字低表示不可能。如果您愿意,可以将其包装在 sigmoid 函数中以获得 0 到 1 之间的百分比。
    猜你喜欢
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2019-07-02
    • 2016-12-27
    • 2019-06-07
    相关资源
    最近更新 更多