如何训练具有 L1 范数重建损失函数的 Keras 模型?

How to train a Keras Model with L1-norm reconstruction loss function?

我目前正在使用 Kears 为 MNIST 数据集构建自动编码器,这是我的代码:

import all the dependencies
from keras.layers import Dense,Conv2D,MaxPooling2D,UpSampling2D
from keras import Input, Model
from keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt

encoding_dim = 15 
input_img = Input(shape=(784,))
# encoded representation of input
encoded = Dense(encoding_dim, activation='relu')(input_img)
# decoded representation of code 
decoded = Dense(784, activation='sigmoid')(encoded)
# Model which take input image and shows decoded images
autoencoder = Model(input_img, decoded)

# This model shows encoded images
encoder = Model(input_img, encoded)
# Creating a decoder model
encoded_input = Input(shape=(encoding_dim,))
# last layer of the autoencoder model
decoder_layer = autoencoder.layers[-1]
# decoder model
decoder = Model(encoded_input, decoder_layer(encoded_input))

autoencoder.compile(optimizer='adam', loss='binary_crossentropy')

最后一步是编译步骤,但是我需要用到L1范数重建损失函数。从Keras losses description来看,他们好像没有这个功能。如何将 L1 范数重建损失函数应用于 autoencoder.compile() 函数?谢谢!

在损失函数中,我们指的是预期误差值。因此,对于 L1 范数,您可以使用名称为 mean_absolute_errorMAE(平均绝对误差)。因此,您可以按如下方式重写代码的最后一行:

autoencoder.compile(optimizer='adam', loss='mean_absolute_error')