在 Keras 中添加不等大小的张量
Addition of unequal sized tensors in Keras
我在 Keras 中使用形式为张量的工作
A =
现在,我想为 40 个“行”中的每一行添加维度为
的张量的索引 0 行
B =
简而言之,对于第二张量我只需要当前步骤B[:,0,:]。因此,排除第一维,这将是矩阵 B 的第一“行”。
Add() 层似乎只适用于大小相同的张量。关于如何指定完成这项工作的 Lambda 函数有什么建议吗?
感谢阅读!
也许可以试试这样:
import tensorflow as tf
samples = 1
A = tf.random.normal((samples, 40, 2))
B = tf.random.normal((samples, 2, 2))
B = tf.expand_dims(B[:, 0, :], axis=1) # or just B = B[:, 0, :]
C = A + B
print(C.shape)
# (1, 40, 2)
或使用 Lambda
层:
import tensorflow as tf
samples = 1
A = tf.random.normal((samples, 40, 2))
B = tf.random.normal((samples, 2, 2))
lambda_layer = tf.keras.layers.Lambda(lambda x: x[0] + x[1][:, 0, :])
print(lambda_layer([A, B]))
我在 Keras 中使用形式为张量的工作
A =
现在,我想为 40 个“行”中的每一行添加维度为
的张量的索引 0 行B =
简而言之,对于第二张量我只需要当前步骤B[:,0,:]。因此,排除第一维,这将是矩阵 B 的第一“行”。
Add() 层似乎只适用于大小相同的张量。关于如何指定完成这项工作的 Lambda 函数有什么建议吗?
感谢阅读!
也许可以试试这样:
import tensorflow as tf
samples = 1
A = tf.random.normal((samples, 40, 2))
B = tf.random.normal((samples, 2, 2))
B = tf.expand_dims(B[:, 0, :], axis=1) # or just B = B[:, 0, :]
C = A + B
print(C.shape)
# (1, 40, 2)
或使用 Lambda
层:
import tensorflow as tf
samples = 1
A = tf.random.normal((samples, 40, 2))
B = tf.random.normal((samples, 2, 2))
lambda_layer = tf.keras.layers.Lambda(lambda x: x[0] + x[1][:, 0, :])
print(lambda_layer([A, B]))