How to generate dataset for multi output keras model

Viewed 87

I followed the code examples for structured data classification at keras.io to build a model for classifying a rather simple model similar to the one in the example.

I wanted to extend the model to handle a second output, but I cannot use this model to train. The dataset is generated like it is done in the example (but with two results):

res1 = dataframe.pop("result1")
res2 = dataframe.pop("result2")
ds = tf.data.Dataset.from_tensor_slices((dict(dataframe),(res1,res2)))

The model is also similar to the example but using a two-dimensional output:

x = layers.Dense(32, activation="relu")(all_features)
x = layers.Dropout(0.5)(x)
output = layers.Dense(2, activation="sigmoid")(x)
model = keras.Model(all_inputs, output)
model.compile("adam", "binary_crossentropy", metrics=["accuracy"])

It compiles, but when i try to run fit...

model.fit(train_ds,epochs=30)

I get an error message:

ValueError: logits and labels must have the same shape ((None, 2) vs (None, 1))

How can I prepare the dataset to meet the shape constraints?

1 Answers

I believe you should use the zip() function:

ds = tf.data.Dataset.from_tensor_slices((dict(dataframe),zip(res1,res2)))

This way, you are telling from_tensor_slices() to zip labels into a new array of shape (N, 2) instead of concatenating two vectors of shape (N, 1) into (2N, 1).

Related