Imran
Imran

Reputation: 13468

ValueError: Data cardinality is ambiguous. Please provide data which shares the same first dimension

I'm trying to create a keras model with multiple input branches, but keras doesn't like that the inputs have different sizes.

Here is a minimal example:

import numpy as np

from tensorflow import keras
from tensorflow.keras import layers


inputA = layers.Input(shape=(2,))
xA = layers.Dense(8, activation='relu')(inputA)

inputB = layers.Input(shape=(3,))
xB = layers.Dense(8, activation='relu')(inputB)

merged = layers.Concatenate()([xA, xB])

output = layers.Dense(8, activation='linear')(merged)    

model = keras.Model(inputs=[inputA, inputB], outputs=output)


a = np.array([1, 2])
b = np.array([3, 4, 5])    

model.predict([a, b])

Which results in the error:

ValueError: Data cardinality is ambiguous:
  x sizes: 2, 3
Please provide data which shares the same first dimension.

Is there a better way to do this in keras? I've read the other questions referencing the same error, but I'm not really understanding what I need to change.

Upvotes: 6

Views: 7594

Answers (1)

Marco Cerliani
Marco Cerliani

Reputation: 22031

you need to pass array in the correct format... (n_batch, n_feat). A simple reshape is sufficient to create the batch dimensionality

import numpy as np
from tensorflow import keras
from tensorflow.keras import layers


inputA = layers.Input(shape=(2,))
xA = layers.Dense(8, activation='relu')(inputA)

inputB = layers.Input(shape=(3,))
xB = layers.Dense(8, activation='relu')(inputB)

merged = layers.Concatenate()([xA, xB])

output = layers.Dense(8, activation='linear')(merged)    

model = keras.Model(inputs=[inputA, inputB], outputs=output)


a = np.array([1, 2]).reshape(1,-1)
b = np.array([3, 4, 5]).reshape(1,-1)

model.predict([a, b])

Upvotes: 3

Related Questions