keras 自定义loss层+接受输入实例
loss函数如何接受输入值
keras封装的比较厉害,官网给的例子写的云里雾里,
在stackoverflow找到了答案
Youcanwrapthelossfunctionasainnerfunctionandpassyourinputtensortoit(ascommonlydonewhenpassingadditionalargumentstothelossfunction).
defcustom_loss_wrapper(input_tensor): defcustom_loss(y_true,y_pred): returnK.binary_crossentropy(y_true,y_pred)+K.mean(input_tensor) returncustom_loss
input_tensor=Input(shape=(10,)) hidden=Dense(100,activation='relu')(input_tensor) out=Dense(1,activation='sigmoid')(hidden) model=Model(input_tensor,out) model.compile(loss=custom_loss_wrapper(input_tensor),optimizer='adam')
Youcanverifythatinput_tensorandthelossvaluewillchangeasdifferentXispassedtothemodel.
X=np.random.rand(1000,10) y=np.random.randint(2,size=1000) model.test_on_batch(X,y)#=>1.1974642 X*=1000 model.test_on_batch(X,y)#=>511.15466
fit_generator
fit_generatorultimatelycallstrain_on_batchwhichallowsforxtobeadictionary.
Also,itcouldbealist,inwhichcasexisexpectedtomap1:1totheinputsdefinedinModel(input=[in1,…],…)
###generator yield[inputX_1,inputX_2],y ###model model=Model(inputs=[inputX_1,inputX_2],outputs=...)
补充知识:keras中自定义loss损失函数和修改不同样本的loss权重(样本权重、类别权重)
首先辨析一下概念:
1.loss是整体网络进行优化的目标,是需要参与到优化运算,更新权值W的过程的
2.metric只是作为评价网络表现的一种“指标”,比如accuracy,是为了直观地了解算法的效果,充当view的作用,并不参与到优化过程
一、keras自定义损失函数
在keras中实现自定义loss,可以有两种方式,一种自定义lossfunction,例如:
#方式一 defvae_loss(x,x_decoded_mean): xent_loss=objectives.binary_crossentropy(x,x_decoded_mean) kl_loss=-0.5*K.mean(1+z_log_sigma-K.square(z_mean)-K.exp(z_log_sigma),axis=-1) returnxent_loss+kl_loss vae.compile(optimizer='rmsprop',loss=vae_loss)
或者通过自定义一个keras的层(layer)来达到目的,作为model的最后一层,最后令model.compile中的loss=None:
#方式二 #Customlosslayer classCustomVariationalLayer(Layer): def__init__(self,**kwargs): self.is_placeholder=True super(CustomVariationalLayer,self).__init__(**kwargs) defvae_loss(self,x,x_decoded_mean_squash): x=K.flatten(x) x_decoded_mean_squash=K.flatten(x_decoded_mean_squash) xent_loss=img_rows*img_cols*metrics.binary_crossentropy(x,x_decoded_mean_squash) kl_loss=-0.5*K.mean(1+z_log_var-K.square(z_mean)-K.exp(z_log_var),axis=-1) returnK.mean(xent_loss+kl_loss) defcall(self,inputs): x=inputs[0] x_decoded_mean_squash=inputs[1] loss=self.vae_loss(x,x_decoded_mean_squash) self.add_loss(loss,inputs=inputs) #Wedon'tusethisoutput. returnx y=CustomVariationalLayer()([x,x_decoded_mean_squash]) vae=Model(x,y) vae.compile(optimizer='rmsprop',loss=None)
在keras中自定义metric非常简单,需要用y_pred和y_true作为自定义metric函数的输入参数点击查看metric的设置
注意事项:
1.keras中定义loss,返回的是batch_size长度的tensor,而不是像tensorflow中那样是一个scalar
2.为了能够将自定义的loss保存到model,以及可以之后能够顺利loadmodel,需要把自定义的loss拷贝到keras.losses.py源代码文件下,否则运行时找不到相关信息,keras会报错
有时需要不同的sample的loss施加不同的权重,这时需要用到sample_weight,例如
discriminator.train_on_batch(imgs,[valid,labels],class_weight=class_weights)
二、keras中的样本权重
#Import importnumpyasnp fromsklearn.utilsimportclass_weight #Examplemodel model=Sequential() model.add(Dense(32,activation='relu',input_dim=100)) model.add(Dense(1,activation='sigmoid')) #Usebinarycrossentropyloss model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) #Calculatetheweightsforeachclasssothatwecanbalancethedata weights=class_weight.compute_class_weight('balanced', np.unique(y_train), y_train) #Addtheclassweightstothetraining model.fit(x_train,y_train,epochs=10,batch_size=32,class_weight=weights)
Notethattheoutputoftheclass_weight.compute_class_weight()isannumpyarraylikethis:[2.575698450.68250928].
以上这篇keras自定义loss层+接受输入实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。