Tensorflow 张量运算2:张量比较

常用的比较函数:tf.equal,tf.greater, tf.less,tf.greater_equal,tf.less_equal,tf.not_equal,tf.is_nan。也可以通过tf.math.equal调用。

import tensorflow as tf 
# 用正态分布来模拟100个样本的预测结果,可以认为是100个MNIST样本
out = tf.random.normal([100,10])
out = tf.nn.softmax(out, axis=1)
# 选取预测值,通过计算最大值所在的索引
pred = tf.argmax(out,axis=1)
'''输出
tf.Tensor(
[7 9 8 1 3 7 9 6 1 8 6 7 2 9 0 9 2 3 3 8 2 5 7 3 5 1 0 1 0 0 8 5 1 7 9 6 4
 3 2 7 3 7 1 0 7 1 8 1 6 9 2 5 9 9 7 0 0 4 8 0 5 0 3 2 7 9 4 8 2 5 7 6 1 3
 1 9 6 0 5 4 7 6 1 2 8 9 1 2 3 8 6 5 4 5 5 2 1 5 1 0], shape=(100,), dtype=int64)
'''

# 用随机函数来表示我们的真实标签
y = tf.random.uniform([100],dtype = tf.int64, maxval=10)
'''输出
tf.Tensor(
[4 4 0 5 8 4 6 4 3 5 7 8 6 2 0 1 3 6 8 5 8 3 1 2 8 2 3 3 9 5 7 7 0 1 8 9 0
 6 4 7 9 8 6 3 1 5 0 5 4 8 8 0 9 3 7 6 1 0 1 5 2 2 7 9 5 6 1 8 2 0 7 4 2 1
 0 5 3 7 8 4 9 6 3 0 3 2 8 5 4 1 8 3 6 6 8 8 5 0 6 6], shape=(100,), dtype=int64)
'''

# 比较真实标签和预测结果,返回布尔型值
out = tf.equal(pred,y)
# 将布尔型结果转换为float32,True转换为1,False转换为0
out = tf.cast(out,dtype=tf.float32)
'''输出
tf.Tensor(
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.
 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.
 0. 0. 0. 0. 1. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 0. 1. 0.
 0. 0. 0. 0. 0. 0. 0. 1. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
 0. 0. 0. 0.], shape=(100,), dtype=float32)
'''
# 统计正确的值
acc = tf.reduce_sum(out)
'''输出
tf.Tensor(9.0, shape=(), dtype=float32)
所以,我们随机产生的预测数据的准确度为9/100 = 9%
'''
发布了93 篇原创文章 · 获赞 2 · 访问量 3038

猜你喜欢

转载自blog.csdn.net/qq_40041064/article/details/104793989