Search code examples
pythontensorflowmachine-learningkeras

Label structure for a keras model with multiple outputs


I have a keras model that inputs a simple array and outputs two values (x and y) that belong to 5 possible categories (encoded as one-hot), with a custom loss function. I know that you have to set the loss function for each desired output value, which I did in my script.

I initialized the model like this:

inputs = keras.Input(shape=(14))
middle = layers.Dense(10,activation="relu")(inputs)
out_x = layers.Dense(5,activation="sigmoid")(middle)
out_y = layers.Dense(5,activation="sigmoid")(middle)
model = keras.Model(inputs=inputs,outputs={"x":out_x,"y":out_y})

model.compile(optimizer="adam",loss={"x":custom_loss,"y":custom_loss},metrics=["accuracy"])

I then tried to make an array of input data and labels. The labels were laid out as such:

[
    {"x":[0,0,1,0,0],"y":[1,0,0,0,0]},
    ...
]

but when I tried to use model.fit(training_data,labels) it gave me an error that was several hundreds of repetitions of the number 5 and then Make sure all arrays contain the same number of samples.

What should my labels look like if I want my model to have multiple outputs?


Solution

    • In your code,you need to provide the labels in a dict format, where each output is associated with its corresponding label. so you have two outputs ("x" and "y"), the labels should be structured as follows:
    labels = {
        "x": [
            [0, 0, 1, 0, 0],
            ...
        ],
        "y": [
            [1, 0, 0, 0, 0],
            ...
        ]
    }
    
    • Each output label is represented as a separate list within the dict. but make that length of each list should match the number of samples in your training data.
    • To train your model using the provided labels, you can use the model.fit()
    model.fit(training_data, labels, ...)
    
    • Also to make sure that your custom loss function is compatible with the shape of your output data.