Python 之 numpy 和 tensorflow 中的各類乘法(點乘和矩陣乘)

點乘和矩陣乘的區別:

1)點乘(即「 * 」) ---- 各個矩陣對應元素作乘法

若 w 爲 m*1 的矩陣,x 爲 m*n 的矩陣,那麼經過點乘結果就會獲得一個 m*n 的矩陣。spa

 

 

若 w 爲 m*n 的矩陣,x 爲 m*n 的矩陣,那麼經過點乘結果就會獲得一個 m*n 的矩陣。3d

 

 

w的列數只能爲 1 與x的列數相等(即n),w的行數與x的行數相等 才能進行乘法運算。code

2)矩陣乘 ---- 按照矩陣乘法規則作運算

若 w 爲 m*p 的矩陣,x 爲 p*n 的矩陣,那麼經過矩陣相乘結果就會獲得一個 m*n 的矩陣。blog

只有 w 的列數 == x的行數 時,才能進行乘法運算ip

 

1. numpy

1)點乘

1 import numpy as np
2 
3 w = np.array([[0.4], [1.2]])
4 x = np.array([range(1,6), range(5,10)])
5 
6 print w
7 print x
8 print w*x

運行結果以下圖:utf-8

 2)矩陣乘

1 import numpy as np
2 
3 w = np.array([[0.4, 1.2]])
4 x = np.array([range(1,6), range(5,10)])
5 
6 print w
7 print x
8 print np.dot(w,x)

運行結果以下:it

 

2. tensorflow

 1)點乘

 1 import tensorflow as tf
 2 
 3 w = tf.Variable([[0.4], [1.2]], dtype=tf.float32) # w.shape: [2, 1]
 4 x = tf.Variable([range(1,6), range(5,10)], dtype=tf.float32) # x.shape: [2, 5]
 5 y = w * x     # 等同於 y = tf.multiply(w, x)   y.shape: [2, 5]
 6 
 7 sess = tf.Session()
 8 init = tf.global_variables_initializer()
 9 sess.run(init)
10 
11 print sess.run(w)
12 print sess.run(x)
13 print sess.run(y)

 運行結果以下:io

 

 2)矩陣乘

 1 # coding:utf-8
 2 import tensorflow as tf
 3 
 4 w = tf.Variable([[0.4, 1.2]], dtype=tf.float32) # w.shape: [1, 2]
 5 x = tf.Variable([range(1,6), range(5,10)], dtype=tf.float32) # x.shape: [2, 5]
 6 y = tf.matmul(w, x) # y.shape: [1, 5]
 7 
 8 sess = tf.Session()
 9 init = tf.global_variables_initializer()
10 sess.run(init)
11 
12 print sess.run(w)
13 print sess.run(x)
14 print sess.run(y)

 運行結果以下:class

相關文章
相關標籤/搜索