【问题标题】:Keras get the number of image in batch from y_pred in side custom loss functionKeras 在侧边自定义损失函数中从 y_pred 中批量获取图像数量
【发布时间】:2018-10-25 21:22:42
【问题描述】:

在这个损失函数中,我需要根据批量图像的数量和图像的大小来创建完整的指标。但是,我可以从 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 形状,但它的形状没有任何价值。

【问题讨论】:

    标签: python tensorflow neural-network keras


    【解决方案1】:

    请参考this answer。听起来您想知道张量的动态形状,但使用的是静态形状。您需要使用tf.shape 在运行时获取批处理的动态形状,而不是使用get_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 仅在运行时已知,而在创建图时不知道。

    【讨论】:

    • 谢谢@Sietschie 的回答,尝试使用tf.shape,但没有成功,我得到了这个异常TypeError: Tensor objects are not iterable when eager execution is not enabled. To iterate over this tensor use tf.map_fn.,逻辑上是正确的,我没有处于渴望模式,所以我可以我不会在 Keras 中获得 y_pred 的 y_true 的形状,而是在 fit 方法中获得 batch 的值。但是,我不确定,但它应该是在等式中使用该值的一种方式。
    猜你喜欢
    • 1970-01-01
    • 2018-10-22
    • 2016-11-12
    • 2019-06-24
    • 2020-10-12
    • 2021-02-08
    • 2020-05-30
    • 2020-01-08
    • 2021-07-23
    相关资源
    最近更新 更多