How to overcome the wrong dimension issue

Viewed 60

I was doing the assignment for the "Model validation on the Iris dataset".

I get this error: "Error when checking input: expected dense_input to have shape (135,) but got array with shape (4,)". How do I overcome this problem?

My code is

from numpy.random import seed
seed(8)
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, model_selection 
from sklearn.model_selection import train_test_split
%matplotlib inline
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D



def read_in_and_split_data(iris_data):

data=iris_data["data"] 

targets=iris_data["target"] 

train_data, test_data, train_targets, test_targets= train_test_split(data,targets,test_size=0.1)

return(train_data, test_data, train_targets, test_targets)



iris_data = datasets.load_iris()
train_data, test_data, train_targets, test_targets = read_in_and_split_data(iris_data)


train_targets = tf.keras.utils.to_categorical(np.array(train_targets))
test_targets = tf.keras.utils.to_categorical(np.array(test_targets))


def get_model(input_shape):

model= Sequential ([
    
    Dense(64, kernel_initializer='he_uniform',bias_initializer='ones', input_shape=(train_data.shape[0],)),
    Dense(128, activation= "relu"),
    Dense(128, activation= "relu"),
    Dense(128, activation= "relu"),
    Dense(128, activation= "relu"),
    Dense(64, activation= "relu"),
    Dense(64, activation= "relu"),
    Dense(64, activation= "relu"),
    Dense(64, activation= "relu"),
    Dense(3, activation= 'softmax')
    

])

return model



model = get_model(train_data[0].shape)


def compile_model(model):
opt= tf.keras.optimizers.Adam(learning_rate=0.0001)
acc= tf.keras.metrics.SparseCategoricalAccuracy()
mae= tf.keras.metrics.MeanAbsoluteError()

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

compile_model(model)



def train_model(model, train_data, train_targets, epochs):

return model.fit(train_data, train_targets, epochs=epochs, validation_split= 0.15, batch_size=40)

Everything is runnning fine until when I load this cell

history = train_model(model, train_data, train_targets, epochs=800)

That's when the error box pops out

 ValueError                                Traceback (most recent call last)
 <ipython-input-20-96db4320a1b9> in <module>
  1 # Run your function to train the model
  2 
  ----> 3 history = train_model(model, train_data, train_targets, epochs=800)

 <ipython-input-19-ce18af880dd7> in train_model(model, train_data, train_targets, epochs)
 11     """
 12 
 ---> 13     return model.fit(train_data, train_targets, epochs=epochs, validation_split= 0.15, 
 batch_size=40)
 14 
 15 

  /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py in fit(self, 
  x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, 
  class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, 
  max_queue_size, workers, use_multiprocessing, **kwargs)
  726         max_queue_size=max_queue_size,
  727         workers=workers,
  --> 728         use_multiprocessing=use_multiprocessing)
  729 
  730   def evaluate(self,

  /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py in 
  fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, 
  shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, 
  validation_freq, **kwargs)
  222           validation_data=validation_data,
  223           validation_steps=validation_steps,
  --> 224           distribution_strategy=strategy)
  225 
  226       total_samples = _get_total_number_of_samples(training_data_adapter)

  /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py in _ 
  process_training_inputs(model, x, y, batch_size, epochs, sample_weights, class_weights, 
  steps_per_epoch, validation_split, validation_data, validation_steps, shuffle, 
  distribution_strategy, max_queue_size, workers, use_multiprocessing)
  514         batch_size=batch_size,
  515         check_steps=False,
  --> 516         steps=steps_per_epoch)
  517     (x, y, sample_weights,
  518      val_x, val_y,

  /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py in _ 
  standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, 
  steps, validation_split, shuffle, extract_tensors_from_dataset)
  2470           feed_input_shapes,
  2471           check_batch_axis=False,  # Don't enforce the batch size.
  -> 2472           exception_prefix='input')
  2473 
  2474     # Get typespecs for the input data and sanitize it if necessary.

  /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_utils.py in 
  standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
  572                              ': expected ' + names[i] + ' to have shape ' +
  573                              str(shape) + ' but got array with shape ' +
  --> 574                              str(data_shape))
  575   return data
  576 

  ValueError: Error when checking input: expected dense_input to have shape (135,) but got array with 
  shape (4,)

Pardon me for asking this message. I'm still a newbie, tensorflow 2.0 is brand new to me. I make mistakes here and there. But I hereby wish everybody a Happy Christmas day ahead.

1 Answers

The error suggest that your input data shape is not compatible with the input shape of the model. You need to check your train_data shape:

 print(train_data.shape)

See if the shape is compatible with the models input_shape. My guess is that you haven't call out the function read_in_and_split_data of yours and the train_data is coming from another cell

Related