TensorFlow 实现矩阵[n,*]的各行乘以另一个[1,n]矩阵的对应元素

这个问题真的研究了好久,这个是个小技巧,很实用。

用到的函数主要有

tf.transpose(a, perm=None, name=’transpose’)

调换tensor的维度顺序
           按照列表perm的维度排列调换tensor顺序,
           如为定义,则perm为(n-1…0)
           # ‘x’ is [[1 2 3],[4 5 6]]
           tf.transpose(x) ==> [[1 4], [2 5],[3 6]]
           # Equivalently
           tf.transpose(x, perm=[1, 0]) ==> [[1 4],[2 5], [3 6]

tf.multiply(x, y)

 

实现过程

import tensorflow as tf

a = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], shape=(2, 2, 3))
a_new = tf.reshape(a, shape=[3, 4])
a_trans = tf.transpose(a_new)  # 转置[3,4] to [4,3]

b = tf.constant([1, 2, 3], shape=[1, 3])
result = tf.multiply(a_trans, b)
result = tf.transpose(result)

with tf.Session() as sess:
    print(sess.run(a_new))
    print(sess.run(result))

输出结果:

TensorFlow 实现矩阵[n,*]的各行乘以另一个[1,n]矩阵的对应元素_第1张图片

 

你可能感兴趣的:(tensorflow)