【深度学习】TensorFlow——理解张量

 1 import tensorflow as tf
 2 
 3 # 张量 -----数据流图中的线-----数据传递----本质:多维数组
 4 
 5 # 两个属性
 6 # dtype---数据类型
 7 # 将numpy里面的np.数据类型----变成了tf.数据类型
 8 # 可以在创建张量的时候去指定dtype 参数来指定tensor的数据类型
 9 #
10 
11 # shape ---形状
12 
13 # # 创建张量----创建固定值张量
14 con_a = tf.constant(3, dtype=tf.float64, name="con_a")
15 con_a = tf.to_int32(con_a)  # 数据类型可以强制转换
16 
17 #
18 res = tf.to_int32(True)
19 res = tf.to_int32(False)
20 print("res:\n",res)
21 print("res的类型: \n", type(res))
22 #
23 # # 数据类型转换 cast
24 # # 参数1  将要转化的tensor
25 # # 参数2  新的数据类型
26 con_a = tf.cast(con_a,dtype=tf.float64)
27 con_a = tf.cast(con_a,dtype=tf.int64)
28 print("con_a:\n", con_a)
29 #
30 #
31 #
32 #
33 # # 创建一个全为0 的张量
34 zeros = tf.zeros(shape=[2, 3], dtype=tf.int32, name="zeros")
35 print("zeros:\n", zeros)
36 #
37 # # 创建一个全部为1 的张量
38 ones = tf.ones(shape=[2, 2], dtype=tf.int32, name="ones")
39 print("ones:\n", ones)
40 #
41 # # 创建随机张量---创建一个符合标准正态分布的随机张量
42 hh = tf.random_normal(
43     shape=[2, 3],
44     mean=0.0,
45     stddev=1.0,
46     name="hh",
47     dtype=tf.float64
48 )
49 print("hh:\n", hh)
50 # 获取 tensor里面包含的值
51 # 开启会话执行图
52 with tf.Session() as ss:
53     print(ss.run(fetches=[con_a, zeros, ones, hh]))
54     print(ss.run(res))
55 
56 
57 # 形状的更改
58 gg = tf.random_normal(
59     shape=[2, 2],
60     mean=0.0,
61     stddev=1.0,
62     name="gg"
63 )
64 # None 行None列的2阶张量
65 gg = tf.placeholder(shape=[None, None], dtype=tf.int32, name="gg")
66 print("gg:\n", gg)
67 # 确定其形状
68 # 静态形状改变,只能将未知的形状确定,不能夸阶更改
69 # gg.set_shape(shape=[2, 2])
70 # gg.set_shape(shape=[1, 2, 2])
71 # 也能将未知的形状确定
72 # 而且可以夸阶更改
73 # 只要元素确定,想怎么改就怎么改
74 gg = tf.reshape(gg, shape=[1, 2, 2])
75 # gg = tf.reshape(gg, shape=[1, 2, 3]) # 错误的
76 print("gg:\n", gg)
77 
78 with tf.Session() as ss:
79     # print(ss.run(gg, feed_dict={gg: [[1, 2], [3, 4]]}))
80     # print(ss.run(gg, feed_dict={gg: [[[1, 2], [3, 4]]]})) # 静态形状更改时错误的不能夸阶更改
81     print(ss.run(gg, feed_dict={gg: [[[1, 2], [3, 4]]]})) # reshape能夸阶更改
82     # print(ss.run(gg)) # 错误的不能夸阶更改

猜你喜欢

转载自www.cnblogs.com/Tree0108/p/12116308.html