前言
以下内容中使用環境為 tensorflow 2.3.0
且
import tensorflow as tf
1. 張量
1.1 建立
tf.constant(張量)
例子:
x=tf.constant([[2,3],[1,5]])
print(x)
輸出:

1.2 操作(張量,shape(形狀),dtype(資料類型))
由上圖輸出圖中可以清楚看到其資料中包含三個元素:張量,shape(形狀),dtype(資料類型),而調用這些資料的處理方式:
資料 | 導出方式 |
---|---|
張量 | .numpy() |
shape | .shape |
dtype | .dtype |
例子:
#續上文
#x=tf.constant([[2,3],[1,5]])
x.numpy()
print('dtype:',x.dtype)
print('shape:',x.shape)
輸出:
1.3 其他的特殊建立(全0,全1,随機)
1.3.1 全0,全1建立
tf.one(shape=(...)) 建立一個大小為...的全1張量
tf.zero(shape=(...)) 建立一個大小為...的全0張量
例子:
print(tf.ones(shape=(2, 1)))
print(tf.zeros(shape=(2, 1)))
1.3.2 随機生成(正态分布,均勻分布)
1.3.2.1 正态分布
tf.random_normal()函數用于從“服從指定正态分布的序列”中随機取出指定個數的值。
參數:
tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)
shape: 輸出張量的形狀,必選
mean: 正态分布的均值,預設為0
stddev: 正态分布的标準差,預設為1.0
dtype: 輸出的類型,預設為tf.float32
seed: 随機數種子,是一個整數,當設定之後,每次生成的随機數都一樣
name: 操作的名稱
例子:
輸出:
1.3.2.2 均勻分布
random_uniform(shape,minval=0,maxval=None,dtype=tf.float32,seed=None,name=None)
shape:一維整數張量或python數組輸出張量形狀
minval:dtype類型的0-D張量或python值;生成的随機值範圍的下限,預設為0
maxval:dtype類型的0-D張量或python值;生成的随機值範圍的上限,如果dtype為float,預設為1
dtype:輸出的類型:float16,float32,float64,int32,int64
seed:seed: 随機數種子,是一個整數,當設定之後,每次生成的随機數都一樣
name: 操作的名稱
例子:
輸出:
2. 變量
變量是用于存儲可變狀态(如神經網絡權重)的特殊張量。
2.1 建立
變量的建立是基于張量上的,Variable()這個構造函數需要初始值,這個初始值可以是一個任何類型任何形狀的Tensor,初始值的形狀和類型決定了這個變量的形狀和類型。構造之後,這個變量的形狀和類型就固定了。
“”
函數:tf.Variable(常量名稱)
例子:
initial_value = tf.random.normal(shape=(2, 2))
a = tf.Variable(initial_value)
print(a)
輸出:
2.2 操作(指派,加法,減法)
函數 | 作用 |
---|---|
assign(value, use_locking=False) | 為變量指定一個新的值 |
assign_add(delta, use_locking=False) | 為這個變量加上一個值 |
assign_sub(delta, use_locking=False) | 為這個變量減去一個值 |
read_value() | 傳回這個變量的值,在目前的上下文中讀取。傳回的是一個含有這個值的Tensor |
set_shape(shape) | 改變變量形狀 |
new_value = tf.random.normal(shape=(2, 2))
a.assign(new_value)
#---------------------------------------------
# The values above are the same as those below
#---------------------------------------------
for i in range(2):
for j in range(2):
assert a[i, j] == new_value[i, j]
added_value = tf.random.normal(shape=(2, 2))
a.assign_add(added_value)
#---------------------------------------------
# The values above are the same as those below
#---------------------------------------------
for i in range(2):
for j in range(2):
assert a[i, j] == new_value[i, j] + added_value[i, j]
3. 在TensorFlow中進行數學運算
3.1 簡單的加減,開方,e的幂
a = tf.random.normal(shape=(2, 2))
b = tf.random.normal(shape=(2, 2))
c = a + b
d = tf.square(c)
e = tf.exp(d)
print(a)
print(b)
print(c)
print(d)
print(e)
輸出:
3.2 計算梯度 GradientTape
可參考:TensorFlow學習(四):梯度帶(GradientTape),優化器(Optimizer)和損失函數(losses)