首页 > 解决方案 > Tensorflow:将矩阵列乘以向量的元素并返回矩阵

问题描述

这是我想在 Tensorflow 中完成的任务。

我有 2x2 矩阵(可训练)

x_1 x_2
x_3 x_4

我有输入向量

a
b

我想将矩阵的每一列乘以向量的元素并返回以下矩阵

ax_1 bx_2
ax_3 bx_4

我可以通过将矩阵的每一列声明为单独的变量来得到这个结果,但我想知道是否有更优雅的解决方案。

标签: tensorflowvectormatrix-multiplication

解决方案


感谢广播,您应该可以使用常规乘法运算符:

import tensorflow as tf

x = tf.constant([[3, 5], [7, 11]], dtype=tf.int32)
a = tf.constant([4, 8], dtype=tf.int32)
y = x * a

with tf.Session() as sess:
    print(sess.run(y))  # Result: [[12, 40], [28, 88]]

推荐阅读