Search code examples
pythontensorflowkerasdeep-learningkeras-layer

Keras error: expected input_1 to have 3 dimensions, but got array with shape (256326, 3)


I was trying to modeling multiple-output dnn. also using kaggle creditcard data. cause I was just trying to test, my code learn from only three dimensions.

my code:

df = pd.read_csv('creditcard.csv')

X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values

X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.1, random_state=1)
temp = []
for x in X_train:
    temp.append(x[:3])
X_train = temp
temp = []
for x in X_test:
    temp.append(x[:3])
X_test = temp

sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

inputs = keras.layers.Input(shape=(None, 3))
x = layers.Dense(16, activation='relu')(inputs)
x = layers.Dense(20, activation='relu')(x)
x = layers.Dropout(0.25)(x)
x = layers.Dense(16, activation='relu')(x)
a_prediction = layers.Dense(1, name='a')(x)
b_prediction = layers.Dense(16, activation='softmax', name='b')(x)
c_prediction = layers.Dense(1, activation='sigmoid', name='c')(x)
model = Model(inputs, [a_prediction, b_prediction, c_prediction])

model.compile(optimizer='rmsprop', loss={'a': mean_squared_error, 'b': categorical_crossentropy, 'c': binary_crossentropy}, loss_weights={'a': 0.25, 'b': 1., 'c': 10.})

model.fit(X_train, {'a': Y_train, 'b': Y_train, 'c': Y_train}, epochs=10, batch_size=64)

error:

Traceback (most recent call last):
  File "C:/Users/Develop/PycharmProjects/reinforcement recommandation system/test2.py", line 44, in <module>
    model.fit(X_train, {'a': Y_train, 'b': Y_train, 'c': Y_train}, epochs=10, batch_size=64)
  File "C:\Users\Develop\PycharmProjects\reinforcement recommandation system\lib\site-packages\keras\engine\training.py", line 1089, in fit
    batch_size=batch_size)
  File "C:\Users\Develop\PycharmProjects\reinforcement recommandation system\lib\site-packages\keras\engine\training.py", line 757, in _standardize_user_data
    exception_prefix='input')
  File "C:\Users\Develop\PycharmProjects\reinforcement recommandation system\lib\site-packages\keras\engine\training_utils.py", line 131, in standardize_input_data
    'with shape ' + str(data_shape))
ValueError: Error when checking input: expected input_1 to have 3 dimensions, but got array with shape (256326, 3)

How can I solve this problem?


Solution

  • The shape parameter for the Input layer should not include the batch size (link to doc). Switching that line to inputs = keras.layers.Input(shape=(3, )) should solve your issue.

    In future, you can use the model.summary() method to see the internal names of your layers and the expected output shape of each. For your current code the following is printed:

    __________________________________________________________________________________________________
    Layer (type)                    Output Shape         Param #     Connected to                     
    ==================================================================================================
    input_1 (InputLayer)            (None, None, 3)      0                                            
    __________________________________________________________________________________________________
    dense_1 (Dense)                 (None, None, 16)     64          input_1[0][0]                    
    __________________________________________________________________________________________________
    dense_2 (Dense)                 (None, None, 20)     340         dense_1[0][0]                    
    __________________________________________________________________________________________________
    dropout_1 (Dropout)             (None, None, 20)     0           dense_2[0][0]                    
    __________________________________________________________________________________________________
    dense_3 (Dense)                 (None, None, 16)     336         dropout_1[0][0]                  
    __________________________________________________________________________________________________
    a (Dense)                       (None, None, 1)      17          dense_3[0][0]                    
    __________________________________________________________________________________________________
    b (Dense)                       (None, None, 16)     272         dense_3[0][0]                    
    __________________________________________________________________________________________________
    c (Dense)                       (None, None, 1)      17          dense_3[0][0]                    
    ==================================================================================================
    Total params: 1,046
    Trainable params: 1,046
    Non-trainable params: 0
    __________________________________________________________________________________________________
    

    We can see that the input layer (input_1, the same as mentioned in the stack trace) incorrectly has three dimensions.