tensorflow笔记02

  1. 1. 矩阵基本操作及实现

矩阵基本操作及实现

常见矩阵操作

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
60
61
62
63
64
65
66
67
68
69
70
71
import tensorflow as tf

#获取交互式会话
sess = tf.InteractiveSession()

#创建5x5 的单位矩阵
I_matrix = tf.eye(5)
#print(I_matrix.eval())

#创建一个被初始化的 10x10的单位矩阵
X = tf.Variable(tf.eye(10),name='helloX')
X.initializer.run()
#print(X.eval())

#创建一个随机的 5x10的矩阵
A = tf.Variable(tf.random_uniform([5,10]),name='helloA')
A.initializer.run()


#两个矩阵相乘
product = tf.matmul(A,X)
#print(product.eval())

#创建一个 只含有1和0的随机矩阵,尺寸为5x10
b = tf.Variable(tf.random_uniform([5,10],0,2,dtype=tf.int32),name='hellob')
b.initializer.run()
#print(b.eval())

#将b转为float32类型
b_new = tf.cast(b,dtype=tf.float32)

#两个矩阵相加
t_sum = tf.add(product,b_new)
t_sub = product - b_new
#print("A*X + b\n",t_sum.eval())
#print("A*X - b\n",t_sub.eval())


sess.close()

##########矩阵按元素相乘、乘以标量,按元素除,按元素取余
#按元素计算,要保证矩阵大小一致,格式一致
a = tf.Variable(tf.random_uniform([4,5],1,10,dtype=tf.int32))
b = tf.Variable(tf.random_uniform([4,5],1,10,dtype=tf.int32))

#元素相乘
A = a * b

#乘以标量 就是全部乘上一个数字
B = tf.scalar_mul(2,A)

#元素除法
C = tf.div(a,b)

#元素取余
D = tf.mod(a,b)

init_op = tf.global_variables_initializer()

with tf.Session() as sess:
sess.run(init_op)
writer = tf.summary.FileWriter('graphs',sess.graph)
a,b,A_R,B_R,C_R,D_R = sess.run([a,b,A,B,C,D])
print("============= a =============\n",a,
"\n============= b =============\n",b,
"\n============ a*b ============\n",A_R,
"\n=========== 2*a*b ===========\n",B_R,
"\n============ a/b ============\n",C_R,
"\n============ a%b ============\n",D_R)

writer.close()