Keras从自定义损失函数中获取批次中的图像数量的y_pred侧

2024-09-26 22:53:53 发布

您现在位置:Python中文网/ 问答频道 /正文

在这个损失函数中,我需要创建完整的指标,这取决于批处理的图像数量和图像的大小。但是,我可以从y峎pred得到图像大小,但是没有批处理大小,因为在初始化图形时,它是以None形式出现的。在

def focal_loss(content, label_remap, gamma_=2, w_d=1e-4):
def focal_loss_fixed(y_true, y_pred):
    num_classes = len(content.keys())
    print("y_true_b", y_true.get_shape().as_list())

    cv_eqation = K.constant([0.114, 0.587, 0.299])
    y_true = tf.multiply(y_true, cv_eqation)
    y_true = tf.reduce_sum(y_true, axis=3)
    y_true = tf.cast(y_true, dtype=tf.uint8)

    lbls_resized = y_true
    logits_train = y_pred

    b, c, w, h = K.int_shape(y_pred)
    batch = K.constant(b)
    channel = K.variable(c)
    width = K.variable(w)
    high = K.variable(h)
    with tf.variable_scope("loss"):
        ......
        # make the labels one-hot for the cross-entropy
        onehot_mat = tf.reshape(tf.one_hot(lbls_resized, num_classes), (-1, num_classes))

        # focal loss p and gamma
        gamma = np.full((high * width * batch, channel), fill_value=gamma_)
        print("gamma", gamma.shape)
        .........
    return loss
return focal_loss_fixed

另外,我尝试了一种不同的方式使用onehot_mat形状,但它的形状没有任何价值。在


Tags: 图像truetfdefcontentvariablenumclasses
1条回答
网友
1楼 · 发布于 2024-09-26 22:53:53

请参考this answer。听起来你想知道张量的动态形状,但却使用了静态形状。您需要使用tf.shape在运行时获取批处理的动态形状,而不是{},后者只返回构造网络时已知的静态形状。在

更新: 对于你的特殊任务,我觉得你在尝试创建一个张量,它的形状依赖于当前的批量大小。我想你可以这样做:

import tensorflow as tf
import numpy as np

vector = tf.Variable(tf.random_normal([3], stddev=0.1), name="weights")
batch = tf.placeholder(tf.float32, shape=[None,2,2])

vector_times_batchsize = tf.tile(vector, tf.shape(batch)[0:1])

init_all_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_all_op)
    print sess.run(vector_times_batchsize, feed_dict={batch: np.zeros((5,2,2), np.float32)}).shape

这会根据张量的第一个维度batch的形状,通过重复gamma_image张量来创建一个新的张量。在

请注意,您不能使用numpy函数,因为这个张量的创建必须是tensorflow图的一部分,因为sice只在运行时知道,而在创建图形时不知道。在

相关问题 更多 >

    热门问题