[英]tensorflow efficient way for tensor multiplication
張量流中有兩個張量,第一個張量是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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.