numpy tensorflow various multiplication and (dot product and matrix multiplication)

Dot matrix multiplication and differentiation of:

1) dot (ie, "*") ---- multiply each matrix corresponding element

If w is m * 1 matrix, x is an m * n matrix, we will obtain a multiplication result by the point m * n matrix.

image.png

If w is a m * n matrix, x is an m * n matrix, the multiplication results obtained will point a m * n matrix.

image.png

w is the number of columns can only be 1 or equal to the number of columns of x (i.e., n), the number of rows the number of rows w and x equal to multiplication.

2) matrix multiplication ---- do operations in accordance with the rules of matrix multiplication

If w is an m * p matrix, x is p * n matrix, the matrix multiplication result will be obtained by a m * n matrix.

Only the number of columns w == x number of lines of time before multiplication

img

1. numpy

1) dot


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

FIG results are as follows:

img

2) matrix multiplication


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)

Results are as follows:

img

2. tensorflow

1) dot

 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)

Results are as follows:

image.png

2) matrix multiplication


 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)

Results are as follows:

img

Guess you like

Origin www.cnblogs.com/xxpythonxx/p/11332860.html