2018-11-14 02:13

# 基于keras写的模型中自定义的函数（如损失函数）如何保存到模型中？

5
``````batch_size = 128
original_dim = 100   #25*4
latent_dim = 16       # z的维度
intermediate_dim = 256  # 中间层的维度
nb_epoch = 50        # 训练轮数
epsilon_std = 1.0    # 重参数

#my tips:encoding
x = Input(batch_shape=(batch_size,original_dim))
h = Dense(intermediate_dim, activation='relu')(x)
z_mean = Dense(latent_dim)(h)                  # mu
z_log_var = Dense(latent_dim)(h)               # sigma

#my tips:Gauss sampling,sample Z
def sampling(args):                   # 重采样
z_mean, z_log_var = args
epsilon = K.random_normal(shape=(128, 16), mean=0.,
stddev=1.0)
return z_mean + K.exp(z_log_var / 2) * epsilon

# note that "output_shape" isn't necessary with the TensorFlow backend
# my tips:get sample z(encoded)
z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])

# we instantiate these layers separately so as to reuse them later
decoder_h = Dense(intermediate_dim, activation='relu')            # 中间层
decoder_mean = Dense(original_dim, activation='sigmoid')          # 输出层
h_decoded = decoder_h(z)
x_decoded_mean = decoder_mean(h_decoded)

#my tips:loss(restruct X)+KL
def vae_loss(x, x_decoded_mean):
xent_loss = original_dim * objectives.binary_crossentropy(x, x_decoded_mean)
kl_loss = - 0.5 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
return xent_loss + kl_loss

vae = Model(x, x_decoded_mean)
vae.compile(optimizer='rmsprop', loss=vae_loss)

vae.fit(x_train, x_train,
shuffle=True,
epochs=nb_epoch,
verbose=2,
batch_size=batch_size,
validation_data=(x_valid, x_valid))
vae.save(path+'//VAE.h5')
``````

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享
• 邀请回答

• 点赞 评论 复制链接分享