every blog every motto: Just live your life cause we don’t live twice.
0. 前言
有關張量的基本概念和操作
1. 正文
1.1 什麼是tensor
不嚴謹的的說,標量、向量、矩陣、多維數組等都叫tensor,(和numpy類似,不同點在於內置了GPU加速,提高計算速度而已。)
1.2 基本操作
1.2.1 創建tensor
import tensorflow as tf
tf.constant(1)
tf.constant(1.)
可指定數據類型
tf.constant(2.,dtype=tf.double)
tf.constant([True,False])
tf.constant('hello world.')
1.2.2 tensor屬性
1.2.2.1 指定生成數據位置
方法一:
with tf.device('cpu'):
a = tf.constant([1])
a.device
數據指定在cpu上,如下圖
with tf.device('gpu'):
b = tf.range(4)
b.device
數據指定在gpu上
**方法二:**使用默認位置
g = tf.constant([2])
g.device
cpu上
v = tf.range(3)
v.device
1.2.2.2 改變數據位置
aa = a.gpu()
aa.device
數據由cpu改變成到gpu
bb = b.cpu()
bb.device
數據有gpu改變成到cpu
1.2.2.3 tensor -> numpy
tensor 轉成 numpy
t = b.numpy()
t
numpy查看維度
t.ndim
1.2.2.4 查看tensor是幾維
h = tf.range(5)
h
tf.rank(h)
查看維度如下圖
1.2.2.5 判斷一個參數是否是tensor
a = tf.constant([1.])
方法一:(推薦使用)
tf.is_tensor(a)
方法二:(不推薦使用)
isinstance(a,tf.Tensor)
1.2.2.6 類型轉換
1. numpy -> tensor
a = np.arange(5)
a
aa = tf.convert_to_tensor(a)
aa
2. 改變tensor的數據類型
tf.cast(aa,dtype=tf.float32)
1.2.2.7 tf.Variable
a = tf.range(5)
a
b = tf.Variable(a)
b
b.trainable
如下圖,可訓練的,能求導
isinstance(b,tf.Tensor)
如下圖,判斷錯誤,所以不推薦用isinstance判斷是否是tensor
推薦使用is_tensor進行判斷
tf.is_tensor(b)
isinstance(b,tf.Variable)
tensor-> numpy
b.numpy()
a = tf.ones([])
a.numpy()
對於標量,還有一種特殊是轉換方式,如下圖
int(a)
float(a)