python - 如何在keras中连接不同的张量形状
问题描述
我正在尝试在 keras 中实现注意力机制,我的 context_vector 形状是 shape=(?, 1024)
而我的 decoder_embedding 形状是 shape=(?, 38, 1024)
context_vector 和 decoder_embedding 都是张量我如何连接这些...... ?
def B_Attention_layer(state_h,state_c,encoder_outputs):
d0 = tf.keras.layers.Dense(1024,name='dense_layer_1')
d1 = tf.keras.layers.Dense(1024,name='dense_layer_2')
d2 = tf.keras.layers.Dense(1024,name='dense_layer_3')
#below are the hidden states of LSTM
# my encoder output shape is shape=(?, 38, 1024)
#my each hidden state shape is i.e.., state_c shape=(?, 1024) ,state_h shape=(?, 1024)
hidden_with_time_axis_1 = tf.keras.backend.expand_dims(state_h, 1)
hidden_with_time_axis_2 = tf.keras.backend.expand_dims(state_c, 1)
score = d0(tf.keras.activations.tanh(encoder_outputs) + d1(hidden_with_time_axis_1) + d2(hidden_with_time_axis_2))
attention_weights = tf.keras.activations.softmax(score, axis=1)
context_vector = attention_weights * encoder_outputs
context_vector = tf.keras.backend.sum(context_vector, axis=1)
input_to_decoder = tf.keras.layers.Concatenate(axis=-1)([context_vector,decoder_embedding])
return input_to_decoder , attention_weights
当我尝试这个时,我得到一个如下的连接错误
ValueError: A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 1, 1024), (None, 38, 1024)]
解决方案
在您的情况下,连接轴为 1,因为您有形状(None, 1, 1024)
和(None, 38, 1024)
示例:
I1 = tf.keras.Input(shape=(1, 1024))
# <tf.Tensor 'input_6:0' shape=(?, 1, 1024) dtype=float32>
I2 = tf.keras.Input(shape=(38, 1024))
# <tf.Tensor 'input_7:0' shape=(?, 38, 1024) dtype=float32>
concated = tf.keras.layers.Concatenate(axis=1)([I1,I2])
# output: <tf.Tensor 'concatenate_4/concat:0' shape=(?, 39, 1024) dtype=float32>
同样作为错误消息状态,因为连接轴是 1 其余维度必须相同。
推荐阅读
- excel - 在 MS Excel 中标记准重复项
- java - 我是否需要服务器才能将在我的应用程序中创建的 PDF 发送到另一台设备上的同一应用程序(不同帐户)?
- sql - SQL 查询没有整体执行
- node.js - 在 Linux Ubuntu 的 Windows 子系统中链接 Windows 命令
- javascript - 将鼠标悬停在一个元素上以使另一个元素可见
- javascript - Discord JS 遇到问题
- typescript - 我可以从通用参数推断枚举值吗?
- sql-server - 如何在左连接上的空值的情况下重复值
- request - SKStoreReviewController.requestReview() 费率不来 Appstore
- javascript - 无法从 api 访问数据