如何在 Tensorflow/Keras 中将形状为 (None, 1, n) 的张量连接到形状为 (None, None, m) 的张量以获得 (None, None, n+m)?

问题描述 投票:0回答:1

我正在使用 LSTM 构建模型。 第一个 LSTM 层

lstm1
输出形状为
Out1
的张量
(None, 1, n)
(n 是常数,第一个暗淡是批量大小)。

我想通过将第二个 LSTM

lstm2
连接到形状为
Out1
的时间序列
ts
来提供第二个 LSTM
(None, None, m)

如何将

Out1
连接到
ts
以获得形状为
(None, None, n+m)
的张量?

我尝试使用

keras.layers.concatenate
但我无法获得兼容的形状

tensorflow keras concatenation tensor
1个回答
0
投票

您可以使用 tf.concat 来指定维度,但它会给出一个额外的维度,您可以使用 tf.squeeze 删除它

import tensorflow as tf

m = 2
n = 3

# Define placeholder shapes
input_shape_1 = (None, 1, n)
input_shape_2 = (None, None, m)

# Define input tensors
tensor_1 = tf.keras.layers.Input(shape=input_shape_1)
tensor_2 = tf.keras.layers.Input(shape=input_shape_2)

# Concatenate tensors along the last axis (axis=-1)
concatenated_tensor = tf.concat([tensor_1, tensor_2], axis=-1)
print(concatenated_tensor.shape) # (None, None, 1, 5)

# Remove the extra 1-dimension
concatenated_tensor = tf.squeeze(concatenated_tensor, axis=2)
print(concatenated_tensor.shape) # (None, None, 5)
© www.soinside.com 2019 - 2024. All rights reserved.