【问题标题】:How can I determine the "index" of y_true and y_pred in the loss function in keras?如何确定 keras 损失函数中 y_true 和 y_pred 的“索引”?
【发布时间】:2020-03-07 08:19:03
【问题描述】:

我必须设计一个网络,在该网络中,特征向量的方向应该尽可能接近真实情况。我正在使用心脏 MRI 数据,并且我已经有一个函数可以计算每个体素的特征向量。我的问题是,该函数需要比 y_pred 和 y_true 更多的输入来计算特征向量。我的 y_true/y_pred 有维度 (841,336,336,33)(每个维度的含义:(索引、x 方向、y 方向、通道))。我现在需要在任何给定时间知道索引,以便我可以将正确的索引传递给我的附加数据。 有什么方法可以知道损失函数当前正在查看的是(841 个)哪个图像?

【问题讨论】:

    标签: python tensorflow keras loss-function


    【解决方案1】:

    编写一个考虑了附加数据和特征向量计算函数的自定义损失函数可能会为您提供最好的服务。特别是,我相信您应该能够在“y_true”数组中传递其他信息(在同一索引处),然后根据需要对其进行切片(使用 tensorflow 功能来分离各种组件。)这是一个示例显示了这个想法。请注意,顶部仅允许在 Google Colab (CPU) 上重现结果。主要代码在注释之后:“#其余代码如下......”我希望这会有所帮助。

    # Install TensorFlow
    try:
      # %tensorflow_version only exists in Colab.
      %tensorflow_version 2.x
    except Exception:
      pass
    
    import tensorflow as tf
    print(tf.__version__)
    print(tf.executing_eagerly())
    
    # Setup repro section from Keras FAQ with TF1 to TF2 adjustments
    
    import numpy as np
    import random as rn
    
    # The below is necessary for starting Numpy generated random numbers
    # in a well-defined initial state.
    
    np.random.seed(42)
    
    # The below is necessary for starting core Python generated random numbers
    # in a well-defined state.
    
    rn.seed(12345)
    
    # Force TensorFlow to use single thread.
    # Multiple threads are a potential source of non-reproducible results.
    # For further details, see: https://stackoverflow.com/questions/42022950/
    
    session_conf = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=1,
                                            inter_op_parallelism_threads=1)
    
    # The below tf.set_random_seed() will make random number generation
    # in the TensorFlow backend have a well-defined initial state.
    # For further details, see:
    # https://www.tensorflow.org/api_docs/python/tf/set_random_seed
    
    tf.compat.v1.set_random_seed(1234)
    
    sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)
    tf.compat.v1.keras.backend.set_session(sess)
    
    # Rest of code follows ...
    
    # Custom Loss
    def my_custom_loss(y_true, y_pred):
    
        tf.print('inside my_custom_loss:')
        tf.print('y_true:')
        tf.print(y_true)
        tf.print('y_true column 0:')
        tf.print(y_true[:,0])
        tf.print('y_true column 1:')
        tf.print(y_true[:,1])
        tf.print('y_pred:')
        tf.print(y_pred)
    
        y_zeros = tf.zeros_like(y_pred)
        y_mask = tf.math.greater(y_pred, y_zeros)
        res = tf.boolean_mask(y_pred, y_mask)
        logres = tf.math.log(res)
        finres = tf.math.reduce_sum(logres)
    
        return finres
    
    # Define model
    model = tf.keras.models.Sequential()
    model.add(tf.keras.layers.Dense(1, activation='linear', input_dim=1, name="Dense1"))
    model.compile(optimizer='rmsprop', loss=my_custom_loss)
    print('model.summary():')
    print(model.summary())
    
    # Generate dummy data
    data = np.array([[2.0],[1.0],[1.0],[3.0],[4.0]])
    labels = np.array([[[2.0],[1.0]],
                       [[0.0],[3.0]],
                       [[0.0],[3.0]],
                       [[0.0],[3.0]],
                       [[0.0],[3.0]]])
    
    # Train the model.
    print('training the model:')
    print('-----')
    model.fit(data, labels, epochs=1, batch_size=5)
    print('done training the model.')
    
    print(data.shape)
    print(labels.shape)
    
    a = model.predict(data)
    print(a)
    

    【讨论】:

    • 感谢解答,有不明白的,通过标签中的索引(2d标签)。然后编写一个自定义损失,将标签的第二维视为 y。和第一个维度作为索引
    猜你喜欢
    • 2018-04-02
    • 2016-12-05
    • 2020-09-21
    • 2018-12-30
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2016-11-12
    相关资源
    最近更新 更多