Keras 函数式 API 和 TensorFlow Hub

Seb*_*eza 6 python keras tensorflow

我正在尝试以功能方式使用TF Hub 中的通用句子编码器作为 keras 层。我想hub.KerasLayer与 Keras 功能 API 一起使用,但我不确定如何实现这一点,到目前为止我只看到 hub.KerasLayer 与 Sequential API 的示例

import tensorflow_hub as hub
import tensorflow as tf
from tensorflow.keras import layers
import tf_sentencepiece


use_url = 'https://tfhub.dev/google/universal-sentence-encoder-multilingual-large/1'

english_sentences = ["dog", "Puppies are nice.", "I enjoy taking long walks along the beach with my dog."]
english_sentences = np.array(english_sentences, dtype=object)[:, np.newaxis]


seq = layers.Input(shape=(None, ), name='sentence', dtype=tf.string)
module = hub.KerasLayer(hub.Module(use_url))(seq)
model = tf.keras.models.Model(inputs=[seq], outputs=[module])
model.summary()

x = model.predict(english_sentences)
print(x)

Run Code Online (Sandbox Code Playgroud)

将输入层传递到嵌入时,上面的代码会遇到此错误:TypeError: Can't convert 'inputs': Shape TensorShape([Dimension(None), Dimension(None)]) is incompatible with TensorShape([Dimension(None)])

是否可以在 TensorFlow 1.x 中将 hub.KerasLayer 与 keras 功能 API 一起使用?如果可以的话,怎么做?

Sun*_*rma 3

尝试这个

sentence_encoding_layer = hub.KerasLayer("https://tfhub.dev/google/universal-sentence-encoder/4",
                                         trainable=False,
                                         input_shape = [],
                                         dtype = tf.string,
                                         name = 'U.S.E')

inputs = tf.keras.layers.Input(shape = (), dtype = 'string',name = 'input_layer')

x = sentence_encoding_layer(inputs)
x = tf.keras.layers.Dense(64,activation = 'relu')(x)

outputs = tf.keras.layers.Dense(1,activation = 'sigmoid',name = 'output_layer')(x)

model = tf.keras.Model(inputs,outputs,name = 'Transfer_learning_USE')
model.summary()
Run Code Online (Sandbox Code Playgroud)

model.predict([句子])