python - Keras 中的逐像素加权损失函数 - TensorFlow 2.0

标签 python tensorflow keras tensorflow2.0

我正在尝试为用 Keras 编写的模型编写一个逐像素加权损失函数,但在 TensorFlow 2.0 中似乎不再可能了,即除了 y_true 之外不可能有其他输入的损失函数和y_pred

我以前是这样写的:

from tensorflow.keras.layers import Input, Conv2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import backend as K

def my_keras_model():
  input = Input((256,256,1), name='input')
  weight = Input((256,256,1), name='weights')
  c1 = Conv2D(16, (3, 3), activation='relu', kernel_initializer='glorot_uniform', padding='same')(input)
  outputs = Conv2D(1, (1, 1), activation='sigmoid')(c1)

  model=Model(input=[input,weight], output=outputs)
  model.compile(optimizer=Adam(learning_rate=0.001, name='adam'), loss=my_weighted_loss(weight))
  return model

def my_weighted_loss(weight):    
   def loss(y_true, y_pred):
     return K.mean(weight * K.binary_crossentropy(y_true, y_pred), axis=-1)
   return loss

知道如何在 TF 2 中做到这一点吗?

最佳答案

实现此目的的一种“hacky”方法是将原始输入添加到输出,并编写自己的损失函数。这样你就可以做到

weight = y_true[...,0]
y_true = y_true[...,1:]

我也很想听到更好的答案:)

关于python - Keras 中的逐像素加权损失函数 - TensorFlow 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61225857/

相关文章:

python - Tensorflow 抛出分布式函数错误

python - Keras 编写一个接受图像的循环层

python - 我们如何计算给定日期和时间给定地点的太阳位置?

python - 从 gpx 数据中滤除噪音

python - Tensorflow session.run feed dict机制

python - tf.print 何时会按预期实际工作(即打印张量和变量的值)?

filter - tf.boolean_mask、mask_dimension必须指定吗?

python - 恢复训练 tf.keras Tensorboard

python - 以编程方式检测图像是否有边框(返回 bool 值)

python - python 中只有部分 unicode 被替换。不明白为什么