python - 如何在 Keras 中使用带有通用句子编码的 LSTM
问题描述
我正在尝试通过从 Universal Sentence Encoder 获取编码来训练模型并使用 LSTM 进行训练。这是我的代码:
module_url = "https://tfhub.dev/google/universal-sentence-encoder-large/3"
embed = hub.Module(module_url, trainable=True)
def UniversalEmbedding(x):
embeds = embed(tf.squeeze(tf.cast(x, tf.string)))
return embeds
input_text = Input(shape=(num_sentences,), dtype=tf.string)
embedding = Lambda(UniversalEmbedding, output_shape=(None,512))(input_text)
lstm = LSTM(128, return_sequences=False)(embedding)
dense = Dense(256, activation="relu")(lstm )
pred = Dense(num_classes, activation='softmax')(dense)
model = Model(inputs=[input_text], outputs=pred)
model.compile(Adam(3e-4), loss='categorical_crossentropy',
metrics=["accuracy", "categorical_accuracy", "top_k_categorical_accuracy"])
我收到以下错误:
ValueError: Input 0 of layer lstm_10 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 512)
问题是 USE 返回具有形状 (None, 512) 的 2-d 张量,而 LSTM 期望 3-d 张量可以使用。
解决方案
您可以tf.keras.layers.Reshape
在 LSTM 之前添加一个以将尺寸扩大 1. 参考 - https://www.tensorflow.org/api_docs/python/tf/keras/layers/Reshape
推荐阅读
- jquery - 如何创建一个可以在检查类时从类中删除复选框的函数?
- c# - C#,我希望主线程在所有子线程结束后输出“num”,怎么做?现在我只能得到'0'
- javascript - {Signature for this request is not valid}币安提款错误
- c - 在C中找到大整数的所有质因子的更好方法?
- node.js - Class-Validator node.js 提供自定义错误
- git - 如何查看 Git 的工作日志(不是提交历史,而是 Git 的进程)
- c# - 如何使 Xamarin 应用全屏(全屏)
- java - 如何将默认的snackbbar动画更改为“Top-to-button”?
- azure-devops - 在排队时分配构建清理选项
- visual-c++ - 带有驱动程序项目的静态驱动程序验证程序:InterceptedBuild 阶段出现不可恢复的错误