1. 程式人生 > >『TensorFlow』簡單的數學計算&張量操作

『TensorFlow』簡單的數學計算&張量操作

cep 裁剪 rec arr variable sum() 乘法 減法 nump

tf.pow()

tf.sqrt()

tf.add()

tf.add_n()

tf.subtract() :減法

tf.matmul() :矩陣乘法

tf.reduce_sum() :求和

tf.reduce_mean():求均值,直接給源碼定義中的註釋

For example:
  ```python
  # ‘x‘ is [[1., 1.]
  #         [2., 2.]]
  tf.reduce_mean(x) ==> 1.5
  tf.reduce_mean(x, 0) ==> [1.5, 1.5]
  tf.reduce_mean(x, 1) ==> [1.,  2.]
  ```
reduction_indices: The old (deprecated) name for axis.

tf.cast():

bool->數字

re = tf.cast([True,False],tf.float32)
sess = tf.Session()
sess.run(re)
# Out[6]: 
# array([ 1.,  0.], dtype=float32)

tf.argmax:

(list,維度)

re = tf.argmax([[0,0.5]],1)
sess.run(re)
# Out[20]: 
# array([1])

tf.squeeze():

數據降維,只裁剪等於1的維度

不指定維度則裁剪所有長度為1的維度

import tensorflow as tf

arr = tf.Variable(tf.truncated_normal([3,4,1,6,1], stddev=0.1))

sess = tf.Session()
sess.run(tf.global_variables_initializer())

sess.run(arr).shape
# Out[12]: 
# (3, 4, 1, 6, 1)
sess.run(tf.squeeze(arr,[2,])).shape
# Out[17]: 
# (3, 4, 6, 1)
sess.run(tf.squeeze(arr,[2,4])).shape
# Out[16]: 
# (3, 4, 6)
sess.run(tf.squeeze(arr)).shape
# Out[19]: 
# (3, 4, 6)

tf.nn.softmax()分類器:

把數組最後一維轉化為概率分布

import  tensorflow as tf  
sess.run(tf.nn.softmax([1.,2.,3.,4.]))
# Out[12]: 
# array([ 0.0320586 ,  0.08714432,  0.23688281,  0.64391422], dtype=float32)
sess.run(tf.nn.softmax([1.,1.,1.,1.]))
# Out[13]: 
# array([ 0.25,  0.25,  0.25,  0.25], dtype=float32)
sess.run(tf.nn.softmax([[1.,1.,1.,1.],[7.,1.,1.,1.]]))
# Out[16]: 
# array([[ 0.25      ,  0.25      ,  0.25      ,  0.25      ],
#        [ 0.99261862,  0.00246046,  0.00246046,  0.00246046]], dtype=float32)

tf.concat([t1,t2,t3...],dim):

矩陣拼接,註意在1.x版本之前和之後dim和[t]的順序是改變了的

這個函數乍看之下不好理解合成方向,實際把合成張量轉化為np數組查看shape後就很好理解了:

import tensorflow as tf
import numpy as np
t1 = np.asarray([[1, 2, 3], [4, 5, 6]])
t2 = np.asarray([[7, 8, 9], [10, 11, 12]])
print(t1.shape)
# (2, 3)
# 第零維度合成就是擴展數字2的大小
re = tf.concat([t1, t2],0) 
sess = tf.Session()
sess.run(re)
# array([[ 1,  2,  3],
#        [ 4,  5,  6],
#        [ 7,  8,  9],
#        [10, 11, 12]])

# 第一維度合成就是擴展數字3的大小
re = tf.concat([t1, t2],1) 
sess = tf.Session()
sess.run(re)
# array([[ 1,  2,  3,  7,  8,  9],
#        [ 4,  5,  6, 10, 11, 12]])

t1 = np.zeros([2,3,3])
t2 = np.ones([2,3,3])
print(t1,‘\n\n‘,t2)
re = tf.concat([t1, t2],2) 
sess = tf.Session()
sess.run(re)

# 第二維度合成就是擴展末尾的數字3的大小
# array([[[ 0.,  0.,  0.,  1.,  1.,  1.],
#         [ 0.,  0.,  0.,  1.,  1.,  1.],
#         [ 0.,  0.,  0.,  1.,  1.,  1.]],

#        [[ 0.,  0.,  0.,  1.,  1.,  1.],
#         [ 0.,  0.,  0.,  1.,  1.,  1.],
#         [ 0.,  0.,  0.,  1.,  1.,  1.]]])

作為參考合成神經網絡輸出的時候在深度方向(inception_v3)是數字3,[batch,heigh,width,depth]。

『TensorFlow』簡單的數學計算&張量操作