TensorFlow中用於評估模型在訓練集和測試集上的準確度的幾個常用函式說明
阿新 • • 發佈:2019-02-08
1. tf.argmax() | tf.argmin()
tf.argmax(input=tensor,dimention=axis)
找到給定的張量tensor中在指定軸axis上的最大值/最小值的位置。
a=tf.get_variable(name='a',
shape=[3,4],
dtype=tf.float32,
initializer=tf.random_uniform_initializer(minval=-1,maxval=1))
b=tf.argmax(input=a,dimension=0 )
c=tf.argmax(input=a,dimension=1)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
print(sess.run(a))
#[[ 0.04261756 -0.34297419 -0.87816691 -0.15430689]
# [ 0.18663144 0.86972666 -0.06103253 0.38307118]
# [ 0.84588599 -0.45432305 -0.39736366 0.38526249]]
print(sess.run(b))
#[2 1 1 2]
print(sess.run(c))
#[0 1 0]
2. tf.equal()
tf.equal(x, y, name=None):
判斷兩個tensor是否每個元素都相等。返回一個格式為bool的tensor
- 引數:
- x: 一個tensor. 必須是以下型別:half, float32, float64, uint8, int8, int16, int32, int64, complex64, quint8, qint8, qint32, string, bool, complex128
- y: 一個tensor. 必須與x 的資料型別一致。
- name: 自定義操作的名稱 (可選)。
import tensorflow as tf
A = tf.constant([1, 3, 4, 5, 6])
B = tf.constant([1, 3, 4, 3, 2])
with tf.Session() as sess:
print(sess.run(tf.equal(A, B)))
# 輸出[ True True True False False]
3. tf.cast()
tf.cast(x, dtype, name=None)
將x的資料格式轉化成dtype.例如,原來x的資料格式是bool,那麼將其轉化成float以後,就能夠將其轉化成0和1的序列。反之也可以
a = tf.Variable([1,0,0,1,1])
b = tf.cast(a,dtype=tf.bool)
sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())
print(sess.run(b))
#[ True False False True True]
4. tf.reduce_mean()
tf.reduce_mean(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None)
引數說明:
- input_tensor: 需要求平均值的張量。應該存在數字型別。
- axis: 需要求平均值的維度. 如果沒有設定(預設情況),所有的維度都會被減值。
- keep_dims: 如果為真,維持減少的維度長度為1..
- name: 操作的名字(可選值).
- reduction_indices: 舊的axis引數的名字(已棄用)
可跨越維度的計算張量各元素的平均值。
- 根據給出的axis在input_tensor上求平均值。除非keep_dims為真,axis中的每個的張量秩會減少1。如果keep_dims為真,求平均值的維度的長度都會保持為1.
- 如果不設定axis,所有維度上的元素都會被求平均值,並且只會返回一個只有一個元素的張量。
x = [[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.]