0

I am a beginner in keras and I am trying to classify data with a neural network.

   x_train = x_train.reshape(1,x_train.shape[0],window,5)
   x_val = x_val.reshape(1,x_val.shape[0],window,5)

   x_train = x_train.astype('float32')
   x_val = x_val.astype('float32')

   model = Sequential()

   model.add(Dense(64,activation='relu',input_shape= (data_dim,window,5)))
   model.add(Dropout(0.5))

   model.add(Dense(64,activation='relu'))
   model.add(Dropout(0.5))
   model.add(Dense(2,activation='softmax'))

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

   weights = model.get_weights()


   model_info = model.fit(x_train, y_train,batch_size=batchsize, nb_epoch=15,verbose=1,validation_data=(x_val, y_val))

  print x_train.shape
  #(1,1600,45,5)

  print y_train.shape
  #(1600,2)

I always have this error with this script and I don't understand why:

 ValueError: Error when checking target: expected dense_3 to have 4 dimensions, but got array with shape (16000, 2)
2
  • Can you provide a fuller exception trace? It will aid in bugfixing. Commented Jun 13, 2017 at 0:41
  • I can't use plot_model, python tells me that it couldn't import pydot even if I already installed it Commented Jun 13, 2017 at 3:34

1 Answer 1

2

Your model's output (dense_3, so named because it is the third Dense layer) has four dimensions. However, the labels you are attempting to compare it to (y_train) is only two dimensions. You will need to alter your network's architecture so that your model reshapes the data to match the labels.

Keeping track of tensor shapes is difficult when you're just starting out, so I recommend calling plot_model(model, to_file='model.png', show_shapes=True) before calling model.fit. You can look at the resulting PNG to understand what effect layers are having on the shape of your data.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you,so I have to change the shape of x_train ?
use print(model.summary()) to check your model layer dimensions. You will see that with this model structure and x_train.shape you will not be able to get the y_train.shape. Either change the shape of x_train or change the model structure.
@coline.s No, the shape of y_train.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.