测试代码如下:
1 # encoding:utf-8
2
3 import tensorflow as tf
4
5 # placeholder 占位符 可以由用户输入
6 data1 = tf.placeholder(tf.float32)
7 data2 = tf.placeholder(tf.float32)
8 dataAdd = tf.add(data1,data2)
9 with tf.Session() as sess:
10 print(sess.run(dataAdd,feed_dict={data1:6, data2:2}))
11 print("end!")1.2.3.4.5.6.7.8.9.10.11.
运行结果如下:
类似于二维数组,测试代码如下:
1 # encoding:utf-8
2
3 import tensorflow as tf
4
5 # 类比 数组M行N列
6 data1 = tf.constant([[6,6]]) # M=1 N=1
7 data2 = tf.constant([[2],
8 [2]]) # M=2 N=1
9 data3 = tf.constant([[3,3]]) # M=1 N=1
10 data4 = tf.constant([[1,2],
11 [3,4],
12 [5,6]]) # M=3 N=2
13 print(data4.shape) # 打印该矩阵的维度
14 with tf.Session() as sess:
15 print(sess.run(data4))
16 print(sess.run(data4[0])) # 打印第一行
17 print(sess.run(data4[:,0])) # 打印第一列
18 print(sess.run(data4[0,0])) # 打印一行一列的数
19 print("end!")1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
运行结果如下:
同维度矩阵相加减,内积,外积等,测试代码如下:
1 # encoding:utf-8
2
3 import tensorflow as tf
4
5 data1 = tf.constant([[6,6]])
6 data2 = tf.constant([[2],
7 [2]])
8 data3 = tf.constant([[3,3]])
9 data4 = tf.constant([[1,2],
10 [3,4],
11 [5,6]])
12 matMul = tf.matmul(data1,data2)
13 matMul2 = tf.multiply(data1,data2)
14 matAdd = tf.add(data1,data3)
15 with tf.Session() as sess:
16 print(sess.run(matMul)) # 矩阵内积
17 print("---------------------------")
18 print(sess.run(matAdd)) # 矩阵相加 矩阵相减类似
19 print("---------------------------")
20 print(sess.run(matMul2)) # 矩阵外积
21 print("---------------------------")
22 print(sess.run([matMul,matAdd])) #打印多个内容
23 print("end!")1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.
运行结果如下:
特殊矩阵的测试代码如下:
1 # encoding:utf-8
2
3 import tensorflow as tf
4
5 # 特殊矩阵的测试
6 # 全零矩阵的两种定义方式
7 mat0 = tf.constant([[0,0,0],[0,0,0]])
8 mat1 = tf.zeros([2,3])
9 # 全1矩阵
10 mat2 = tf.ones([3,2])
11 # 填充矩阵
12 mat3 = tf.fill([2,2],16)
13 # 归零矩阵
14 mat4 = tf.constant([[2],[3],[4]])
15 mat5 = tf.zeros_like(mat4)
16 # 等间隔矩阵
17 mat6 = tf.linspace(0.0,2.0,11)
18 # 随机矩阵
19 mat7 = tf.random_uniform([2,3],-1,2)
20 with tf.Session() as sess:
21 print(sess.run(mat0)) #
22 print("---------------------------")
23 print(sess.run(mat1))
24 print("---------------------------")
25 print(sess.run(mat2))
26 print("---------------------------")
27 print(sess.run(mat3))
28 print("---------------------------")
29 print(sess.run(mat4))
30 print("---------------------------")
31 print(sess.run(mat5))
32 print("---------------------------")
33 print(sess.run(mat6))
34 print("---------------------------")
35 print(sess.run(mat7))
36 print("---------------------------")
37 print("end!")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.
运行结果如下:
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删