Reputation: 13
I have tried the following example:
from keras.models import Sequential
from keras.layers import *
import numpy as np
x_train = np.random.random((30,50,50,3))
y_train = np.random.randint(2, size=(30,1))
model = Sequential()
#start from the first hidden layer, since the input is not actually a layer
#but inform the shape of the input, with 3 elements.
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input
#further layers:
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.fit(x_train, y_train,
epochs=20,
batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)
I get this error:
ValueError: Error when checking input: expected dense_1_input to have 2 dimensions, but got array with shape (30, 50, 50, 3).
Thus, I changed the input_shape as follows:
from keras.models import Sequential
from keras.layers import *
import numpy as np
x_train = np.random.random((30,50,50,3))
y_train = np.random.randint(2, size=(30,1))
model = Sequential()
#start from the first hidden layer, since the input is not actually a layer
#but inform the shape of the input, with 3 elements.
model.add(Dense(units=4,input_shape=(50,50,3))) #hidden layer 1 with input
#further layers:
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.fit(x_train, y_train,
epochs=20,
batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)
But now I get this error:
ValueError: Error when checking target: expected dense_2 to have 4 dimensions, but got array with shape (30, 1)
Any idea about what am I doing wrong?
Upvotes: 1
Views: 159
Reputation: 527
the problem is with the output shape of the last dense layer. You can use model.summary() to see the output shape of each layer.
your output shape is (None,50,50,1),but to match with your y_train shape it should be in (None,1) shape.
So i suggest you to add a flattern layer before the last dense layer.Plese refer this link for the definition of flattern layer in keras.
This is how your model code should looks like
model.add(Dense(units=4,input_shape=(50,50,3),name="d1")) #hidden layer 1 with input
model.add(Dense(units=4,name="d2")) #hidden layer 2
model.add(Flatten())
model.add(Dense(units=1,name="d3")) #output layer
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.summary()
Futher more use name for your layers it will be easy for you to understand where the problem is.good luck ;-)
Upvotes: 1