Error in DNN: Input 0 of layer sequential_10 is incompatible with the layer

Viewed 182

Description

ValueError: Input 0 of layer sequential_10 is incompatible with the layer: expected axis -1 of input shape to have value 21 but received input with shape (None, 22)

I am creating a DNN model for parkinsons prediction. Dataset is from UCI repository. I sliced the dataset into 195 rows and 23 columns. There are 22 features and one class label attribute saying positive or negative. When i try to fit the model with keras, it is showing me that expected axis -1 of input shape to have value 21 but received input with shape (None, 22).

Code

from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
dataset = loadtxt(r'/parkinsons.data - Copy.csv',delimiter=',')
X = dataset[:, 0:22]
y = dataset[:, 22]
X.shape
model = Sequential()
model.add(Dense(21, input_dim=21, activation='relu'))
model.add(Dense(21, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X, y, epochs=150, batch_size=10)

Error

Epoch 1/150
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-67-39d59395a0a6> in <module>()
----> 1 model.fit(X, y, epochs=150, batch_size=10)

9 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    975           except Exception as e:  # pylint:disable=broad-except
    976             if hasattr(e, "ag_error_metadata"):
--> 977               raise e.ag_error_metadata.to_exception(e)
    978             else:
    979               raise

ValueError: in user code:

    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:805 train_function  *
        return step_function(self, iterator)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:795 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:1259 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:2730 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:3417 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:788 run_step  **
        outputs = model.train_step(data)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:754 train_step
        y_pred = self(x, training=True)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/base_layer.py:998 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/input_spec.py:259 assert_input_compatibility
        ' but received input with shape ' + display_shape(x.shape))

    ValueError: Input 0 of layer sequential_10 is incompatible with the layer: expected axis -1 of input shape to have value 21 but received input with shape (None, 22)
1 Answers

I propose you create your model by adapting this procedure:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# Sequential malli, 3 kerrosta
model = keras.Sequential(
    [
        layers.Dense(21, activation="relu", name="layer1"),
        layers.Dense(21, activation="relu", name="layer2"),
        layers.Dense(1, activation="sigmoid", name="layer3"),
    ]
)

#Maaritellaan eli let's define the training...
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])

#Create the test data
x=tf.random.normal([195, 23],0,1,tf.float32,seed=1)
y=tf.random.normal([195, 1],0,1,tf.float32,seed=1)

model.fit(x,y,epochs=5,batch_size=2)

print("Valmista eli ready!")

...if you get as a result something like that: enter image description here

...you know you are able to create and train a DNN from basic elements. Then try to train your data, investigate the performance, change the size and number of layers of your DNN, see the effects, etc, and enjoy!

Related