I'm creating a Bidirectional LSTM but I faced following error
ValueError: Dimensions must be equal, but are 5 and 250 for '{{node Equal}} = Equal[T=DT_INT64, incompatible_shape_error=true](ArgMax, ArgMax_1)' with input shapes: [?,5], [?,250]
I have no idea what is wrong and how to fix it!
I have a text dataset with 59k row for train the model and i would divid them into 15 classes which then I would use for text similarity base on classes for the received new text.
Based on the other post I played with loss but still it doesn't solve the issue.
Here is the model plot:
Also sequential model would be as follow:
model_lstm = Sequential()
model_lstm.add(InputLayer(250,))
model_lstm.add(Embedding(input_dim=max_words+1, output_dim=200, weights=[embedding_matrix],
mask_zero=True, trainable= True, name='corpus_embed'))
enc_lstm = Bidirectional(LSTM(128, activation='sigmoid', return_sequences=True, name='LSTM_Encod'))
model_lstm.add(enc_lstm)
model_lstm.add(Dropout(0.25))
model_lstm.add(Bidirectional(LSTM( 128, activation='sigmoid',dropout=0.25, return_sequences=True, name='LSTM_Decod')))
model_lstm.add(Dropout(0.25))
model_lstm.add(Dense(15, activation='softmax'))
model_lstm.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['Accuracy'])
## Feed the model
history = model_lstm.fit(x=corpus_seq_train,
y=target_seq_train,
batch_size=128,
epochs=50,
validation_data=(corpus_seq_test,target_seq_test),
callbacks=[tensorboard],
sample_weight= sample_wt_mat)
This is the model summary:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
corpus_embed (Embedding) (None, 250, 200) 4000200
bidirectional (Bidirectiona (None, 250, 256) 336896
l)
dropout (Dropout) (None, 250, 256) 0
bidirectional_1 (Bidirectio (None, 250, 256) 394240
nal)
dropout_1 (Dropout) (None, 250, 256) 0
dense (Dense) (None, 250, 15) 3855
=================================================================
Total params: 4,735,191
Trainable params: 4,735,191
Non-trainable params: 0
_________________________________
and dataset shape:
corpus_seq_train.shape, target_seq_train.shape
((59597, 250), (59597, 5, 8205))
Finally, here is the error:
Epoch 1/50
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
C:\Users\AMIRSH~1\AppData\Local\Temp/ipykernel_10004/3838451254.py in <module>
9 ## Feed the model
10
---> 11 history = model_lstm.fit(x=corpus_seq_train,
12 y=target_seq_train,
13 batch_size=128,
C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py in error_handler(*args, **kwargs)
65 except Exception as e: # pylint: disable=broad-except
66 filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67 raise e.with_traceback(filtered_tb) from None
68 finally:
69 del filtered_tb
C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py in tf__train_function(iterator)
13 try:
14 do_return = True
---> 15 retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
16 except:
17 do_return = False
ValueError: in user code:
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1051, in train_function *
return step_function(self, iterator)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1040, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1030, in run_step **
outputs = model.train_step(data)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 894, in train_step
return self.compute_metrics(x, y, y_pred, sample_weight)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 987, in compute_metrics
self.compiled_metrics.update_state(y, y_pred, sample_weight)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\compile_utils.py", line 501, in update_state
metric_obj.update_state(y_t, y_p, sample_weight=mask)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\metrics_utils.py", line 70, in decorated
update_op = update_state_fn(*args, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\metrics\base_metric.py", line 140, in update_state_fn
return ag_update_state(*args, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\metrics\base_metric.py", line 646, in update_state **
matches = ag_fn(y_true, y_pred, **self._fn_kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\metrics\metrics.py", line 3295, in categorical_accuracy
return metrics_utils.sparse_categorical_matches(
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\metrics_utils.py", line 893, in sparse_categorical_matches
matches = tf.cast(tf.equal(y_true, y_pred), backend.floatx())
ValueError: Dimensions must be equal, but are 5 and 250 for '{{node Equal}} = Equal[T=DT_INT64, incompatible_shape_error=true](ArgMax, ArgMax_1)' with input shapes: [?,5], [?,250].
the problem is because of the Loss function and y-label shape.
we should not pad y_label and it should fit the model directly without any other process
Related
I am trying to create a LSTM model for time series prediction, at each time step input has 9 elements and the output has 4.
To create a dataset I write this code:
def create_dataset(dataset, look_back):
dataX, dataY = [], []
for i in range(len(dataset)-look_back):
dataX.append(dataset[i:(i+look_back)]) # all 22 columns for X
dataY.append(dataset[i + look_back, 9:14]) # first 8 columns for Y, just as an example
return np.array(dataX), np.array(dataY)
data = np.concatenate((input, output), axis=1)
X, Y = create_dataset(data, 1)
I used this model
model=Sequential()
model.add(Embedding(1, 13, input_length=304413))
model.add(LSTM(12, input_shape=(304413,1,13), kernel_initializer='normal',activation='relu',return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(12, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(4, activation='relu'))
model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),metrics=['accuracy','mse'])
The input shape is (304413,13) and the output shape is (304413, 4)
The output of summary is:
Model: "sequential_20"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding_15 (Embedding) (None, 304413, 13) 13
lstm_30 (LSTM) (None, 304413, 12) 1248
dropout_28 (Dropout) (None, 304413, 12) 0
lstm_31 (LSTM) (None, 12) 1200
dropout_29 (Dropout) (None, 12) 0
dense_14 (Dense) (None, 4) 52
=================================================================
Total params: 2,513
Trainable params: 2,513
Non-trainable params: 0
and here where I face the error:
pred=model.fit(x,Y, verbose=0,epochs=150, batch_size=70)
The error is
ValueError: in user code:
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1021, in train_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1010, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1000, in run_step **
outputs = model.train_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 859, in train_step
y_pred = self(x, training=True)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py", line 264, in assert_input_compatibility
raise ValueError(f'Input {input_index} of layer "{layer_name}" is '
ValueError: Input 0 of layer "sequential_20" is incompatible with the layer: expected shape=(None, 304413), found shape=(None, 1, 13)
What is my mistake and how can I solve it?
I am trying to hypertune the input shape of an LSTM model based on the different values of timesteps. However, I am facing an issue. While initializing the model, the default value of timesteps (which is 2) is chosen, and accordingly, the build_model.scaled_train is created of shape (4096, 2, 64). Thus the value of input_shape during initialization is (2, 64). When the training starts and the value of timesteps is arbitrarily chosen as 16, then build_model.scaled_train has shape (512, 16, 64). This means that input_shape now takes the value (16, 64). However, this is not reflected in the model. The InputLayer retains the shape (2, 64) it got during initialization. Hence, an error - Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 16, 64), found shape=(None, 2, 64).
def build_model(hp):
timesteps = hp.Choice('timesteps', [2, 4, 8, 16], ordered = False)
....
DFS, UFS = get_data_in_shape(DF, UF, timesteps)
build_model.scaled_train, build_model.train_label = train_test_splitting(DFS, UFS)
model = keras.Sequential()
model.add(InputLayer(input_shape = (timesteps, nosamples))
...
...
return model
class MyTuner(BayesianOptimization):
def run_trial(self, trial, *args, **kwargs):
kwargs['batch_size'] = trial.hyperparameters.Choice('batch_size', [32, 64, 128, 256])
return super(MyTuner, self).run_trial(trial, *args, **kwargs)
tuner = MyTuner(
build_model,
objective ='val_loss',
max_trials = 20,
overwrite = True,
directory = '/content/drive/MyDrive/Colab Notebooks',
project_name = 'bo4')
When I start hyperparameter tuning, this happens.
tuner.search(build_model.scaled_train, build_model.train_label, validation_split = 0.2, epochs = 100, callbacks = [early_stopping])
Error -
Search: Running Trial #1
Value |Best Value So Far |Hyperparameter
16 |? |timesteps
4 |? |layers
1024 |? |unitsLSTM
0.15 |? |rate
64 |? |unitsANN
0.001 |? |learning_rate
Epoch 1/100
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-76-10e3851dd45f> in <module>()
----> 1 tuner.search(build_model.scaled_train, build_model.train_label, validation_split = 0.2, epochs = 100, callbacks = [early_stopping]) #, model_checkpoint
6 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
1145 except Exception as e: # pylint:disable=broad-except
1146 if hasattr(e, "ag_error_metadata"):
-> 1147 raise e.ag_error_metadata.to_exception(e)
1148 else:
1149 raise
ValueError: in user code:
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1021, in train_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1010, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1000, in run_step **
outputs = model.train_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 859, in train_step
y_pred = self(x, training=True)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py", line 264, in assert_input_compatibility
raise ValueError(f'Input {input_index} of layer "{layer_name}" is '
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 16, 64), found shape=(None, 2, 64)
I think I am making a logical mistake somewhere but cannot find it. Please help.
I made some changes which are written below and it worked fine. But I don't know if it is the optimal solution.
def build_model(hp):
...
...
scaled_train, train_label = train_test_splitting(DFS, UFS)
...
...
return model, scaled_train, train_label
class MyTuner(BayesianOptimization):
def run_trial(self, trial, *args, **kwargs):
hp = trial.hyperparameters
model, scaled_train, train_label = self.hypermodel.build(hp)
kwargs['batch_size'] = trial.hyperparameters.Choice('batch_size', [32, 64, 128, 256])
return self.hypermodel.fit(hp, model, scaled_traintrain, train_label, *args, **kwargs)
I am trying to implement the game of Rock, paper and scissors in jupyther notebook using tensorflow with a neural network, the code I am trying to implement is this one: https://learnopencv.com/playing-rock-paper-scissors-with-ai/
When I use my webcam It works correctly, but when I use a dslr camera it doesnt work
The specific line when the code broke is here:
history = model.fit(x=augment.flow(trainX, trainY, batch_size=batchsize), validation_data=(testX, testY),
steps_per_epoch= len(trainX) // batchsize, epochs=epochs)
The complete error is :
Epoch 1/15
7/7 [==============================] - ETA: 0s - loss: 1.0831 - accuracy: 0.6154
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17300/1526770187.py in <module>
4
5 # Start training
----> 6 history = model.fit(x=augment.flow(trainX, trainY, batch_size=batchsize), validation_data=(testX, testY),
7 steps_per_epoch= len(trainX) // batchsize, epochs=epochs)
8
C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py in error_handler(*args, **kwargs)
65 except Exception as e: # pylint: disable=broad-except
66 filtered_tb = process_traceback_frames(e.traceback_)
---> 67 raise e.with_traceback(filtered_tb) from None
68 finally:
69 del filtered_tb
C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py in tf__test_function(iterator)
13 try:
14 do_return = True
---> 15 retval_ = ag_.converted_call(ag.ld(step_function), (ag.ld(self), ag_.ld(iterator)), None, fscope)
16 except:
17 do_return = False
ValueError: in user code:
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1557, in test_function *
return step_function(self, iterator)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1546, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1535, in run_step **
outputs = model.test_step(data)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1499, in test_step
y_pred = self(x, training=False)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\input_spec.py", line 264, in assert_input_compatibility
raise ValueError(f'Input {input_index} of layer "{layer_name}" is '
ValueError: Input 0 of layer "model_1" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(None, 290, 290, 3)
THE COMPLETE CODE OF THE PROGRAM IS HERE: https://learnopencv.com/playing-rock-paper-scissors-with-ai/
From the error, it seems like the shape of the input images is (290, 290, 3). Resizing the images to (224, 224, 3) will solve the issue. Please add the following line before normalizing.
#Resizing images
images = np.resize(images,(400, 224, 224, 3))
#Normalizing images
images = np.array(images, dtype="float") / 255.0
I am trying to train a 1D CNN. My input is a numpy array which has 476 rows and 4 columns. I couldn't figure out how to set input shape. I also tried to reshape input to (476, 4, 1) but still got error. Train_labels's shape is (476, ). O is train data and 0[0].shape is (4,) Here is the code, error and data below.
ValueError: Input 0 of layer "sequential_17" is incompatible with the layer: expected shape=(None, 476, 4), found shape=(1, 4, 1)
Traceback (most recent call last)
<ipython-input-363-440de758fd68> in <module>()
10
11
---> 12 model.fit(o, train_labels, epochs=5, batch_size=1)
13 print(model.evaluate(o, train_labels))
1 frames
/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
65 except Exception as e: # pylint: disable=broad-except
66 filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67 raise e.with_traceback(filtered_tb) from None
68 finally:
69 del filtered_tb
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
1145 except Exception as e: # pylint:disable=broad-except
1146 if hasattr(e, "ag_error_metadata"):
-> 1147 raise e.ag_error_metadata.to_exception(e)
1148 else:
1149 raise
ValueError: in user code:
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1021, in train_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1010, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1000, in run_step **
outputs = model.train_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 859, in train_step
y_pred = self(x, training=True)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py", line 264, in assert_input_compatibility
raise ValueError(f'Input {input_index} of layer "{layer_name}" is '
model=Sequential()
model.add(Conv1D(filters=32, kernel_size=3, activation='relu', input_shape=(476,4)))
model.add(Conv1D(filters=16, kernel_size=3, activation='relu'))
model.add(Dropout(0.5))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(50, activation='relu'))
model.add(Dense(2, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(o, train_labels, epochs=5, batch_size=1)
print(model.evaluate(o, train_labels))
Here is the model structure below.
Model: "sequential_34"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv1d_56 (Conv1D) (None, 474, 32) 416
conv1d_57 (Conv1D) (None, 472, 16) 1552
dropout_19 (Dropout) (None, 472, 16) 0
max_pooling1d_19 (MaxPoolin (None, 236, 16) 0
g1D)
flatten_19 (Flatten) (None, 3776) 0
dense_40 (Dense) (None, 50) 188850
dense_41 (Dense) (None, 2) 102
Total params: 190,920
Trainable params: 190,920
Non-trainable params: 0
My data is a numpy array which has 476 rows and 4 columns. It's shape is (476,4).
[[0.35603836 0.6439616 0.49762452 0.5023755 ]
[0.12395032 0.87604964 0.49762452 0.5023755 ]
[0.5605615 0.43943852 0.49762452 0.5023755 ]
...
[0.6250699 0.37493005 0.48114303 0.51885694]
[0.6650569 0.33494312 0.48114303 0.51885694]
[0.53505033 0.46494964 0.48114303 0.51885694]]
I solved the problem myself and wanted to provide an answer for anyone having the same issue.
Here is the steps I applied:
I used sparse categorical crossentropy.
I changed input shape to (number of attributes, 1)
I changed CNN kernel size from 3 to 2
model=Sequential()
model.add(Conv1D(filters=8, kernel_size=2, activation='relu', input_shape=(4,1)))
model.add(Conv1D(filters=4, kernel_size=2, activation='relu'))
model.add(Dropout(0.3))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(20, activation='relu'))
model.add(Dense(2, activation='softmax'))
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(o, train_labels, epochs=5, batch_size=1)
print(model.evaluate(o, train_labels))
I was trying to train a simple Keras network for classification when I faced the following error. I know there is something wrong with my inputs but I couldn't figure out how to fix it. Here is my code
my data set shape :
x_train : float32 0.0 1.0 (2444, 64, 64, 1)
y_train : float32 0.0 1.0 (2444, 2)
x_test : float32 0.0 1.0 (9123, 64, 64, 1)
y_test : float32 0.0 1.0 (9123, 2)
the model :
inputs = keras.Input(shape=(64,64,1), dtype='float32')
x = keras.layers.Conv2D(12,(9,9), padding="same",input_shape=(64,64,1), dtype='float32',activation='relu')(inputs)
x = keras.layers.Conv2D(18,(7,7), padding="same", activation='relu')(x)
x = keras.layers.MaxPool2D(pool_size=(2,2))(x)
x = keras.layers.Dropout(0.25)(x)
x = keras.layers.Dense(50, activation='relu')(x)
x = keras.layers.Dropout(0.4)(x)
outputs = keras.layers.Dense(2, activation='softmax')(x)
model = keras.Model(inputs, outputs)
model summary :
Model: "model_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_2 (InputLayer) [(None, 64, 64, 1)] 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 64, 64, 12) 984
_________________________________________________________________
conv2d_3 (Conv2D) (None, 64, 64, 18) 10602
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 32, 32, 18) 0
_________________________________________________________________
dropout_2 (Dropout) (None, 32, 32, 18) 0
_________________________________________________________________
dense_2 (Dense) (None, 32, 32, 50) 950
_________________________________________________________________
dropout_3 (Dropout) (None, 32, 32, 50) 0
_________________________________________________________________
dense_3 (Dense) (None, 32, 32, 2) 102
=================================================================
Total params: 12,638
Trainable params: 12,638
Non-trainable params: 0
________________________
compiler and fitter which error occurs when I wanna fit the model
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(),
optimizer=keras.optimizers.Adam(0.01),
metrics=["acc"],
)
model.fit(x_train, y_train, batch_size=32, epochs = 20, validation_split= 0.3,
callbacks=[tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)])
and finally the error:
ValueError Traceback (most recent call last)
<ipython-input-31-e4cade46a08c> in <module>()
1 model.fit(x_train, y_train, batch_size=32, epochs = 20, validation_split= 0.3,
----> 2 callbacks=[tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)])
9 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
992 except Exception as e: # pylint:disable=broad-except
993 if hasattr(e, "ag_error_metadata"):
--> 994 raise e.ag_error_metadata.to_exception(e)
995 else:
996 raise
ValueError: in user code:
/usr/local/lib/python3.7/dist-packages/keras/engine/training.py:853 train_function *
return step_function(self, iterator)
/usr/local/lib/python3.7/dist-packages/keras/engine/training.py:842 step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
/usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:1286 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:2849 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:3632 _call_for_each_replica
return fn(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/keras/engine/training.py:835 run_step **
outputs = model.train_step(data)
/usr/local/lib/python3.7/dist-packages/keras/engine/training.py:792 train_step
self.compiled_metrics.update_state(y, y_pred, sample_weight)
/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py:457 update_state
metric_obj.update_state(y_t, y_p, sample_weight=mask)
/usr/local/lib/python3.7/dist-packages/keras/utils/metrics_utils.py:73 decorated
update_op = update_state_fn(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/keras/metrics.py:177 update_state_fn
return ag_update_state(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/keras/metrics.py:681 update_state **
matches = ag_fn(y_true, y_pred, **self._fn_kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/keras/metrics.py:3537 sparse_categorical_accuracy
return tf.cast(tf.equal(y_true, y_pred), backend.floatx())
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/math_ops.py:1864 equal
return gen_math_ops.equal(x, y, name=name)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/gen_math_ops.py:3219 equal
name=name)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/op_def_library.py:750 _apply_op_helper
attrs=attr_protos, op_def=op_def)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py:601 _create_op_internal
compute_device)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py:3569 _create_op_internal
op_def=op_def)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py:2042 __init__
control_input_ops, op_def)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py:1883 _create_c_op
raise ValueError(str(e))
ValueError: Dimensions must be equal, but are 2 and 32 for '{{node Equal}} = Equal[T=DT_FLOAT, incompatible_shape_error=true](IteratorGetNext:1, Cast_1)' with input shapes: [?,2], [?,32,32].
As you can see in the model summary, the output shape of the model is (None,32,32,2), while based on target values it should be (None,2), Try to add Flatten layer before Dense layers:
x = keras.layers.Dropout(0.25)(x)
x = keras.layers.Flatten()(x) # Add this
x = keras.layers.Dense(50, activation='relu')(x)