【问题标题】:Keras fails while processing word embedingsKeras 在处理词嵌入时失败
【发布时间】:2020-04-30 07:38:48
【问题描述】:
word_embed = keras.layers.Embedding(len(vocab), 101)
em = word_embed(tf.convert_to_tensor(np.random.rand(10, 48)))

print(em.shape) 
# (10, 48, 101)    
# 10 sentences in bacth, 48 words in sentence(with padding), 101 - embedding dimension...

lstm = K.layers.LSTMCell(101)
lstm_layer = keras.layers.RNN(lstm)hidden_states = lstm_layer(em) 

# TypeError: Expected Operation, Variable, or Tensor, got False

谁能帮忙,为什么会出现错误?预期 lstm 单元的隐藏状态...

【问题讨论】:

  • 你想在这里做什么?为什么要将lstm 层传递给RNN 层,为什么要使用LSTMCell 而不是LSTM

标签: python keras tensorflow2.0


【解决方案1】:

您可以在模型中使用“嵌入到 LSTM 层”一词,如下所示。

这里我考虑二进制分类示例,嵌入维度为 101,句子中的最大单词数为 48。

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding,Dense,LSTM  

model = Sequential()
model.add(Embedding(len(vocab), 101, input_length=48))
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
## Fit the model
model.fit(data, np.array(labels), validation_split=0.4, epochs=3)

【讨论】:

    猜你喜欢
    • 2018-09-03
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 2016-12-12
    • 2023-03-25
    相关资源
    最近更新 更多