【问题标题】:Trying to define combine loss function in CNN with VGG16 perceptual loss and SSIM尝试用 VGG16 感知损失和 SSIM 定义 CNN 中的组合损失函数
【发布时间】:2023-01-25 19:56:02
【问题描述】:

问题定义:

我正在使用 Tensorflow 实现 CNN。输入和输出的大小为samples x 128 x 128 x 1(灰度图像)。在损失函数中,我已经有了 SSIM (0-1),现在我的目标是使用预训练的 VGG16 将 SSIM 值与感知损失结合起来。我已经参考了以下答案 link1link2 但我不想在主模型的末尾连接 VGG 模型,而是想在特定层(例如 pool1、pool2、pool3)计算损失函数内的特征图并计算整体 MSE .我将损失函数定义如下:

组合损失函数:

def lossfun( yTrue, yPred):
    alpha = 0.5
    return (1-alpha)*perceptual_loss(yTrue, yPred) + alpha*K.mean(1-tf.image.ssim(yTrue, yPred, 1.0))

知觉丧失:

from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg16 import preprocess_input
model = VGG16()
model = Model(inputs=model.inputs, outputs=model.layers[1].output)

def perceptual_loss(yTrue, yPred): 
    true = model(preprocess_input(yTrue))
    P=Concatenate()([yPred,yPred,yPred])
    pred = model(preprocess_input(P))
    vggLoss = tf.math.reduce_mean(tf.math.square(true - pred))
    return vggLoss

错误我遇到的是以下内容:

ValueError: Dimensions must be equal, but are 224 and 128 for 'loss_22/conv2d_132_loss/sub' (op: 'Sub') with input shapes: [?,224,224,64], [?,128,128,64].

出现以下错误原因:

yPred 的大小为 None,128,128,1 ,在将它连接三次和 pred = model(preprocess_input(P)) 之后,我收到名为 pred 的特征图,大小为 None,128,128,64。 yTrue 的大小为None,在true = model(preprocess_input(yTrue)) 之后,true 的维度为None,224,224,64。这最终会在计算最终 vggLoss 时造成维度不兼容。

问题

由于我是这项任务的新手,所以我不确定我是否以正确的方式解决了这个问题。我应该创建大小为 224x244 的样本而不是 128x128 以避免此冲突,还是有任何其他解决方法来解决此问题?

谢谢 !

【问题讨论】:

    标签: python tensorflow keras deep-learning


    【解决方案1】:

    问题是 VGG16 模型 (yTrue) 的输入形状与主模型 (yPred) 的输出形状不同。 VGG16 模型需要形状为(None, 224, 224, 3) 的输入,而您的主模型输出形状为(None, 128, 128, 1) 的图像。

    一种解决方案是调整输入图像的大小以匹配 VGG16 模型的预期输入大小。例如,您可以使用 tf.image.resize 函数将图像的大小调整为 (224, 224),然后再将它们传递给 VGG16 模型。

    yTrue_resized = tf.image.resize(yTrue, (224, 224))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-05
      • 2018-07-22
      • 2019-03-10
      • 1970-01-01
      • 2019-05-26
      • 2019-08-31
      • 2017-10-10
      • 1970-01-01
      相关资源
      最近更新 更多