keras 自定义loss model.add_loss的使用详解
一点见解,不断学习,欢迎指正
1、自定义loss层作为网络一层加进model,同时该loss的输出作为网络优化的目标函数
fromkeras.modelsimportModel importkeras.layersasKL importkeras.backendasK importnumpyasnp fromkeras.utils.vis_utilsimportplot_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) defcustom_loss1(y_true,y_pred): returnK.mean(K.abs(y_true-y_pred)) loss1=KL.Lambda(lambdax: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='model.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)
补充知识:kerasload_weightsfine-tune
分享一个小技巧,就是在构建网络模型的时候,不要怕麻烦,给每一层都定义一个名字,这样在复用之前的参数权重的时候,除了官网给的先加载权重,再冻结权重之外,你可以通过简单的修改层的名字来达到加载之前训练的权重的目的,假设权重文件保存为model_pretrain.h5,重新使用的时候,我把想要复用的层的名字设置成一样的,然后
model.load_weights('model_pretrain.h5',by_name=True)
以上这篇keras自定义lossmodel.add_loss的使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。