tf.where 和 tf.cond对比

本文对比了TensorFlow中tf.where和tf.cond的功能与用法。tf.cond适用于函数级别的条件判断,而tf.where则用于具体数值计算的选择。通过示例代码展示了两者在不同场景下的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tf.where 和 tf.cond都是类似于if…else 的逻辑操作,现对比两者区别

import tensorflow as tf 

pred=tf.placeholder(dtype=tf.bool,name='bool') 
x=tf.constant(1) 
y = tf.cond(pred,lambda:x+1,lambda:x-1) 
z=tf.where(pred,x+1,x-1) 
with tf.Session() as sess: 
	sess.run(tf.global_variables_initializer()) 
	y1,z1=sess.run([y,z],feed_dict={pred:True}) 
	y2,z2=sess.run([y,z],feed_dict={pred:False})

我们可以看出,用法几乎一样,不过,tf.cond针对的是函数,而tf.where针对的是具体计算


原作者:GAN_player
来源:优快云
原文:https://blog.youkuaiyun.com/GAN_player/article/details/77777644

class ClassSpecificPrecision(tf.keras.metrics.Metric): def __init__(self, class_id, num_classes=8, name="class_precision", **kwargs): """ 为指定类别计算精确率 参数: class_id: 要计算精确率的类别ID (0-7) num_classes: 总类别数 (默认为8) name: 指标名称 """ super().__init__(name=name, **kwargs) self.class_id = class_id self.num_classes = num_classes # 初始化真正例(TP)预测正例(PP)计数器 self.true_positives = self.add_weight( name="tp", initializer="zeros", dtype=tf.float32) self.predicted_positives = self.add_weight( name="pp", initializer="zeros", dtype=tf.float32) def update_state(self, y_true, y_pred, sample_weight=None): # 将标签转换为整数类型 y_true = tf.cast(y_true, tf.int32) # 获取预测类别 (形状: [batch_size]) y_pred_class = tf.argmax(y_pred, axis=-1, output_type=tf.int32) # 计算真正例 (TP): 实际为class_id且预测为class_id true_positive = tf.logical_and( tf.equal(y_true, self.class_id), tf.equal(y_pred_class, self.class_id) ) # 计算预测正例 (PP): 预测为class_id (不论实际类别) predicted_positive = tf.equal(y_pred_class, self.class_id) # 应用样本权重 (如果提供) if sample_weight is not None: true_positive = tf.cast(true_positive, tf.float32) * sample_weight predicted_positive = tf.cast(predicted_positive, tf.float32) * sample_weight else: true_positive = tf.cast(true_positive, tf.float32) predicted_positive = tf.cast(predicted_positive, tf.float32) # 更新状态变量 self.true_positives.assign_add(tf.reduce_sum(true_positive)) self.predicted_positives.assign_add(tf.reduce_sum(predicted_positive)) def result(self): # 避免除以零错误 return tf.where( self.predicted_positives > 0, self.true_positives / self.predicted_positives, 0.0 ) def reset_state(self): # 重置计数器 self.true_positives.assign(0.0) self.predicted_positives.assign(0.0) 上面自定义的指标输出为什么会超过100.0
最新发布
07-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值