Neural Network Input 0 of layer "sequential_4" is incompatible with the layer: expected shape=(None, 4), found shape=(None, 2)?

Viewed 341

I am working with some data to make a trainable model suing Neural Network. This is the code I am working on:

import os, time, random
import numpy as np
import pandas as pd

from google.colab import files

df = pd.read_csv('/content/drive/MyDrive/Deep Learning Final Project/ObjectDetection/train_solution_bounding_boxes (1).csv')
df.rename(columns={'image':'image_id'}, inplace=True)
df.head(13)

X = df.iloc[:,:2].values
y = df.iloc[:,3:10].values
print(X.shape, y.shape)

from sklearn.preprocessing import StandardScaler
model = StandardScaler()
X = model.fit_transform(X)

from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder()
y = ohe.fit_transform(y).toarray()
y

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.1)

# Building nural network model 
import keras
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(1, input_dim=4, activation='relu'))
model.add(Dense(1, activation='relu'))
model.add(Dense(4, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# Here below I have a problem with running this section 

history = model.fit(X_train, y_train, epochs=100, batch_size=64)

It gives me this error

ValueError: Input 0 of layer "sequential_5" is incompatible with the layer: expected shape=(None, 4), found shape=(None, 2)

Please any one can help we solving this problem.

1 Answers

The first layer of the network model.add(Dense(1, input_dim=4, activation='relu')) expects an input of dimension 4, (as specified by input_dim=4).

That's why the error says Input 0 of layer "sequential_5" is incompatible with the layer: expected shape=(None, 4). It means, the initial layer (Input 0) of the Sequential model is expecting an array of length=4.

Now, the input is given by X = df.iloc[:,:2].values, i.e only two columns are passed as input. Thus, the error says found shape=(None, 2). Check the value of X.shape. Its 2nd index would be 2.

This is the mismatach. Fix model.add(Dense(1, input_dim=4, activation='relu')) as the input_dim=2. It will work.

Moreover, after you fix this, check for the first dimension. None should not work. Fix that as well.

Related