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

标签 python tensorflow deep-learning

我在 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/

相关文章:

python - 导入错误: cannot import name bayesflow

python - 如何将 Tensorflow 数据集转换为二维 numpy 数组

python - 如何在训练时卡住 tensorflow 变量中的特定节点?

python - 如何基于Tensorflow模型进行预测

python - 替换 "tf.gather_nd"

python - 如何使用 python 将流上传到 AWS s3

python - 使用 Flask 和 gunicorn 进行 JSON 格式的日志记录

python - 从 Django webapp 安全地执行 Go 脚本

python - 用于 conv2d 和手动加载图像的 Keras input_shape

python - 多次调用 pd.DataFrame.plot() 后颜色一致