看了 UeFan写的tensorflow tf.where使用方法,大于某个值为1,小于为0文章,依然有些模糊,自己结合实际注解了一下。
a=tf.random.uniform([2,2]) #随机生成2*2矩阵a
one = tf.ones_like(a) #生成与a大小一致的值全部为1的矩阵
zero = tf.zeros_like(a)
label = tf.where(a <0.5, x=zero, y=one) #0.5为阈值
得到结果:
a: tf.Tensor(
[[0.25626993 0.53764176]
[0.27858937 0.92834556]], shape=(2, 2), dtype=float32)
label: tf.Tensor(
[[0. 1.]
[0. 1.]], shape=(2, 2), dtype=float32)
在numpy中:
threshold=0.5
x = np.where(pred < threshold, 0, 1) #数值小于0.5置0,大于0.5置1