我一直在学习 tensorflow 网站上的教程,特别是 https://www.tensorflow.org/tutorials/keras/ 上的“使用 TensorFlow Hub 进行文本分类:电影评论”
我一直在学习 tensorflow 网站上的教程,特别是 https://www.tensorflow.org/tutorials/keras/text_classification_with_hub .
当我运行以下代码时:
import os
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
print("Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("GPU is", "available" if tf.config.list_physical_devices("GPU") else "NOT AVAILABLE")
# Split the training set into 60% and 40% to end up with 15,000 examples
# for training, 10,000 examples for validation and 25,000 examples for testing.
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)))
print(train_examples_batch)
print(train_labels_batch)
embedding = "https://tfhub.dev/google/nnlm-en-dim50/2"
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()
我收到以下错误:
Traceback (most recent call last):
File "{path to MovieReviews.py}/MovieReviews.py", line 30, in <module>
model.add(hub_layer)
File "{path to sequential.py}/sequential.py", line 95, in add
raise ValueError(
ValueError: Only instances of `keras.Layer` can be added to a Sequential model. Received: <tensorflow_hub.keras_layer.KerasLayer object at 0x7f059295ab70> (of type <class 'tensorflow_hub.keras_layer.KerasLayer'>)
我知道问题出在任何 model.add() 调用上。此外,我已在系统上重新安装了 tensorflow 和 tensorflow_hub,并确保它们是最新的。我无法弄清楚为什么会出现此错误,因为代码是直接从 tensorflow 网站复制粘贴的。任何建议都值得感激。