具有多个输入和输出的定制损失函数

时间:2019-08-31 17:18:43

标签: python tensorflow keras neural-network

我有一个具有两个输入和两个输出的网络,如下所示:

image_inputs = Input(shape=(784,))
A_inputs = Input(shape=(780,))
inputs = keras.layers.concatenate([image_inputs, A_inputs])
x = Dense(512, activation='relu')(inputs)
outputs1 = Dense(784, activation='sigmoid')(x)
outputs2 = Dense(780, activation='sigmoid')(x)
outputs = keras.layers.concatenate([outputs1, outputs2])

我的模特是:

model = Model([image_inputs, A_inputs], outputs, name='vae_mlp')

我想定义一些损失函数:

def loss_X(inputs,outputs):
    reconstruction_loss = original_dim*binary_crossentropy(inputs[::,0:-(n_d)], outputs[::,0:-(780)])                                              
    return K.mean(reconstruction_loss)

def loss_A(inputs,outputs):
    reconstruction_loss = original_dim*binary_crossentropy(inputs[::,-(n_d):], outputs[::,-(780):])                                              
    return K.mean(reconstruction_loss)

def loss_KL(inputs,outputs):
    A,A_T=triangle(n_z,A_inputs)
    sum_A=tf.reduce_sum(A*A,0)    
    kl_loss =  -0.5*K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)*sum_A, axis=-1)    
    return K.mean(kl_loss)

def loss_total(inputs,outputs):
    reconstruction_loss = original_dim*binary_crossentropy(inputs,outputs)                                              
    A,A_T=triangle(n_z,A_inputs)
    sum_A=tf.reduce_sum(A*A,0)    
    kl_loss =  -0.5*K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)*sum_A, axis=-1)  
    return K.mean(reconstruction_loss + kl_loss)

最后:

model.compile(optimizer='adam',loss=loss_total,metrics= [loss_X,loss_A,loss_KL])
history = model.fit([x_train,A_vec],epochs=epochs, batch_size=batch_size, 
                    validation_data=([x_test,A_vec], None))

实际上,我想测试包含某些部分的损失函数(loss_total),我也需要检查这些单独的部分。但是由于模型的输入和输出是多个,所以当我要运行模型时,会收到此错误:

IndexError: list index out of range

该模型适用于单个输入和输出情况,但是我不知道在这种情况下如何运行模型?

0 个答案:

没有答案