Search code examples
pythontensorflowmachine-learningkerasloss-function

Loss function Keras out_dim > 1


I have a training data:

enter image description here

And, I have a model in Keras with more than one dimension of output. I want to predict A, B and C:

model = Sequential()
model.add(GRU(32, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(3))
model.compile(loss='mean_squared_error', optimizer='adam')

But I want the minimum mean_squared_error in A, i.e. only want to consider A for the loss function.

What I can do?


Solution

  • You can define a custom loss function and only compute the mean_squared_error() loss based on the value of A:

    from keras import losses
    
    def loss_A(y_true, y_pred):
        return losses.mean_squared_error(y_true[:,0], y_pred[:,0])
    
    #...
    model.compile(loss=loss_A, optimizer='adam')