1、數據載體
① list : list中可以添加多種數據,[1,1.2,‘hello’,(1,2)]
② np.array:np數組主要用於解決同種數據的運算,不支持自動求導,不支持GPU運算
③ tf.Tensor:
▪ scalar: 1.1
▪ vector: [1.1],[1.1,2.2,…]
▪ matrix: [[1.1,2.2],[3.3,4.4],[5.5,6.6]]
▪ tensor: 𝑟𝑎𝑛𝑘 > 2
2、TF是一個計算庫,跟np非常接近,主要有以下數據類型和屬性
(1) int ,float, double,bool,string
1 #int整型
2 a = tf.constant(1) 3 print("int型a: ",a) 4
5 #float型
6 b = tf.constant(1.0) 7 print("float型b:",b) 8
9 #double型
10 c = tf.constant(1.0, dtype = tf.double) #指定數據類型
11 print("double型c: ",c) 12
13 #bool型
14 d = tf.constant([True,False]) 15 print("bool型:",d) 16
17 #字符串型
18 e = tf.constant('hello,world!') 19 print("字符串型:",e)
輸出:
int型a: tf.Tensor(1, shape=(), dtype=int32) float型b: tf.Tensor(1.0, shape=(), dtype=float32) double型c: tf.Tensor(1.0, shape=(), dtype=float64) bool型: tf.Tensor([ True False], shape=(2,), dtype=bool) 字符串型: tf.Tensor(b'hello,world!', shape=(), dtype=string)
(2)tensor的屬性
#新建兩個tensor
1 with tf.device("cpu"): 2 a = tf.constant([1]) 3
4 with tf.device("gpu"): 5 b = tf.range(4)
屬性主要有
① device,查看設備
print(a.device) print(b.device)
輸出:
/job:localhost/replica:0/task:0/device:CPU:0 /job:localhost/replica:0/task:0/device:GPU:0
② gpu,cpu對tensor進行數據計算平台轉換
1 aa = a.gpu() #a是cpu tensor,轉換為gpu
2 print(aa.device) 3
4 bb = b.cpu() #b是gpu tensor,轉換為cpu
5 print(bb.device)
輸出:
/job:localhost/replica:0/task:0/device:GPU:0 /job:localhost/replica:0/task:0/device:CPU:0
③ ndim,查看tensor的維度
1 d = a.ndim 2 print(d) #1
④tensor和numpy的轉換,tf.convert_to_tensor()和 tf.cast()(萬能api)
#
1 a = np.arange(5) 2 print(a) #[0 1 2 3 4]
3 print(a.dtype) # int32
4
5 aa = tf.convert_to_tensor(a, dtype = tf.float32) #將整型a抓換為浮點型tensoraa
6 print(aa) #tf.Tensor([0. 1. 2. 3. 4.], shape=(5,), dtype=float32)
7
8 bb = tf.cast(aa,dtype = tf.float64) 9 print(bb) # tf.Tensor([0. 1. 2. 3. 4.], shape=(5,), dtype=float64)
10
11 bbb = tf.cast(aa,dtype = tf.double) 12 print(bbb) # tf.Tensor([0. 1. 2. 3. 4.], shape=(5,), dtype=float64)
3、檢查tensor的類型
(1)isinstance,is_tensor,dtype
1 a = tf.constant([1.]) 2 print(isinstance(a,tf.Tensor)) 3 print(tf.is_tensor(a)) 4 print(a.dtype)
輸出:
True True <dtype: 'float32'>
4、tf.Variable,定義一個可以優化的參數,即變量
1 a = tf.Variable(5) 2 print(a) 3 print(a.dtype)
輸出:
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=5>
<dtype: 'int32'>
