【问题标题】:How do you apply a loss using an optimizer on a image如何在图像上使用优化器应用损失
【发布时间】:2020-11-29 23:02:44
【问题描述】:

我正在尝试实现神经艺术转移。所以我现在的问题是我不知道如何将它应用到图像上。下面我创建了一个优化器、一个损失函数和一个随机生成的图像。如何对此应用自定义优化器?每当我运行它时,它就会得到'tensorflow.python.framework.ops.EagerTensor' object is not callable,我对这条消息有点困惑。任何帮助将不胜感激。

optimiser=tf.keras.optimizers.Adam(learning_rate=0.05)
#All [content_image,style_image,generated_image] the same Shape 1, H ,W ,C uint8

epochs=20
# pass content image through model
content_image_value=model(content_image.reshape(size_of_images))[-1] 
# pass styles image through model
style_image_values=model(style_image.reshape(size_of_images))[:-1]
# Randomly Generated Image
generated_image=tf.Variable(generated_image)

for epoch in range(epochs):
    # pass model generated image
    generate_image_values=model(generated_image)
    # Get the output we compare with the content
    content_generator_value=generate_image_values[-1]
    # Get the output we compare with the style
    style_generator_value=generate_image_values[:-1]
    loss=some_custom_loss() # returns a float64
    
    print(loss)
    # Minimise the error
    optimiser.minimize(loss,var_list=[generated_image])

    imshow(generated_image[0])

【问题讨论】:

标签: tensorflow optimization keras tensorflow2.0 tf.keras


【解决方案1】:

问题在于minimize 函数。此函数旨在在 tensorflow session 中运行。

您需要如下修改您的代码,以尽量减少在 Eager 模式下的损失:

with tf.GradientTape() as tape:
    generate_image_values = model(generated_image)
    # Get the output we compare with the content
    content_generator_value = generate_image_values[-1]
    # Get the output we compare with the style
    style_generator_value = generate_image_values[:-1]
    loss = some_custom_loss() # returns a float64
print(loss)
# Get the gradients
grads = tape.gradient(loss, generated_image)
# minimize
opt.apply_gradients(zip(grads, generated_image)
imshow(generated_image[0])

【讨论】:

    猜你喜欢
    • 2017-01-10
    • 2019-06-09
    • 1970-01-01
    • 2019-10-06
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多