gpt4 book ai didi

python - tensorflow张量乘法的有效方法

转载 作者:行者123 更新时间:2023-11-28 16:23:49 24 4
gpt4 key购买 nike

我在 tensorflow 中有两个张量,第一个张量是 3-D,第二个是 2D。我想像这样将它们相乘:

x = tf.placeholder(tf.float32, shape=[sequence_length, batch_size, hidden_num]) 
w = tf.get_variable("w", [hidden_num, 50])
b = tf.get_variable("b", [50])

output_list = []
for step_index in range(sequence_length):
output = tf.matmul(x[step_index, :, :], w) + b
output_list.append(output)
output = tf.pack(outputs_list)

我用循环做乘法运算,但我觉得太慢了。使此过程尽可能简单/干净的最佳方法是什么?

最佳答案

您可以使用 batch_matmul。不幸的是,batch_matmul 似乎不支持沿批量维度进行广播,因此您必须平铺 w 矩阵。这将使用更多内存,但所有操作将保留在 TensorFlow 中

a = tf.ones((5, 2, 3))
b = tf.ones((3, 1))
b = tf.reshape(b, (1, 3, 1))
b = tf.tile(b, [5, 1, 1])
c = tf.batch_matmul(a, b) # use tf.matmul in TF 1.0
sess = tf.InteractiveSession()
sess.run(tf.shape(c))

这给出了

array([5, 2, 1], dtype=int32)

关于python - tensorflow张量乘法的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38222126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com