Reputation: 79
im trying to build image classification model that will predict if you are wearing a mask.This is a first time i make my own model and when im training it the accuracy jump arround 50% and if i predict it always says "no mask" i tryied changing number of epoches, batch size, number of training data changing model code and nothing works. This is my code:
import os
import cv2
import random
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten,Dropout
from tensorflow.keras.optimizers import SGD
def preproccesImage(img):
img = cv2.resize(img,dsize=(150,150 ), interpolation = cv2.INTER_CUBIC)
return img
def getData():
training = []
for image in os.listdir("src/data/with_mask"):
img = cv2.imread(f"src/data/with_mask/{image}",cv2.IMREAD_GRAYSCALE)
proccesed = preproccesImage(img)
training.append([proccesed.tolist(),1])
for image in os.listdir("src/data/without_mask"):
img = cv2.imread(f"src/data/without_mask/{image}",cv2.IMREAD_GRAYSCALE)
proccesed = preproccesImage(img)
training.append([proccesed.tolist(),0])
random.shuffle(training)
train_x = np.array([x[0] for x in training],dtype=np.float32)
train_y = np.array([x[1] for x in training],dtype=np.float32)
print(train_x)
print(train_y)
return (train_x ,train_y)
train_x , train_y = getData()
model = Sequential()
model.add(Dense(32,input_shape=(len(train_x[0]),150),activation="relu"))
model.add(Flatten())
model.add(Dense(128,activation="relu"))
model.add(Dropout(0.2))
model.add(Dense(128,activation="relu"))
model.add(Flatten())
model.add(Dense(1,activation="softmax"))
model.compile(loss="categorical_crossentropy",
optimizer="adam", metrics=["accuracy"])
hist = model.fit(
train_x,train_y,
epochs=200, batch_size=2, verbose=1)
model.save("model.h5", hist)
img = cv2.imread("src/me.png",cv2.IMREAD_GRAYSCALE)
resized = cv2.resize(img,dsize=(150,150 ), interpolation = cv2.INTER_CUBIC)
def predict():
res = model.predict([resized.tolist()])[0]
resoult = [[i, r] for i, r in enumerate(res)]
predicted = []
for r in resoult:
predicted.append({"intent": 1 if r[0] == 1 else 0, "probability": r[1]})
if predicted[0]["intent"] == 1:
print("mask on")
else:
print('no mask')
predict()
I will be pleased if someone can help
Upvotes: 0
Views: 101
Reputation: 60319
This is not the correct combination for binary classification; you should change your loss to binary_crossentropy
and the activation of your last layer to sigmoid
, i.e.:
model.add(Dense(1,activation="sigmoid")) # last layer
model.compile(loss="binary_crossentropy",
optimizer="adam", metrics=["accuracy"])
More generally, you could really benefit from some convolutional layers in the early stages of your model; notice also that placing Flatten
layers after Dense
ones does not make any sense.
Upvotes: 1