【深度學習】Tensorflow學習(1)張量與常用函式
關於張量
張量可以表示0階到N階的陣列
在TensorFlow中,張量(Tensor)表示某種相同資料型別的多維資料
因此張量有兩個重要特徵:
- 資料型別
- 陣列形狀(各個維度的大小)
張量的資料型別
tf.int,tf.float
tf.int32,tf.float32,tf.float64
tf.bool
tf.constant([True,False])
tf.string
tf.constant("Hello Wrold !")
建立Tensor
建立一個最簡單的張量
tf.constant(張量內容,dtype=資料型別(可選))
import tensorflow as tf a = tf.constant([1,5],dtype=tf.int64) print(a) print(a.dtype) print(a.shape)
python 3.10 tensorflow-gpu 2.8 | 執行結果
tf.Tensor([1 5], shape=(2,), dtype=int64) <dtype: 'int64'> (2,)
將numpy資料型別轉為tensor資料型別
tf.convert_to_tensor(a,dtype=tf.int64)
import tensorflow as tf
import numpy as np
a = np.arange(0,5)
b = tf.convert_to_tensor(a,dtype=tf.int64)
print(a)
print(b)
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
[0 1 2 3 4] tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)
通過維度建立一個tensor
建立全為0的張量
tf.zeros(維度)
建立全為1的張量
tf.ones(維度)
建立全為指定值的張量
tf.fill(維度,指定值)
舉例
import tensorflow as tf
a=tf.zeros([2,3])
b=tf.ones(4)
c=tf.fill([2,2],9)
print(a)
print(b)
print(c)
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
tf.Tensor( [[0. 0. 0.] [0. 0. 0.]], shape=(2, 3), dtype=float32) tf.Tensor([1. 1. 1. 1.], shape=(4,), dtype=float32) tf.Tensor( [[9 9] [9 9]], shape=(2, 2), dtype=int32)
維度
一維 直接寫個數
二維 用[行,列]
多維 用[n,m,j,k……]
生成隨機數
生成正態分佈的隨機數
預設均值為0,標準差為1
tf.random.normal(維度,mean=均值,stddev=標準差)
生成截斷式正態分佈的隨機數(生成的隨機數更集中一些)
tf.ranodm.truncated_normal(維度,mean=均值,sttdev=標準差)
舉例 對比
import tensorflow as tf
d = tf.random.normal([2,3],mean=0.5,stddev=1) # stddev 標準差
e = tf.random.truncated_normal([2,2],mean=0.5,stddev=1)
print(d)
print(e)
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
tf.Tensor( [[ 2.1269822 1.2042918 -0.28122586] [ 0.25896066 0.15369958 0.72224903]], shape=(2, 3), dtype=float32) tf.Tensor( [[ 1.900454 1.7232051 ] [-0.5688374 -0.36629975]], shape=(2, 2), dtype=float32)
生成指定維度的均勻分佈的隨機數[minval,maxval)
tf.random.uniform(維度,minval=最小值,maxval=最大值) # 前閉後開區間
import tensorflow as tf
f = tf.random.uniform([2,3],minval=0,maxval=1) # stddev 標準差
print(f)
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
tf.Tensor( [[0.29363596 0.731918 0.8976741 ] [0.13689423 0.53846407 0.23545396]], shape=(2, 3), dtype=float32)
常用函式
強制tensor轉換為該資料型別
tf.cast(張量名稱,dtype=資料型別)
計算張量維度上元素的最小值
tf.reduce_min(張量名)
計算張量維度上元素的最大值
tf.reduce_max(張量名)
import tensorflow as tf
x1=tf.constant([1.,2.,3.],dtype=tf.float64)
print(x1)
x2=tf.cast(x1,tf.int32)
print(x2)
print(tf.reduce_min(x2),'\n',tf.reduce_max(x2))
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
tf.Tensor([1. 2. 3.], shape=(3,), dtype=float64) tf.Tensor([1 2 3], shape=(3,), dtype=int32) tf.Tensor(1, shape=(), dtype=int32) tf.Tensor(3, shape=(), dtype=int32)
axis
axis:用於指定操作方向
在一個二維張量或陣列中,可以通過調整axis等於1或者0控制執行維度
- axis=0 代表跨行(經度,down)
- axis=1 代表跨列(維度,across)
- 不指定axis,則所有元素參與計算
計算張量沿著指定維度的平均值
tf.reduce_mean(張量名,axis=操作軸)
計算張量沿著指定維度的和
tf.reduce_sum(張量名,axis=操作軸)
import tensorflow as tf
x=tf.constant([
[1,2,3],
[4,5,6]
])
print(x)
print(tf.reduce_mean(x)) # 計算張量沿著指定維度的平均值 所有元素參與計算
print(tf.reduce_sum(x,axis=1)) #計算張量沿著指定維度的和 跨列操作
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
tf.Tensor( [[1 2 3] [4 5 6]], shape=(2, 3), dtype=int32) tf.Tensor(3, shape=(), dtype=int32) tf.Tensor([ 6 15], shape=(2,), dtype=int32)
tf.Variable()
作用:將變數標記為“可訓練”
被標記的變數會在反向傳播中記錄梯度資訊。神經網路訓練中,常用該函式標記待訓練引數
tf.Variable(初始值)
import tensorflow as tf
# 神經網路初始化引數w
w = tf.Variable(tf.random.normal([2,2],mean=0,stddev=1)) # 生成正態分佈的隨機數 維度為[2,2] 均值為0 標準差為1
# 通過上述操作,就可以在反向傳播中 通過梯度下降更新引數w
import tensorflow as tf w = tf.Variable(tf.random.normal([2,2],mean=0,stddev=1)) print(w)
執行結果
<tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy= array([[ 0.2049946 , 0.1968063 ], [-0.29070154, -0.02642607]], dtype=float32)>
tensorflow中的數學運算
對應元素的四則運算:tf.add,tf.subtract,tf.multiply,tf.divide(加減乘除)
平方:tf.square
次方:tf.pow
開方:tf.sqrt
矩陣乘:tf.matmul
重要:只有兩個維度相同的張量才可以做四則運算
實現兩個張量對應元素相加
tf.add(張量1,張量2)
實現兩個張量對應元素相減
tf.subtract(張量1,張量2)
實現兩個張量對應元素相乘
tf.multiply(張量1,張量2)
實現兩個張量對應元素相除
tf.divide(張量1,張量2)
import tensorflow as tf
a = tf.ones([1,3])
b = tf.fill([1,3],3.)
print(a)
print(b)
print(tf.add(a,b))
print(tf.subtract(a,b))
print(tf.multiply(a,b))
print(tf.divide(b,a))
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float32) tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32) tf.Tensor([[4. 4. 4.]], shape=(1, 3), dtype=float32) tf.Tensor([[-2. -2. -2.]], shape=(1, 3), dtype=float32) tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32) tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
計算某個張量的平方
ft.square(張量名)
計算某個張量的N次方
ft.pow(張量名,n次方數)
計算某個張量的開方
ft.sqrt(張量名)
import tensorflow as tf
a = tf.fill([1,3],3.)
print(a)
print(tf.pow(a,3)) # 三次方
print(tf.square(a)) # 平方
print(tf.sqrt(a)) # 開方
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32) tf.Tensor([[27. 27. 27.]], shape=(1, 3), dtype=float32) tf.Tensor([[9. 9. 9.]], shape=(1, 3), dtype=float32) tf.Tensor([[1.7320508 1.7320508 1.7320508]], shape=(1, 3), dtype=float32)
矩陣乘
tf.matmul(矩陣1,矩陣2)
import tensorflow as tf
a = tf.ones([3,2])
b = tf.fill([2,3],3.)
print(a)
print(b)
print(tf.matmul(a,b))
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
tf.Tensor( [[1. 1.] [1. 1.] [1. 1.]], shape=(3, 2), dtype=float32) tf.Tensor( [[3. 3. 3.] [3. 3. 3.]], shape=(2, 3), dtype=float32) tf.Tensor( [[6. 6. 6.] [6. 6. 6.] [6. 6. 6.]], shape=(3, 3), dtype=float32)
tf.data.Dataset.from_tensor_slices
切分傳入張量的第一維度,生成輸入 特徵/標籤 對,構建資料集
data =tf.data.Dataset.from_tensor_slices((輸入特徵,標籤))
Numpy和Tensor格式都可以用該語句讀入資料
import tensorflow as tf
features = tf.constant([12, 23, 10, 17])
labels = tf.constant([0, 1, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
print(dataset)
for element in dataset:
print(element)
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
<TensorSliceDataset element_spec=(TensorSpec(shape=(), dtype=tf.int32, name=None), TensorSpec(shape=(), dtype=tf.int32, name=None))> (<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=int32, numpy=0>) (<tf.Tensor: shape=(), dtype=int32, numpy=23>, <tf.Tensor: shape=(), dtype=int32, numpy=1>) (<tf.Tensor: shape=(), dtype=int32, numpy=10>, <tf.Tensor: shape=(), dtype=int32, numpy=1>) (<tf.Tensor: shape=(), dtype=int32, numpy=17>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
實現某個函式對指定引數的求導運算
tf.GradientTape
with結構計算過程,gradient求出張量的梯度
with tf.GradientTape() as tape:
若干個計算過程
grad=tape.gradient(函式,對誰求導)
import tensorflow as tf
with tf.GradientTape() as tape:
w = tf.Variable(tf.constant(3.0)) # 標記為“可訓練”
loss = tf.pow(w, 2) # 求w的2次方
# 損失函式loss 對 引數w 的求導數運算
grad = tape.gradient(loss,w)
print(grad)
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
tf.Tensor(6.0, shape=(), dtype=float32)
列舉 enumerate
enumerate是python的內建函式,它可以遍歷每個元素(如列表、元組或者字串),組合為 索引 元素。常在for迴圈中使用
enumerate 列表名
import tensorflow as tf
seq = ['one','two','three']
for i,element in enumerate(seq):
print(i,element)
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
0 one 1 two 2 three
獨熱編碼(one-hot encoding)
在分類問題中,常用獨熱編碼做標籤
標記類別:1表示是,0表示非
tf.one_hot()
該函式將待轉換資料。轉換為one-hot形式的資料輸出
tf.one_hot(待轉化資料,depth=幾分類)
import tensorflow as tf
classes = 3
labels = tf.constant([1,0,2]) # 輸入元素的最小值為0,最大值為2
output = tf.one_hot(labels,depth=classes)
print(output)
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
tf.Tensor( [[0. 1. 0.] [1. 0. 0.] [0. 0. 1.]], shape=(3, 3), dtype=float32)
tf.nn.softmax(x)
作用:使輸出符合概率分佈
當n分類的n個輸出(y0,y1 …… yn-1)通過softmax()函式
便符合概率分佈了。
import tensorflow as tf
y = tf.constant([1.01,2.01,-0.66])
y_pro =tf.nn.softmax(y)
print("After softmax , y_pro is :",y_pro)
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
After softmax , y_pro is : tf.Tensor([0.25598174 0.6958304 0.0481878 ], shape=(3,), dtype=float32)
assign_sub
作用:常用於引數自更新
- 賦值操作,更新引數的返回值並返回
- 呼叫
assign_sub
前,先使用tf.Variable
定義變數w
為可訓練(可自更新)
w.assign_sub(w要自減的內容)
import tensorflow as tf
w = tf.Variable(4)
w.assign_sub(1) # w-=1 即是 w=w-1
print(w)
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>
tf.argmax
作用:返回張量沿指定維度最大值的索引
tf.argmax(張量名,axis=操作軸)
import tensorflow as tf
import numpy as np
test = np.array([[1,2,3],[2,3,4],[5,4,3],[8,7,2]])
print(test)
print(tf.argmax(test,axis=0)) # 返回每一行(經度)最大值的索引
print(tf.argmax(test,axis=1)) # 返回每一行(維度)最大值的索引
python 3.10 tensorflow-gpu 2.8 numpy 1.22.1 | 執行結果
[[1 2 3] [2 3 4] [5 4 3] [8 7 2]] tf.Tensor([3 3 1], shape=(3,), dtype=int64) tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)
作者:萌狼藍天,轉載請註明原文連結:https://www.cnblogs.com/mllt/p/tensorflow01.html | 萌狼藍天@嗶哩嗶哩 | QQ:3447902411(僅限技術交流,新增請說明方向)| 歡迎關注我的嗶哩嗶哩