Tensorflow 2.0 基本函數與數學表示

Tensorflow 2.0 基本函數與數學表示

日更不了 所以又把老博客的博客搬來了。。。
之前沒打代碼塊 因爲太多了 所以就不改啦 (「・ω・)「嘿

最近重新看了一下Tensorflow2.0用法。Tensorflow 2代 相比 Tensorflow 1代 有挺多的改動,一開始有的代碼也找不到,後來看了下guide,發現大多代碼都移到了tf.math 數學方程, tf.linalg 線代方程, tf.signal 信號類方程(FFT 傅里葉轉換) 等庫裏。這筆記是爲了我自己以後更好的查找,所以相對的簡約。詳情可在寫代碼時在Jupyter裏, 雙?查看詳情,例如 ??tf.math.add

import tensorflow as tf
print('The version of Tensorflow is ',tf.__version__)
The version of Tensorflow is  2.0.0

1. Basic Create


1.1. Basic

  • tf.constant 簡單的定義
    • scalar 標量
    • vector 向量
    • matrix 矩陣
scalar = tf.constant(1., name='scalar') 
vector = tf.constant([1.,1.,2.,3.,4.,3.,3.,2.,1.,2.], name='vector')
matrix = tf.constant([[1., 2.],[3., 4.]], name ='matrix')
tf.print(scalar,' scalar \n', vector, 'vector \n', matrix, ' matrix')
1  scalar 
 [1 1 2 ... 2 1 2] vector 
 [[1 2]
 [3 4]]  matrix
  • tf.convert_to_tensor(value, dtype=tf.float32): 轉換成 tensor 格式
    • value: Tensor, numpy arrays, python lists, python scalars 可轉換類型
  • tf.zeros([…,a,b], dtype=tf.float32): 創建 …個(a*b) 的空矩陣 01,101,b0a,10a,ba×b,\begin{aligned} \begin{matrix} 0_{1,1} & \dots & 0_{1,b} \\ \dots & \dots & \dots \\ 0_{a,1} & \dots & 0_{a,b} \end{matrix}_{a \times b} ,\dots \end{aligned}
    • tf.ones(shape, dtype=tf.float32): 創建shape的全1矩陣
    • tf.zeros_like(input): 創建相同shape的空矩陣
    • tf.fill(shape,value): 創建shape的全value矩陣
  • tf.identity(input) 恆等映射 類似copy, 輸出相同輸入值
  • tf.cast(value, dtype): 類型轉換
    • dtypes: uint8, uint16, uint32, uint64, int8, int16, int32, int64, float16, float32, float64, complex64, complex128, bfloat16.
    • For complex number, only real part of value is return
  • tf.shape(input, out_type=tf.int32)
    • tensor.shape
  • tf.size(input, out_type=tf.int32)
  • tf.rank(input, out_type=tf.int32)
  • tf.reshape(input, shape)
  • tf.expand_dims(input, axis) 插入一維
  • tf.slice(input_, begin, size) 切片
  • tf.split(split_dim, num_split, value, name=‘split’) 分離
  • tf.concat(values, axis, name=‘concat’) 連結合並
  • tf.reverse(tensor, axis, name=None) 序列反轉
  • tf.transpose(a, perm=None, conjugate=False, name=‘transpose’) 調換維度順序
  • tf.gather() 合併索引indices所指示params中的切片
  • tf.one_hot()
tf.one_hot([0,2,3,2],4, on_value=5, off_value=0)
<tf.Tensor: id=10, shape=(4, 4), dtype=int32, numpy=
array([[5, 0, 0, 0],
       [0, 0, 5, 0],
       [0, 0, 0, 5],
       [0, 0, 5, 0]])>
  • tf.print(): print() in Tensorflow
  • tf.summary…: summary tag used for TensorBoard

1.2. Distribution

  • tf.random.unifrom 隨機均勻分佈

    • minval, maxval: 最小與最大值
  • tf.random.normal 隨機正態分佈

    • mean: 正態分佈的均值
    • stddev: 正態分佈的標準差
    • tf.random.truncated_normal 截斷正態分佈
random_uniform_2_2 = tf.random.uniform([2,2],minval=0,maxval=1,name='uniform_distribution')
tf.print('Uniform distribution: \n', random_uniform_2_2)

random_normal_2_2 = tf.random.normal([2,2], mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name='normal_distribution')
tf.print('Normal distribution: \n', random_normal_2_2)
Uniform distribution: 
 [[0.067463994 0.870353]
 [0.81344986 0.0281436443]]
Normal distribution: 
 [[1.282112 -0.353030533]
 [-0.508329332 1.42963946]]

1.3. Loop

  • 使用 tf.while_loop 實現 for loop
    • cond: 返回 bool 值
    • body: 返回 input 的相同格式的值
def cond(a,b)->bool: return a< 5 # return bool formate
def body(a,b): return a+1, tf.add(b,b) # return same formate as input
tf.print('For 5 loops: ', tf.while_loop(cond, body, [1,scalar],name='for5loop'))
For 5 loops:  (5, 16)

2. Mathematic Symbols with tf


2.1. math

Using tf.math

  • tf.add(a,b): ai+bia_i + b_i 加法 兩個相加
  • tf.add_n([a,b,c, …]): ai+bi+ci+a_i + b_i + c_i + \dots 幾個數相加
  • tf.multiply(a,b, name=‘dot_product’): ai×bia_i \times b_i elements dot product 元素相乘
matrix1 = tf.constant([[2., 3.],[1., 4.]])
matrix2 = tf.constant([[4., 3.],[2., 1.]])
tf.print('Add: ', matrix + matrix1 + matrix2)
tf.print('Add: ', tf.add(matrix, matrix2,name='add'))
tf.print('Add element wise: ', tf.add_n([matrix,matrix1, matrix2],name='addwise'))
tf.print('Multiply(dot_product): ', tf.multiply(matrix,matrix2,name='multi'))
Add:  [[7 8]
 [6 9]]
Add:  [[5 5]
 [5 5]]
Add element wise:  [[7 8]
 [6 9]]
Multiply(dot_product):  [[4 6]
 [6 4]]
  • tf.subtract(a,b, name=‘minus’): aibia_i - b_i 減法

  • tf.divide(a,b, name =‘divide’): ai÷bia_i \div b_i 除法

  • tf.pow(a,b): aba^b Power 冪

  • tf.square(a): ai2a_i^2 平方

  • tf.sqrt(a): ai\sqrt{a_i} 平方根

  • tf.negative(a): ai- a_i 取負

  • tf.abs(a): vertaivert a_i \vert 絕對值

  • tf.sign(a): sign(ai)=1 if ai<0;0 if ai==0;1 if ai>0sign(a_i) = -1 \ \mathrm{if} \ a_i < 0; 0 \ \mathrm{if}\ a_i == 0; 1 \ \mathrm{if} \ a_i > 0 取符號

  • tf.exp(a): eaie^{a_i} 自然數e指數取值

  • tf.math.reciprocal(a): 1ai\frac{1}{a_i} 取倒數

  • tf.round(a): round “四捨五入”

  • tf.math.ceil(a): a\lceil a \rceil 向上取整

  • tf.math.floor(a): a\lfloor a \rfloor 向下取整

  • tf.math.rint(a): most close integer 取最近整數

  • 三角函數:

    • tf.math.cos(a): cos(a)\cos{(a)}
    • tf.math.cosh(a): cosh(a)\cosh{(a)}
    • etc.
tf.math.cosh(matrix)
<tf.Tensor: id=45, shape=(2, 2), dtype=float32, numpy=
array([[ 1.5430807,  3.7621956],
       [10.067662 , 27.308233 ]], dtype=float32)>

Complex number

  • tf.complex(real_tensor, imag_tensor, name=None)
  • tf.abs(x, name=None) 複數絕對值(長度)
  • tf.math.conj(input, name=None) 共軛複數
  • tf.math.image(input, name=None) 取虛數
  • tf.math.real(input, name=None) 取實數
  • tf.signal.fft(input, name=None) Fast Fourier transform 傅里葉變換

2.2. Linear Algebra

Using tf.linalg


Calculate Matrix

  • tf.matmul(A,B): A×BA \times B matrixs times 矩陣乘法
  • tf.linalg.inv(A): A1A^{-1} inverse matrix 逆矩陣
  • tf.linalg.matrix_transpose(A): AA^\top 矩陣軸變換(最後兩維進行轉置)
  • tf.linalg.adjoint(A): conjugates last two dimensions of matrix AA^* 伴隨矩陣
  • tf.linalg.matvect(A,B): [a1,a2,,ai]j×[b1,b2,,bi]j[a_1, a_2, \dots, a_i]_j \times [b_1, b_2, \dots, b_i]_j 橫向相乘

Matrix Create

  • tf.linalg.diag([a,b,…]): Diagonal matrix -> a000b000\begin{aligned} \begin{matrix} a & 0 & 0 \\ 0 & b & 0 \\ 0 & 0 & \dots \end{matrix}\end{aligned}
  • tf.eye(num_rows): Identity matrix -> 10001000\begin{aligned} \begin{matrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & \dots \end{matrix}\end{aligned}

Matrix compute

  • tf.linalg.eigh(A): return eigenvalues, eigenvectors
  • tf.linalg.trace(A): Trace of A 對角線和 (矩陣跡)
  • tf.linalg.norm(A, ord=‘euclidean’): norm of A 求範數
  • tf.matrix_determinant(input, name=None): 返回方陣的行列式
tf.print('Multiply(matrix): \n', tf.matmul(matrix,matrix2,name='matrixmulti'))
Multiply(matrix): 
 [[8 5]
 [20 13]]

3. Functions 函數


3.1. Basic

  • params: input_tensor, axis=None, keepdims=False, name=None
    • keepdims: 是否保留原維度
    • axis = 0: horizontal 橫向
    • axis = 1: vertical 縱向
  • tf.reduce_mean() 求平均數
  • tf.reduce_max() 求最大值
  • tf.reduce_sum() 求所有和
  • tf.reduce_prod() 求所有乘積
  • tf.reduce_logsumexp() 求 log(i=1(eai))\log( \sum_{i=1}{(e^{a_i})})
  • tf.reduce_all(bool_input) 求所有值是否都是正確
  • tf.reduce_any(bool_input) 求所有值是否有正確
  • tf.math.count_nonzero() 計算非零數
tf.print('Mean value: \n', tf.reduce_mean(matrix,0,True))
tf.print('Production value: \n', tf.reduce_prod(matrix))
tf.print('Matrix1: \n', matrix1)
tf.print('Argmax horizontal: \n', tf.argmax(matrix1,1))
tf.print('Argmax vertical: \n', tf.argmax(matrix1,0))
Mean value: 
 [[2 3]]
Production value: 
 24
Matrix1: 
 [[2 3]
 [1 4]]
Argmax horizontal: 
 [1 1]
Argmax vertical: 
 [0 1]

  • 大小比較

    • 對比元素, 返回 bool 值
  • tf.equal(a,b)

  • tf.not_equal(a,b)

  • tf.less(a,b)

  • tf.less_equal(a,b)

  • tf.greater(a,b)

  • tf.greater_equal(a,b)


  • tf.unique(value, out_idx = tf.int32): 輸出唯一值與它的座標index
  • tf.where(bool_input, x=None, y=None): 輸出每個True的座標 若x,y爲空
  • tf.argmax(pred, axis=1) 返回最大數值所在的座標
  • tf.argmin(pred, axis=1) 返回最小數值所在的座標
  • tf.math.invert_permutation(value) 返回反座標
tf.print('Does two matrixs equal: \n', tf.equal(matrix, matrix1))
tf.print('Get vector unique: \n', tf.unique(vector))
Does two matrixs equal: 
 [[0 0]
 [0 1]]
Get vector unique: 
 Unique(y=[1 2 3 4], idx=[0 0 1 ... 1 0 1])

3.2. Loss Function 損失函數

  • L2 Norm
    • tf.nn.l2_loss(x): t22\frac{\sum {t^2}}{2}
  • Cross Entropy 交叉熵函數
    • tf.nn.softmax_cross_entropy_with_logits(pred, y)
tf.print('Cross entropy: ', tf.nn.softmax_cross_entropy_with_logits(matrix,matrix2))
Cross entropy:  [2.939785 6.19283152]

3.3. Neural Network

  • tf.sigmoid(x) sigmoid 激活: 1(1+ex)\frac{1}{(1+e^{-x})}
    • 還可用其他形式: tf.nn.sigmoid(x), tf.math.sigmoid(x)
  • tf.nn.relu(x) 整流函數: max(x,0)\max (x,0)
  • tf.nn.relu(x) 以6爲閾值的整流函數: min(max(x,0),6)\min (\max(x,0),6)
  • tf.nn.elu(x) exponential linear: ex1 if <0 otherwise xe^x -1 \ \text{if}\ < 0 \ \text{otherwise}\ x
  • tf.nn.softplus(x): log(ex+1)\log{(e^x +1)}
  • tf.nn.dropout(x,rate,noise_shape=None,seed=None): rate=0.1 drop 10% of x
  • tf.nn.bias_add(value, 1D_bias, data_format=None): 加一偏置量
  • tf.nn.tanh(x) hyperbolic tangent 雙曲線切線激活函數: [inf,inf][1,1][-\inf, \inf] \to [-1,1]
  • tf.nn.l2_normalize(x, axis=None, epsilon=1e-12) L2範式標準化: xmax(x2, ϵ)\frac{x}{\sqrt{\max(\sum x^2, \ \epsilon)}}
  • tf.nn.softmax(x, axis=-1): exi,j(exi,j,axis)\frac{e^{x_{i,j}}}{\sum(e^{x_{i,j}}, \text{axis})}
  • tf.nn.log_softmax(x, axis=-1): xi,jln((exi,j,axis))x_{i,j} - \ln(\sum (e^{x_{i,j}}, \text{axis}))
  • [Others NN or RNN]
tf.print('Sigmoid: ', tf.sigmoid(matrix, name='sigmoid'))
Sigmoid:  [[0.731058598 0.880797]
 [0.952574134 0.982013762]]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章