import tensorflow as tf
import numpy as np
TensorFlow數據類型
python里面有類型:list, np.array, tf.Tensor
list是python自帶的類型,可以存儲不同類型的data,但是整體不夠高效;
np.array包含在numpy庫里面,方便數據計算,但是不支持求導;
Tensor是tensorflow里面的類型,可以進行快速計算和求梯度等,tensor是基於向量和矩陣的推廣,可以將標量視為0階張量,向量視為1階張量,矩陣視為2階張量。
tensor的數據可以分為以下類型:int, float, double, bool, string
1.1 如何進行創建?
- 創建一個整型的tensor:
tf.constant(1)
- 創建一個浮點型的tensor:
tf.constant(1.)
- 創建一個bool型的tensor:
tf.constant([True, False])
- 創建一個string型的tensor:
tf.constant('hello, world.')
- 創建一個雙精度浮點型的tensor:
tf.constant(2., dtype=tf.double)
1.2 Tensor的屬性
tensor一般存儲在GPU當中,numpy的變量一般存儲在CPU當中,有些時候需要將得到的數據進行轉換才能進一步進行計算。
#分別在cpu和gpu中創建兩個tensor,默認是在gpu中創建
with tf.device("cpu"):
a = tf.constant([1])
with tf.device("gpu"):
b = tf.range(4)
#查看變量是存儲在gpu還是cpu中
a.device
b.device
#相互轉換
aa=a.gpu()
aa.device #將cpu中的變量a轉換為cpu中的aa, 然后查看
bb=b.cpu()
bb.device
gpu上面的操作只能在gpu上面操作,cpu上面的操作只能在cpu上面操作
#將tensor轉換為numpy中的數據類型
b.numpy()
#查看數據維度(這兩者有區別嗎?)
b.ndim #shape屬性的長度(length)也是它的ndim.
tf.rank(b) #張量的秩與矩陣的秩不一樣.張量的秩是唯一選擇張量的每個元素所需的索引的數量.秩也被稱為 “order”,“degree” 或 “ndims”.
tf.rank(tf.ones([3,4,2]))
1.3 查看數據類型
a=tf.constant([1.])
b=tf.constant([True, False])
c=tf.constant('hello, world.')
d=np.arange(4)
#判斷是否是一個Tensor
isinstance(a, tf.Tensor) #在一種情況會失效,后面會提到
tf.is_tensor(b)
a.dtype, b.dtype, c.dtype
a.dtype==tf.float32
c.dtype==tf.string
1.4 數據類型轉化
- 轉換數據類型, 將一個numpy轉換為一個tensor, 可以用這種方式創建一個tensor
a=np.arange(5)
a.dtype #默認生成int64
aa=tf.convert_to_tensor(a)
aa=tf.convert_to_tensor(a, dtype=tf.int32)
tf.cast(aa, dtype=tf.float32)
aaa=tf.cast(aa, dtype=tf.double)
tf.cast(aaa, dtype=tf.int32) #tf.cast和tf.convert_to_tensor區別?tf.convert_to_tensor是將numpy轉化為tensor,
#tf.cast是轉換tensor的dtype
- bool型和int型相互轉換:
b=tf.constant([0,1])
tf.cast(b, dtype=tf.bool)
bb=tf.cast(b,dtype=tf.bool)
tf.cast(bb, tf.int32)
- tf.Variable是tensorflow中特有的數據類型,表示在訓練神經網絡時可以優化的參數,也就是不斷求梯度進行迭代的變量。將一般的tensor進行轉化為tf.Variable之后,具有了兩個屬性:trainable和name。
a=tf.range(5)
b=tf.Variable(a)
b.dtype
b.name
b=tf.Variable(a, name='input_data') #可對tf.Variable重命名
b.name
b.trainable
isinstance(b, tr.Tensor) #此時函數失效,返回false
isinstance(b, tr.Variable) #True
tf.is_tensor(b) #True
- 轉換為numpy數據:
a.numpy()
b.numpy()
a=tf.ones([])
a.numpy() #將tensor轉換為numpy
int(a) #具有相同的功效,更常用
float(a)