1 tf.argmax()简介
tf.argmax(vector, 1):返回的是vector中的最大值的索引号,如果vector是一个向量,那就返回一个值,如果是一个矩阵,那就返回一个向量,这个向量的每一个维度都是相对应矩阵行的最大值元素的索引号。
tf.argmax(input=tensor,dimention=axis) 找到给定的张量tensor中在指定轴axis上的最大值/最小值的位置。
实例1
import numpy as np import tensorflow as tf A = np.arange(1, 8, 2).reshape(1, 4) print("A:", A) B = np.arange(1, 7).reshape(2, 3) print("B:", B) with tf.Session() as sess: print("A中沿X轴最大值的索引为:", sess.run(tf.argmax(A, 1))) print("A中沿Y轴最大值的索引为:", sess.run(tf.argmax(A, 0))) print("B中沿X轴最大值的索引为:", sess.run(tf.argmax(B, 1))) print("B中沿Y轴最大值的索引为:", sess.run(tf.argmax(B, 0)))
结果
实例2
import tensorflow as tf 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.initialize_all_variables()) 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]
结果:
实例来自:https://blog.csdn.net/liyaoqing/article/details/54020202
2 tf.reduce_mean()
求平均值:tf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None)
实例
import numpy as np import tensorflow as tf A = np.arange(0, 6).reshape(2, 3) print("A:", A) with tf.Session() as sess: print("A中所有值的平均值为:", sess.run(tf.reduce_mean(tf.cast(A, tf.float32)))) print("A中沿X轴平均值为:", sess.run(tf.reduce_mean(A, 1))) print("A中沿Y轴平均值为:", sess.run(tf.reduce_mean(A, 0)))
结果:
A: [[0 1 2] [3 4 5]] A中所有值的平均值为: 2.5 A中沿X轴平均值为: [1 4] A中沿Y轴平均值为: [1 2 3] [Finished in 2.3s]
3 tf.reduce_sum()
按某个轴求和
实例
import numpy as np import tensorflow as tf A = np.arange(0, 6).reshape(2, 3) print("A:", A) with tf.Session() as sess: print("A中所有值的和为:", sess.run(tf.reduce_sum(tf.cast(A, tf.float32)))) print("A中沿X轴和为:", sess.run(tf.reduce_sum(A, 1))) print("A中沿Y轴和为:", sess.run(tf.reduce_sum(A, 0)))
结果
A: [[0 1 2] [3 4 5]] A中所有值的和为: 15.0 A中沿X轴和为: [ 3 12] A中沿Y轴和为: [3 5 7] [Finished in 2.4s]
4 tf.equal()
tf.equal(real, prediction)是对比这两个矩阵或者向量的相等的元素,如果是相等的那就返回True,反正返回False,返回的值的矩阵维度和real是一样的,我们会在求准确率的时候经常用到它
实例
import tensorflow as tf import numpy as np real = [[1, 3, 4, 5, 6]] # 真实值 prediction = [[1, 3, 4, 3, 2]] # 预测值 with tf.Session() as sess: correct_preds = tf.equal(real, prediction) # print(sess.run(correct_preds)) correct_preds_num = tf.cast(correct_preds, tf.float32) print(sess.run(correct_preds_num)) accuracy = tf.reduce_mean(correct_preds_num) print(sess.run(accuracy))True True True False False]] [[1. 1. 1. 0. 0.]] 0.6 0.6 [Finished in 2.0s] # 等同于 accuracy = tf.reduce_mean(tf.cast(correct_preds, tf.float32)) print(sess.run(accuracy))
结果:
[[ True True True False False]] [[1. 1. 1. 0. 0.]] 0.6 0.6 [Finished in 2.0s]