【问题标题】:tf.keras loss from two images in serial两个连续图像的 tf.keras 损失
【发布时间】:2020-04-28 08:12:45
【问题描述】:

我想使用the paper的稳定性训练方法,并将其应用到一个非常简单的CNN。
原理架构如下:


如图所示,您根据输入图像 I 的输出 f(I) 计算损失 扰动图像 I' 的输出 f(I')
我的问题是如何在没有两个 DNN 实例的情况下以有效的方式做到这一点, 因为我正在训练大型 3D 图像。换句话说:如何串行处理两个图像并根据这两个图像计算损失?
我正在将 tf2 与 keras 一起使用。

【问题讨论】:

    标签: tensorflow keras deep-learning tensorflow2.0


    【解决方案1】:
    1. 您可以先将 DNN 编写为 tf.keras 模型。

    2. 之后,您可以编写另一个模型,该模型采用两个图像输入,对一个图像应用一些高斯噪声,然后将它们传递给 DNN。

    3. 设计一个自定义损失函数,从两个输出中找到合适的损失。

    这是一个演示代码:

    from tensorflow.keras.layers import Input, Dense, Add, Activation, Flatten
    from tensorflow.keras.models import Model
    import tensorflow as tf
    import numpy as np
    import random
    
    
    from tensorflow.python.keras.layers import Input, GaussianNoise, BatchNormalization
    
    # shared DNN, this is the base model with a feature-space output, there is only once instance of the model
    ip = Input(shape=(32,32,1)) # same as original inputs
    f0 = Flatten()(ip)
    d0 = Dense(10)(f0) # 10 dimensional feature embedding
    dnn = Model(ip, d0)
    
    # final model with two version of images and loss
    
    input_1 = Input(shape=(32,32,1))
    input_2 = Input(shape=(32,32,1))
    
    g0 = GaussianNoise(0.5)(input_2)  # only input_2 passes through gaussian noise layer, you can design your own custom layer too
    
    # passing the two images to same DNN
    
    path1 = dnn(input_1) # no noise
    path2 = dnn(g0) # noise
    
    model = Model([input_1, input_2], [path1, path2])
    
    def my_loss(y_true, y_pred):
      # calculate your loss based on your two outputs path1, path2
      pass
    
    model.compile('adam', my_loss)
    model.summary()
    
    

    【讨论】:

    • 谢谢!只需连接 [path1, path2] 用作模型输出,否则我无法在同一个损失函数中使用两个输出。
    猜你喜欢
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 2021-04-18
    • 2021-08-20
    • 2019-10-29
    • 2012-10-08
    • 1970-01-01
    相关资源
    最近更新 更多