• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

keras 自定义loss model.add_loss的使用详解

python 搞代码 4年前 (2022-01-09) 23次浏览 已收录 0个评论

一点见解,不断学习,欢迎指正

1、自定义loss层作为网络一层加进model,同时该loss的输出作为网络优化的目标函数

from keras.models import Model
import keras.layers as KL
import keras.backend as K
import numpy as np
from keras.utils.vis_utils import plot_model
 
x_train=np.random.normal(1,1,(100,784))
 
x_in = KL.Input(shape=(784,))
x = x_in
x = KL.Dense(100, activation='relu')(x)
x = KL.Dense(784, activation='sigmoid')(x)
def custom_loss1(y_true,y_pred):
 return K.mean(K.abs(y_true-y_pred))
loss1=KL.Lambda(lambda x:custom_loss1(*x),name='loss1')([x,x_in])
 
model = Model(x_in, [loss1])
model.get_layer('loss1').output#取出loss
model.add_loss(loss1)#作为网络优化的目标函数
model.compile(optimizer='adam')
plot_model(model,to_file='mod<em style="color:transparent">本文来源gao.dai.ma.com搞@代*码#网</em>el.png',show_shapes=True)
#
model.fit(x_train, None, epochs=5)

2、自定义loss,作为网络优化的目标函数

x_in = KL.Input(shape=(784,))
x = x_in
x = KL.Dense(100, activation='relu')(x)
x = KL.Dense(784, activation='sigmoid')(x)
 
model = Model(x_in, x)
loss = K.mean((x - x_in)**2)
model.add_loss(loss)#只是作为loss优化目标函数
model.compile(optimizer='adam')
plot_model(model,to_file='model.png',show_shapes=True)
model.fit(x_train, None, epochs=5)

补充知识:keras load_weights fine-tune

分享一个小技巧,就是在构建网络模型的时候,不要怕麻烦,给每一层都定义一个名字,这样在复用之前的参数权重的时候,除了官网给的先加载权重,再冻结权重之外,你可以通过简单的修改层的名字来达到加载之前训练的权重的目的,假设权重文件保存为model_pretrain.h5 ,重新使用的时候,我把想要复用的层的名字设置成一样的,然后

model.load_weights(‘model_pretrain.h5’, by_name=True)

以上这篇keras 自定义loss model.add_loss的使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:keras 自定义loss model.add_loss的使用详解
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址