The code doesnt have any syntax error and the model accuracy is 95% but when I feed it image to predict emotion, It usually just predicts one of the emotion at random for all inputs.
Here is my code(I have not put data preprocessing part and import part)
classes = ['angry','disgust', 'fear', 'happy', 'neutral','sad', 'surprise']
training_data = []
x = []
y = []
for feature, label in training_data:
x.append(feature)
y.append(label)
X = np.array(x).reshape(-1,224,224,3)
Y = np.array(y)
model = tf.keras.applications.MobileNetV2()
base_input = model.layers[0].input
base_output = model.layers[-2].output
base_output
final_output = layers.Dense(128)(base_output)
final_output = layers.Activation("relu")(final_output)
final_output = layers.Dense(64)(final_output)
final_output = layers.Activation("relu")(final_output)
final_output = layers.Dense(7,activation="softmax")(final_output)
new_model = keras.Model(inputs = base_input, outputs = final_output)
new_model.summary()
new_model.compile(loss = 'sparse_categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
new_model.save("emotion_detection")
test_image = cv2.imread("/content/Happy image to test.jpg")
img_bcp = test_image.copy()
]
face_classifier = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
gray_img = cv2.cvtColor(test_image, cv2.COLOR_BGR2GRAY)
faces_coordinates = face_classifier.detectMultiScale(gray_img)
for (x, y, w, h) in faces_coordinates:
# Draw rectangle around face
cv2.rectangle(test_image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Crop face from image
cropped_face = img_bcp[y:y+h, x:x+w]
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(test_image, cv2.COLOR_BGR2RGB))
plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(cropped_face, cv2.COLOR_BGR2RGB))
class_dictionary = {0: 'angry', 1: 'fear', 2: 'happy', 3: 'neutral', 4: 'sad', 5: 'surprise'}
final_image = cv2.resize(cropped_face, (224,224))
final_image = np.expand_dims(final_image, axis=0) ## Need 4th dimension
final_image = final_image/255.0 ## Normalizing ```
new_model = tf.keras.models.load_model('emotion_detection')
prediction = new_model.predict(final_image)
class_dictionary[np.argmax(prediction)]
Here is accuracy Here is the wrong output
I have tried increases dataset, Changing code here and there, Changed layers ETC