gpt4 book ai didi

python - Tensorflow:如何设计自定义成本函数?

转载 作者:太空宇宙 更新时间:2023-11-04 02:12:13 26 4
gpt4 key购买 nike

我是一名学习对象检测的学生。我用 FCN 实现了一个简单的对象查找模型。准确率为 95% 但召回率为 0。简而言之,模型已确定所有区域都没有物体。我使用 softmax_cross_entropy 作为误差函数。但是,如果模型判断存在物体的部分没有物体,我想就大错特错了。我想我必须自己设计损失函数,我该怎么办?

def model(X, P):
x = tf.cast(X, tf.float32)
x = x / 255.0

net = slim.conv2d(x, 32, kernel_size =(3, 3))
net = slim.max_pool2d(net, (2, 2)) # 128 160
net = slim.conv2d(net, 64, kernel_size =(3, 3))
net = slim.max_pool2d(net, (2, 2)) # 64 80
net = slim.conv2d(net, 128, kernel_size =(3, 3))
net = slim.max_pool2d(net, (2, 2)) # 32 40
net = slim.conv2d(net, 256, kernel_size =(3, 3))
net = slim.max_pool2d(net, (2, 2)) # 16 20
net = slim.conv2d(net, 512, kernel_size=(3, 3))
net = slim.max_pool2d(net, (2, 2)) # 8 10
net = tf.nn.dropout(net, keep_prob=P)
net = slim.conv2d(net, 2, kernel_size=(3, 3))
net = slim.max_pool2d(net, (2, 2)) # 4 5

X = tf.placeholder(tf.uint8 ,[None, 320, 256, 3])
Y = tf.placeholder(tf.int64, [None, 20])
P = tf.placeholder(tf.float32)
y = tf.reshape(Y, (-1, 5, 4))
logits = model(X,P)
arg = tf.argmax(logits, -1)
with tf.name_scope('Optimizer'):
cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y))
optimizer = tf.train.AdadeltaOptimizer(0.001).minimize(cost)

enter image description here

最佳答案

您正在使用 sparse_softmax_cross_entropy ,这已经允许您增加损失的权重:

tf.losses.sparse_softmax_cross_entropy(
labels,
logits,
weights=1.0,
...

weights acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If weights is a tensor of shape [batch_size], then the loss weights apply to each corresponding sample.

如果您的 y 是二进制的(1 表示对象,0 表示空),您可以简单地将其乘以所需的因子并将其作为权重传递:

penalty_empty = 0.5
penalty_object = 1

weights = penalty_empty + y * (penalty_object - penalty_empty)

关于python - Tensorflow:如何设计自定义成本函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53480391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com