tensorflow中向量與矩陣相乘

         我們只當使用tensorflow的tf.matmul()可以進行矩陣間的運算,但是要求矩陣的每一個維度的長度都要大於2,假如我們進行向量與矩陣的乘法時,使用該函數,則會報錯。

          具體地,我們使用一個2爲的向量乘以一個2×2的矩陣:

import tensorflow as tf
a = tf.constant([2, 3])
b = tf.constant([[0, 1], [2, 3]])
c = tf.matmul(a, b)
with tf.Session() as sess:
     print(sess.run(c))
會報錯:
ValueError: Shape must be rank 2 but is rank 1 for 'MatMul_11' (op: 'MatMul') with input shapes: [2], [2,2].

那如何實現向量與矩陣相乘呢?

         我們知道矩陣乘法的本質是對矩陣的向量進行線性組合,利用這個性質,我們可以對矩陣進行點乘再相加,從實現向量與矩陣的乘法。具體如下

1、矩陣×向量

 [[0, 1],      [2,
 [2, 3]]   ×    3] 

具體代碼實現:

import tensorflow as tf
a = tf.constant([2, 3])
b = tf.constant([[0, 1], [2, 3]])
mul =tf.reduce_sum(tf.multiply(a, b), reduction_indices=1)
with tf.Session() as sess:
     print(sess.run(mul))
結果是:
[ 3 13]

2、向量×矩陣

   [2, 3]  ×  [[0, 1],      
              [2, 3]]     
這個時候需要將矩陣進行轉置,然後在進行點乘,再橫向相加
具體代碼如下:

import tensorflow as tf
a = tf.constant([2, 3])
b = tf.constant([[0, 1], [2, 3]])
mul =tf.reduce_sum(tf.multiply(a, tf.transpose(b, perm=[1, 0])), reduction_indices=1)
with tf.Session() as sess:
     print(sess.run(mul))
結果:
[ 6 11]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章