1

I am trying to create a basic neural network model in Keras that will learn to add positive numbers together and am having trouble with shaping the training data to fit the model:

I have already tried numerous configurations for the "input_shape" attribute of the first Dense layer, but nothing seems to work.

# training data
training = np.array([[2,3],[4,5],[3,8],[2,9],[11,4],[13,5],[2,9]], dtype=float)
answers  = np.array([5, 9, 11, 11, 15, 18, 11],  dtype=float)
# create our model now:
model = tf.keras.Sequential([
    tf.keras.layers.Dense(units=16, input_shape=(2,)),
    tf.keras.layers.Dense(units=16, activation=tf.nn.relu),
    tf.keras.layers.Dense(units=1)
])
# set up the compile parameters: 
model.compile(loss='mean_squared_error',
              optimizer=tf.keras.optimizers.Adam(.1))
#fit the model:
model.fit(training, answers, epochs=550, verbose=False)

print(model.predict([[7,9]]))

I'm expecting this to run without error and produce the result '16', but I am getting the following error:

"Traceback (most recent call last):
  File "c2f", line 27, in <module>
    print(model.predict([[7,9]]))
  File "C:\Users\Aalok\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1096, in predict
    x, check_steps=True, steps_name='steps', steps=steps)
  File "C:\Users\Aalok\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 2382, in _standardize_user_data
    exception_prefix='input')
  File "C:\Users\Aalok\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training_utils.py", line 362, in standardize_input_data
    ' but got array with shape ' + str(data_shape))

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

nathancy
  • 42,661
  • 14
  • 115
  • 137
Aalok Borkar
  • 153
  • 3
  • 12

1 Answers1

1

Got the error. The error was in this line according to the stack traces,

print(model.predict([[7,9]]))

Now, Keras Sequential model expects inputs in the form of a NumPy array ( ndarray ). In the above line, the model interprets the array as a list on multiple inputs ( which is not your case ).

According to the official docs, argument x in model.fit() is,

Numpy array of training data (if the model has a single input), or list of Numpy arrays (if the model has multiple inputs). If input layers in the model are named, you can also pass a dictionary mapping input names to Numpy arrays. x can be None (default) if feeding from framework-native tensors (e.g. TensorFlow data tensors).

We need to create a NumPy array, using numpy.array(),

print(model.predict(np.array([[7,9]])))

The error is resolved. I have run the code and it works perfectly fine.

Shubham Panchal
  • 4,061
  • 2
  • 11
  • 36