天天看點

tensorflow筆記01tf.clip_by_value的用法tf.reduce_mean函數

tf.clip_by_value的用法

tf.clip_by_value(A, min, max):輸入一個張量A,把A中的每一個元素的值都壓縮在min和max之間。小于min的讓它等于min,大于max的元素的值等于max。

import tensorflow as tf;
import numpy as np;
 
A = np.array([[1,1,2,4], [3,4,8,5]])
 
with tf.Session() as sess:
	print sess.run(tf.clip_by_value(A, 2, 5))

           

輸出:

[[2 2 2 4]

[3 4 5 5]]

tf.reduce_mean函數

tf.reduce_mean 函數用于計算張量tensor沿着指定的數軸(tensor的某一次元)上的的平均值,主要用作降維或者計算tensor(圖像)的平均值。

reduce_mean(input_tensor,
                axis=None,
                keep_dims=False,
                name=None,
                reduction_indices=None)

           

第一個參數input_tensor: 輸入的待降維的tensor;

第二個參數axis: 指定的軸,如果不指定,則計算所有元素的均值;

第三個參數keep_dims:是否降次元,設定為True,輸出的結果保持輸入tensor的形狀,設定為False,輸出結果會降低次元;

第四個參數name: 操作的名稱;

第五個參數 reduction_indices:在以前版本中用來指定軸,已棄用;

以一個次元是2,形狀是[2,3]的tensor舉例:

import tensorflow as tf
 
x = [[1,2,3],
      [1,2,3]]
 
xx = tf.cast(x,tf.float32)
 
mean_all = tf.reduce_mean(xx, keep_dims=False)
mean_0 = tf.reduce_mean(xx, axis=0, keep_dims=False)
mean_1 = tf.reduce_mean(xx, axis=1, keep_dims=False)
 
 
with tf.Session() as sess:
    m_a,m_0,m_1 = sess.run([mean_all, mean_0, mean_1])
 
print m_a    # output: 2.0
print m_0    # output: [ 1.  2.  3.]
print m_1    #output:  [ 2.  2.]

           

如果設定保持原來的張量的次元,keep_dims=True ,結果:

print m_a    # output: [[ 2.]]
print m_0    # output: [[ 1.  2.  3.]]
print m_1    #output:  [[ 2.], [ 2.]]
           

類似函數還有:

tf.reduce_sum :計算tensor指定軸方向上的所有元素的累加和;

tf.reduce_max : 計算tensor指定軸方向上的各個元素的最大值;

tf.reduce_all : 計算tensor指定軸方向上的各個元素的邏輯和(and運算);

tf.reduce_any: 計算tensor指定軸方向上的各個元素的邏輯或(or運算);

繼續閱讀