将两个神经网络的损失函数与一些权重相结合并同时进行训练

时间:2018-12-27 09:30:23

标签: python tensorflow keras deep-learning keras-layer

我想结合两个神经网络的损失函数来解决相同的二进制分类任务。假设N1和N2是分别在隐藏层中具有400和40个神经元的两个神经网络,我希望损失函数如下: 损失(N1)+ alpha *损失(N2)α是与神经网络N2的损失函数相关的权重

我尝试了以下代码,但不确定是正确还是错误

  M1 = Input(shape=(num_features,),name='M1')
  M2 = Dense(400, activation='relu',name='M2')(M1)
  M3 = Dense(1, activation='sigmoid',name='M3')(M2)

  C2 = Dense(40, activation='relu',name='C2')(M1)
  C3 = Dense(1, activation='sigmoid',name='C3')(C2)


  #O = Concatenate(axis=-1)([M3, C3])
  merged = Model(inputs=[M1],outputs=[M3, C3])
  plot_model(merged,to_file='architecture4.png',show_shapes=True)
  loss1 = 'binary_crossentropy'
  loss2 = 'binary_crossentropy'

  merged.compile(optimizer='adam',loss=[loss1, loss2],loss_weights=[alpham, 1 - alpham], metrics=['accuracy'])
  history = merged.fit(X_train, [y_train,y_train] ,batch_size=16, epochs=100)
  score = merged.evaluate(X_test, [y_test,y_test], batch_size=16)

0 个答案:

没有答案