2CNN in Keras: Shape mismatch - python

I'm trying to construct a 2D CNN neural network, looking at this code: https://kgptalkie.com/human-activity-recognition-using-accelerometer-data/. I have four arrtibutes and nine classes
X_train[0].shape, X_test[0].shape
((200, 4), (200, 4))
X_train = X_train.reshape(3104, 200, 4, 1)
X_test = X_test.reshape(776, 200, 4, 1)
X_train[0].shape, X_test[0].shape
((200, 4, 1), (200, 4, 1))
model = Sequential()
model.add(Conv2D(16, (2, 2), activation = 'relu', input_shape = X_train[0].shape))
model.add(Dropout(0.1))
model.add(Conv2D(32, (2, 2), activation='relu'))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(64, activation = 'relu'))
model.add(Dropout(0.5))
model.add(Dense(9, activation='softmax'))
model.compile(optimizer=Adam(learning_rate = 0.001), loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])
history = model.fit(X_train, y_train, epochs = 10, validation_data= (X_test, y_test), verbose=1)
I'm finding this error:
ValueError Traceback (most recent call last)
<ipython-input-42-d7e8ba9ba93b> in <module>()
1 model.compile(optimizer=Adam(learning_rate = 0.001), loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])
----> 2 history = model.fit(X_train, y_train, epochs = 10, validation_data= (X_test, y_test), verbose=1)
10 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
971 except Exception as e: # pylint:disable=broad-except
972 if hasattr(e, "ag_error_metadata"):
--> 973 raise e.ag_error_metadata.to_exception(e)
974 else:
975 raise
ValueError: in user code:
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:806 train_function *
return step_function(self, iterator)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:796 step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
/usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:1211 run
return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2585 call_for_each_replica
return self._call_for_each_replica(fn, args, kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2945 _call_for_each_replica
return fn(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:789 run_step **
outputs = model.train_step(data)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:749 train_step
y, y_pred, sample_weight, regularization_losses=self.losses)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/compile_utils.py:204 __call__
loss_value = loss_obj(y_t, y_p, sample_weight=sw)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:149 __call__
losses = ag_call(y_true, y_pred)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:253 call **
return ag_fn(y_true, y_pred, **self._fn_kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:1567 sparse_categorical_crossentropy
y_true, y_pred, from_logits=from_logits, axis=axis)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/backend.py:4783 sparse_categorical_crossentropy
labels=target, logits=output)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/nn_ops.py:4176 sparse_softmax_cross_entropy_with_logits_v2
labels=labels, logits=logits, name=name)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/nn_ops.py:4091 sparse_softmax_cross_entropy_with_logits
logits.get_shape()))
ValueError: Shape mismatch: The shape of labels (received (288,)) should equal the shape of logits except for the last dimension (received (32, 6)).
Could you help me please?

I resolved the problem changing the loss mode from 'sparse_categorical_crossentropy' to loss=tf.keras.losses.KLDivergence()

Related

How can I recover this Error? Em trying to find accurracy by using LSTM

Model Set Code
EPOCHS = 1
x_tr = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))
x_ts = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))
model = Sequential()
model.add(LSTM(units=390, input_shape = (1,X_train.shape[1]), return_sequences = True))
model.add(LSTM(units=260, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=190, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=160, return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(units=60, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=90, return_sequences=True, name='output'))
model.add(Dense(6,activation='sigmoid'))
#Compiling the model
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
print(model.summary())
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
y_train = np.reshape(y_train, (y_train.shape[0], -1, y_train.shape[1]))
y_test = np.reshape(y_test, (y_test.shape[0], -1, y_test.shape[1]))
# Fitting with 1000 epochs and 20 batch size
model.fit(x_tr, y_train, validation_data=(x_ts, y_test),epochs=EPOCHS,batch_size=20)
This is the error that is showing whenever I run the Code. i don't know which type of error is existing
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 860, in train_step
loss = self.compute_loss(x, y, y_pred, sample_weight)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 919, in compute_loss
y, y_pred, sample_weight, regularization_losses=self.losses)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py", line 201, in __call__
loss_value = loss_obj(y_t, y_p, sample_weight=sw)
File "/usr/local/lib/python3.7/dist-packages/keras/losses.py", line 141, in __call__
losses = call_fn(y_true, y_pred)
File "/usr/local/lib/python3.7/dist-packages/keras/losses.py", line 245, in call **
return ag_fn(y_true, y_pred, **self._fn_kwargs)
File "/usr/local/lib/python3.7/dist-packages/keras/losses.py", line 1790, in categorical_crossentropy
y_true, y_pred, from_logits=from_logits, axis=axis)
File "/usr/local/lib/python3.7/dist-packages/keras/backend.py", line 5083, in categorical_crossentropy
target.shape.assert_is_compatible_with(output.shape)
ValueError: Shapes (None, 512, 2) and (None, 1, 6) are incompatible

ValueError: Unknown loss function: custom_loss_function. Please ensure this object is passed to the `custom_objects` argument

I'm trying to train my model with this custom loss function:
1
where S(pn;ω) is the predicted value (y_pred) and MOSn is the target (y_true), so I wrote it this way:
import keras.backend as K
def custom_loss_function(y_true,y_pred):
for i in range(1,n+1):
l= K.abs(y_pred-y_true)
l = K.mean(l, axis=-1)
return l
then I built my model:
#Model definition
from keras import models
from keras import layers
def build_model():
model = models.Sequential()
model.add(layers.Conv2D(32, (5, 5), activation='relu', input_shape=(32, 32, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(32, (5, 5), activation='relu'))
model.add(layers.MaxPooling2D((10, 10)))
model.add(layers.Dense(250, activation='relu'))
model.add(layers.Dense(250, activation='relu'))
model.add(layers.Dense(1))
model.compile(optimizer='rmsprop', loss='custom_loss_function', metrics=['mae'])
return model
model = build_model()
but when I run the training process:
num_epochs = 20
history = model.fit(train_data, train_labels, epochs=num_epochs, batch_size=None, verbose=0)
I get this error:
ValueError Traceback (most recent call last)
<ipython-input-16-eb44c7fa4ec7> in <module>()
1 num_epochs = 20
----> 2 history = model.fit(train_data, train_labels, epochs=num_epochs, batch_size=None, verbose=0)
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:789 train_step
y, y_pred, sample_weight, regularization_losses=self.losses)
/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py:184 __call__
self.build(y_pred)
/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py:133 build
self._losses = tf.nest.map_structure(self._get_loss_object, self._losses)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/nest.py:869 map_structure
structure[0], [func(*x) for x in entries],
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/nest.py:869 <listcomp>
structure[0], [func(*x) for x in entries],
/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py:273 _get_loss_object
loss = losses_mod.get(loss)
/usr/local/lib/python3.7/dist-packages/keras/losses.py:2136 get
return deserialize(identifier)
/usr/local/lib/python3.7/dist-packages/keras/losses.py:2095 deserialize
printable_module_name='loss function')
/usr/local/lib/python3.7/dist-packages/keras/utils/generic_utils.py:709 deserialize_keras_object
.format(printable_module_name, object_name))
ValueError: Unknown loss function: custom_loss_function. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.
I read the details about the 'custom object' argument and tried to apply it but still can't figure it out, How exactly can I pass my custom function to the 'custom_objects' argument ?
In python, you can pass a function as a self-contained object, or Callable. In this case, you can pass the argument loss=custom_loss_function without the single-quotes. Here's more info about callables and custom loss functions in Tensorflow.

keras - 1D-CNN input compatibility error, a time series problem

I am using the below code where I am trying to train a 1d CNN, my x_train data shape is (10027, 5, 14) and y_train shape is (10027,4). But I am getting an error (below the code)
regarding the shape compatibility.
model = keras.models.Sequential([
keras.layers.Conv1D(filters=20, kernel_size=4, strides=2, padding="valid",
input_shape=(n_timesteps,n_features))
])
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
verbose, epochs, batch_size = 0, 10, 5
model.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=verbose)```
Below error
```ValueError: in user code:
/usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/training.py:805 train_function *
return step_function(self, iterator)
/usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/training.py:795 step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
/usr/local/lib/python3.8/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.8/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.8/dist-packages/tensorflow/python/distribute/distribute_lib.py:3417 _call_for_each_replica
return fn(*args, **kwargs)
/usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/training.py:788 run_step **
outputs = model.train_step(data)
/usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/training.py:755 train_step
loss = self.compiled_loss(
/usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/compile_utils.py:203 __call__
loss_value = loss_obj(y_t, y_p, sample_weight=sw)
/usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/losses.py:152 __call__
losses = call_fn(y_true, y_pred)
/usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/losses.py:256 call **
return ag_fn(y_true, y_pred, **self._fn_kwargs)
/usr/local/lib/python3.8/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/losses.py:1537 categorical_crossentropy
return K.categorical_crossentropy(y_true, y_pred, from_logits=from_logits)
/usr/local/lib/python3.8/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/backend.py:4833 categorical_crossentropy
target.shape.assert_is_compatible_with(output.shape)
/usr/local/lib/python3.8/dist-packages/tensorflow/python/framework/tensor_shape.py:1134 assert_is_compatible_with
raise ValueError("Shapes %s and %s are incompatible" % (self, other))
ValueError: Shapes (None, 4) and (None, 1, 20) are incompatible```
I mean, the last layer of your network is a conv1D with filters=20, so the output of your network will be (batch, 1, 20), and you give a Y with a shape of (batch, 4).
The loss don't understand what it has to compare, since the two arrays are not matching at all.
If you want to have something working you should give a last layer compatible with your Y :
model = keras.models.Sequential([
keras.layers.Conv1D(filters=20, kernel_size=4, strides=2, padding="valid",
input_shape=(n_timesteps,n_features)),
keras.layers.Flatten(),
keras.layers.Dense(4, activation = 'softmax')
])

Why is my neural network giving AttributeError? - "NoneType" object has no attribute "shape"

I am trying to use a neural network to predict 1 of 3 classes. Reading the error message, it seems like the variable I am using to evaluate the model is empty, but this is not the case.
Here's the code:
# train features and labels
train_X = np.array(list(training[:, 0]))
train_y = np.array(list(training[:, 1]))
input_shape = (len(train_X[0]),)
output_shape = len(train_y[0])
epochs = 200
model = Sequential()
model.add(Dense(128, input_shape=input_shape, activation="relu"))
model.add(Dropout(0.6))
model.add(Dense(64, activation="relu"))
model.add(Dropout(0.6))
model.add(Dense(output_shape, activation = "softmax"))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=["accuracy"])
model.summary()
However, when I perform the model.evaluate(train_X) method on my training data it throws the following error message.
AttributeError Traceback (most recent call last)
<ipython-input-33-65f91bca3821> in <module>()
----> 1 model.evaluate(tf.convert_to_tensor(train_X, dtype=tf.int64))
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
AttributeError: in user code:
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1233 test_function *
return step_function(self, iterator)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1224 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:1217 run_step **
outputs = model.test_step(data)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1188 test_step
self.compiled_metrics.update_state(y, y_pred, sample_weight)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/compile_utils.py:387 update_state
self.build(y_pred, y_true)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/compile_utils.py:318 build
self._metrics, y_true, y_pred)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/nest.py:1163 map_structure_up_to
**kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/nest.py:1258 map_structure_with_tuple_paths_up_to
func(*args, **kwargs) for args in zip(flat_path_gen, *flat_value_gen)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/nest.py:1258 <listcomp>
func(*args, **kwargs) for args in zip(flat_path_gen, *flat_value_gen)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/nest.py:1161 <lambda>
lambda _, *values: func(*values), # Discards the path arg.
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/compile_utils.py:418 _get_metric_objects
return [self._get_metric_object(m, y_t, y_p) for m in metrics]
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/compile_utils.py:418 <listcomp>
return [self._get_metric_object(m, y_t, y_p) for m in metrics]
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/compile_utils.py:439 _get_metric_object
y_t_rank = len(y_t.shape.as_list())
AttributeError: 'NoneType' object has no attribute 'shape'
model.evaluate() needs also the labels. Try removing the convert_to_tensor() part and go directly for model.evaluate(train_X, train_Y).
Be sure that you have fitted the model before calling evaluate (you don't show it here).

ValueError: logits and labels must have the same shape ((None, 124, 124, 3) vs (None, 2))

I am developing a image classification model. I have my input shape of image as (128,128,3) but when I am running the model.fit it is giving an error.
My input data is
real_data = [f for f in os.listdir(data_dir+'/test') if f.endswith('.png')]
fake_data = [f for f in os.listdir(data_dir+'/test_f') if f.endswith('.png')]
print(real_data)
X = []
Y = []
for img in real_data:
X.append(img_to_array(load_img(data_dir+'/test/'+img)) / 255.0)
Y.append(1)
for img in fake_data:
X.append(img_to_array(load_img(data_dir+'/test_f/'+img)) / 255.0)
Y.append(0)
Y_val_org = Y
X = np.array(X)
Y = to_categorical(Y, 2)
print(X)
print(Y)
My model is
model = Sequential()
model.add(Conv2D(16, kernel_size=(3,3), activation='relu',input_shape=(128,128,3)))
model.add(Conv2D(16, kernel_size=(3,3), activation='relu'))
model.add(Dense(units=3, activation='softmax'))
model.compile(loss='binary_crossentropy',
optimizer=optimizers.Adam(lr=1e-5, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False),
metrics=['accuracy'])
#model.build(input_shape=(128,128,3))
model.summary()
And model summary is
Model: "sequential_80"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_892 (Conv2D) (None, 126, 126, 16) 448
_________________________________________________________________
conv2d_893 (Conv2D) (None, 124, 124, 16) 2320
_________________________________________________________________
dense_48 (Dense) (None, 124, 124, 3) 51
=================================================================
Total params: 2,819
Trainable params: 2,819
Non-trainable params: 0
_________________________________________________________________
When I am fitting the model through model.fit()
early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=2, mode='auto')
EPOCHS = 20
BATCH_SIZE = 100
history = model.fit(X_train, Y_train, batch_size = BATCH_SIZE, epochs = EPOCHS, validation_data = (X_val, Y_val))
This is the error I am getting
Epoch 1/20
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-168-b3e2ed37ed88> in <module>()
2 EPOCHS = 20
3 BATCH_SIZE = 100
----> 4 history = model.fit(X_train, Y_train, batch_size = BATCH_SIZE, epochs = EPOCHS, validation_data = (X_val, Y_val))
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:756 train_step
y, y_pred, sample_weight, regularization_losses=self.losses)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/compile_utils.py:203 __call__
loss_value = loss_obj(y_t, y_p, sample_weight=sw)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/losses.py:152 __call__
losses = call_fn(y_true, y_pred)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/losses.py:256 call **
return ag_fn(y_true, y_pred, **self._fn_kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/losses.py:1608 binary_crossentropy
K.binary_crossentropy(y_true, y_pred, from_logits=from_logits), axis=-1)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/backend.py:4979 binary_crossentropy
return nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/nn_impl.py:174 sigmoid_cross_entropy_with_logits
(logits.get_shape(), labels.get_shape()))
ValueError: logits and labels must have the same shape ((None, 124, 124, 3) vs (None, 2))
Change your model into:
model.add(Conv2D(16, kernel_size=(3,3), activation='relu'))
model.add(Flatten()) # added flatten before dense
model.add(Dense(units=2, activation='softmax'))
Last output should be 2 units because you have 2 classes. Also change your loss to:
loss='categorical_crossentropy'
because you applied to_categorical().

Categories

Resources