'Keras model `logits` and `labels` must have same shape (None, 2) vs (None, 1)
I have a keras model trained for occupancy detection of parking spaces, which I load using keras.models.load_model(PATH_TO_MODEL). The input for the model is a 224 x 224 RGB image. This is the model structure as output of keras.plot_model(...):

I then compile the loaded model using this line of code:
loaded_model.compile(loss='binary_crossentropy', optimizer='adam')
And then I begin the training process using a custom image generator:
def image_generator(input_path:str, bs:int, mode:str='train', img_size:int=224, aug=None):
file_path = os.path.join(OCD_DATA_DIR, 'splits', input_path, 'all.txt')
f = open(file_path, 'r')
while True:
images = []
labels = []
while len(images) < bs:
line = f.readline()
if line == '':
f.seek(0)
line = f.readline()
if mode == 'eval':
break
image_path, label = line.strip().split(' ')
# print(image_path)
image_path = os.path.join(OCD_DATA_DIR, input_path, image_path)
image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED) * 1. / 255
image = cv2.resize(image, (img_size, img_size))
images.append(image)
labels.append(label)
if aug is not None:
(images, labels) = next(aug.flow(np.array(images), labels, batch_size=bs))
labels = np.array(labels).astype('float32')
yield (np.array(images), labels)
generator = image_generator(SvJur_PATH, 64)
history = loaded_model.fit(
x = generator,
steps_per_epoch = NUM_TRAIN_IMAGES // 64,
epochs = 18)
I am getting this error:
ValueError:
logitsandlabelsmust have the same shape, received ((None, 2) vs (None, 1)).
Edit: I have concluded that I can just add a layer to the end of my model so that it has the desired output shape. I do it like this:
model = keras.models.Sequential()
for layer in loaded_model.layers: # go through all layers
model.add(layer)
model.add(keras.layers.Dense(1, activation='softmax'))
But when I compare the predicted values, they do not seem to match:
0.92 0.08
1.00 0.00
1.00 0.00
0.89 0.11
0.41 0.59
Versus the new model predictions:
[1.]
[1.]
[1.]
[1.]
[1.]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
