1 | 矩阵乘([m,n] * [n, p] --> [m, p]) |
代码示例如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59#!/usr/bin/python
# coding=utf-8
import numpy as np
import tensorflow as tf
a = np.arange(1, 5).reshape(2, 2)
b = np.arange(0, 4).reshape(2, 2)
c = np.arange(0, 3)
d = np.arange(1, 4)
e = np.mat(a)
f = np.mat(b)
'''
a:
array([[1, 2],
[3, 4]])
b:
array([[0, 1],
[2, 3]])
c:
array([0, 1, 2])
d:
array([1, 2, 3])
e:
matrix([[1, 2],
[3, 4]])
f:
matrix([[0, 1],
[2, 3]])
'''
with tf.Session() as sess:
print np.dot(a, b) # np.dot
print np.dot(e, f) # np.dot
print e * f # np.mat() * np.mat()
print sess.run(tf.matmul(a.astype('float32'), b.astype('float32'))) # tf.matmul()
#这四个都是矩阵相乘,结果如下
'''
[[ 4 7]
[ 8 15]]
'''
print np.dot(c, d) # np.dot
#这个也是矩阵相乘,可以看作[1, 3]*[3, 1]->[1,1]
'''
8
'''
print np.multiply(a, b) # np.multiply(array, array)
print np.multiply(e, f) # np.multiply(mat, mat)
print a * b # np.array() * np.array()
print sess.run(tf.constant(a, dtype=tf.float32) * tf.constant(b, dtype=tf.float32)) # tf.Variable() * tf.Variable()
#这四个都是对应位置相乘,结果如下
'''
[[ 0. 2.]
[ 6. 12.]]