Reputation: 758
Trying to train a Resnet50 model from it's pre trained form but once it hits the code of training it, it throws this error ValueError: Shapes (None, 5) and (None, 1000) are incompatible
I can't figure out what am I doing wrong here?
I have 5 classes dataset so that's why I am using categorical_crossentropy
as the loss.
Full code is here:
# This is in for loop until labels.append
#load the image, pre-process it, and store it in the data list
image = cv2.imread(imagePath)
image = cv2.resize(image, (224, 224))
image = img_to_array(image)
data.append(image)
# extract the class label from the image path and update the
# labels list
label = imagePath.split(os.path.sep)[-2]
labels.append(label)
print("[INFO] ...reading the images completed", "+ Label class extracted.")
# scale the raw pixel intensities to the range [0, 1]
data = np.array(data, dtype="float") / 255.0
labels = np.array(labels)
print("[INFO] data matrix: {:.2f}MB".format(
data.nbytes / (1024 * 1000.0)))
# binarize the labels
lb = LabelBinarizer()
labels = lb.fit_transform(labels)
# partition the data into training and testing splits using 80% of
# the data for training and the remaining 20% for testing
(trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.2, random_state=42)
model = ResNet50()
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print("[INFO] Model compilation completed.")
# train the network
print("[INFO] training network...")
H = model.fit(trainX, trainY, batch_size=BS,
validation_data=(testX, testY),
steps_per_epoch=len(trainX) // BS,
epochs=EPOCHS, verbose=1)
Upvotes: 0
Views: 604
Reputation: 36704
Try adding a layer with the proper number of categories for your task:
base = ResNet50(include_top=False, pooling='avg')
out = K.layers.Dense(5, activation='softmax')
model = K.Model(inputs=base.input, outputs=out(base.output))
Upvotes: 1
Reputation: 104
You have used the fully connected layers of the pre-trained ResNet, you need to create your appropriate classification layers suitable for your task.
from tensorflow.keras.layers import GlobalAveragePooling2D
from tensorflow.keras import Model
model = ResNet50(include_top=False)
f_flat = GlobalAveragePooling2D()(model.output)
fc = Dense(units=2048,activation="relu")(f_flat)
logit = Dense(units=5, activation="softmax")(fc)
model = Model(model.inputs,logit)
Upvotes: 1