一、Tensor
- 标量scalar:1.1
- 向量vector:[1.1],[1.1,2.2,...]
- 矩陣matrix:[[1.1,2.2],[1.1,2.2]]
-
張量tensor:rank>2
張量是基于向量和矩陣的推廣,可以将标量看為零階張量,矢量看做一階張量,矩陣看做二階張量。
目錄
一、Tensor
二、資料類型分類
三、建立tensor
四、Tensor的索引與切片
五、次元變換
六、基本的運算
二、資料類型分類
TF is a computing lib.
- int,float,double
- bool
- string
基礎案例:
import tensorflow as tf
import numpy as np
#建立一個常數
tf.constant(1)
#加上dtpye說明類型
tf.constant(2.2,dtype=tf.int32)
#傳回裝置名字
with tf.device("gpu"):
a=tf.constant([1])
a.device
aa=a.cpu()#将建立的資料轉移到cpu上
b.ndim
print(b.ndim)#demention是1
tf.rank(tf.ones([2,3,4])) #傳回的還是次元:3
#判斷一個參數是不是tensor
tf.is_tensor(b)
#将一個資料轉換到tensor
a=np.arange(5) #此時的類型是一個int64
aa=tf.convert_to_tensor(a,dtype=tf.int32)
#資料轉換api
tf.cast(aa,dtype=tf.float32)
b=tf.constant([0,1])
tf.cast(b,dtype=tf.bool) #numpy=array([false,true])
#梯度可求導的
a=tf,range(5)#numpy=array([0,1,2,3,4])
b=tf.Varible(a)
b.trainabe #true
#将資料轉換為numpy
a.numpy()
三、建立tensor
tf.convert_to_tensor(np.ones([2,3])) #建立一個tensor
tf.zeros([2,3,4]) #傳進去的是一個shape,不是一個data
tf.zeros_like(a) #建立一個和a同一類型的資料類型
tf.ones(a.shape) #等價于上一句
tf.fill([2,2],0) #填充為0
#初始化分布資料建立
tf.random.normal([2,2],mean=1,stddev=1) #初始化為兩行兩列的一個(1,1)分布的資料
#截斷資料api
tf.random.truncated_normal([2,2],mean=0,stddev=1)
#均勻分布
tf.random.uniform([2,2],minval=0,maxval=1) #均勻的0,1分布
#随機打散
idx=tf.random.shuffle(idx)
a=tf.gather(a,idx) #再組合
#編碼函數
out = tf.random.uniform([4,10])
y=range(4)#[0,1,2,3]
y=tf.one_hot(y,depth=10)#([[1,0,0,0,0,0,0,0,0,0],...])
四、Tensor的索引與切片
#1.直接索引:[idx0][idx1]...
a = tf.ones([1,5,5,3])
aa= a[0][0]
#2.numpy的索引方式
a = tf.random.norml([4,28,28,3])
aa= a[1,3,3] #shape:[3]
#3.切片:讀取數組的一部分
a = tf.range(10)
a[-1:0] #numpy=arrray([9])
a[:-1] #傳回到倒數第二個 numpy=array([0,1,2,3,4,5,6,7,8])
a[0:] #numpy=array([0,1,2,3,4,5,6,7,8,9])
#4.間隔采樣切片
a=tf.random.normal([4,28,28,3])
a.shape() #Tensorshape([4,28,28,3])
a[:,0:28:2,:,:] #Tensorshape([4,14,28,3])
#5.倒序采樣
a = tf.range(10)
aa =a[::-1] #tf.Tensor([9 8 7 6 5 4 3 2 1 0], shape=(10,), dtype=int32)
#省略寫法
a[0,...,2].shape #取中間三個次元的第二通道的資訊
#6.選擇性采樣:Selective Indexing
tf.gather #6.1一個次元指定
a = tf.random.normal([4,35,8]) #4個班級,每個班級35個人,每個人8門學科
tf.gather(a,axis=0,indices=[2,3]).shape
tf.gather_nd #6.2多個次元指定
tf.gather_nd(a,[[0,1],[1,2]]) #Tensorshape([2,8])
tf.gather_nd(a,[[0,0,0],[1,1,1],[2,2,2]]) #Tensorshape([3])
tf.gather_nd(a,[[[0,0,0],[1,1,1],[2,2,2]]]) #Tensorshape([1,3])
tf.boolean_mask #6.3通過True和false指定
tf.random.normal([4,28,28,3])
tf.boolean_mask(a,[True,True,false,false],axis=0) #Tensorshape([2,28,28,3])
a = tf.ones([2,3,4])
aa = tf.boolean_mask(a,[[True,False,False],[False,True,False]])
print(aa)
#tf.Tensor(
#[[1. 1. 1. 1.]
# [1. 1. 1. 1.]], shape=(2, 4), dtype=float32)
五、次元變換
- shape,ndim
tf.reshape函數:将原本的資料的行列資料混合,減少次元
a = tf.random.normal([4,28,28,3])
aa= tf.reshape(a,[4,-1,3]) #Tensorshape([4,784,3])
- tf.transpose
tf.transpose:tensor的交換函數
a=tf.random.normal([4,3,2,1])
tf.transpose(a) #預設将所有次元都做一個轉置
#1.指定次元轉置
tf.transpose(a,perm[0,3,1,2])#Tensorshape([4,3,1,2])
#2.增加一個次元
tf.expand_dims()
a = tf.random.normal([4,3,9])
aa = tf.expand_dims(a,axis=1)
print(aa.shape) #Tensorshape([4,1,3,9])
b = tf.expand_dims(a,axis=-1)
print(b.shape) #Tensorshape([4,3,9,1])
#3.squeeze:去掉所有次元為1的次元
tf.squeeze(tf.ones([1,2,3,1])).shape#Tensorshape([2,3])
#squeeze指定一個為1的次元消失
tf.squeeze(tf.ones([1,2,3,1]),axis=0).shape#Tensorshape([2,3,1])
- broadcasting
Broadcasting 稱為廣播機制(或自動擴充機制),它是一種輕量級的張量複制手段,在邏輯上擴充張量資料的形狀,但是隻會在需要時才會執行實際存儲複制操作。對于大部分場景,Broadcasting 機制都能通過優化手段避免實際複制資料而完成邏輯運算,進而相對于tf.tile 函數,減少了大量計算代價。
a = tf.random.normal([4,32,32,3])
aa =(a+tf.random.normal([1]))
b = tf.random.normal([4,1,1,3])
bb = tf.broadcast_to(b,[4,32,32,3])
print(aa.shape)#(4, 32, 32, 3)
print(bb.shape)#(4, 32, 32, 3)
六、基本的運算
- 加減乘除:+-*/
- 平方根/高次/開方:**,pow,square
- 平方根:sqrt
- 其他:exp,log
- 矩陣相乘:@,matmul(效果與@等同)
- 次元操作:reduce_mean/max/min/sum
#1.tf.math.log()和tf.exp()
a = tf.ones([2,2])
print(a)
b = tf.math.log(a)
print(b)
c = tf.exp(a)
print(c)
#tf.Tensor(
# [[1. 1.]
# [1. 1.]], shape=(2, 2), dtype=float32)
# tf.Tensor(
# [[0. 0.]
# [0. 0.]], shape=(2, 2), dtype=float32)
# tf.Tensor(
# [[2.7182817 2.7182817]
# [2.7182817 2.7182817]], shape=(2, 2), dtype=float32)
#2.tf.pow()函數、tf.sqrt()函數和**操作符
a = tf.fill([2,2],2)
b=tf.pow(a,3)
c=a**3
d=tf.sqrt(a)
#3.矩陣運算
b = tf.fill([2,2],2)
a = tf.ones([2,2])
b = tf.cast(b,tf.float32)
c = [email protected]
print(c)
#tf.Tensor(
#[[4. 4.]
# [4. 4.]], shape=(2, 2), dtype=float32)
c = tf.matmul(a,b)#效果與@等同
#4.矩陣運算結合broadcasting
a = tf.ones([4,2,3])
b = tf.fill([3,5],2.)
c = [email protected]
# tf.Tensor(
# [[[6. 6. 6. 6. 6.]
# [6. 6. 6. 6. 6.]]
# ...
# [6. 6. 6. 6. 6.]]], shape=(4, 2, 5), dtype=float32)