<jupyter_start><jupyter_text>Importing Libraries<jupyter_code>import os
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.models import Sequential, load_model
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense
path=r'C:\Users\sahoo\Desktop\Models\Corona mask detector\dataset'
labels=['with_mask','without_mask']
img_cube=[]
for i in os.listdir(path):
    final_path=path+'\\'+i
    label=labels.index(i)
    for j in os.listdir(final_path):
        img=cv2.imread(final_path+'\\'+j,1)
        img=cv2.resize(img,(200,200))
        img_cube.append([img,label])
        
len(img_cube) ,img_cube[0][0]
plt.imshow(img_cube[1][0])
print("Label: ",img_cube[1][1])
plt.show()

plt.imshow(img_cube[1000][0])
print("Label: ",img_cube[1000][1])
plt.show()<jupyter_output>Label:  1<jupyter_text>Split dataset into train and test<jupyter_code>features,target=([] for i in range(2))
for i,j in img_cube:
    features.append(i)
    target.append(j)
features=np.array(features)
features=features/255.0
target=np.array(target)
x_train,x_test,y_train,y_test=train_test_split(features, target, test_size=0.25, random_state=42)
print(x_train.shape,x_test.shape)
print(y_train.shape,y_test.shape)
features[0]
x_test.shape<jupyter_output><empty_output><jupyter_text>Train Neural Network model<jupyter_code>model=Sequential()
model.add(Conv2D(64,(3,3),input_shape=x_train.shape[1:],activation="relu"))
model.add(MaxPooling2D(3,3))
model.add(Conv2D(128,(3,3),activation="relu"))
model.add(MaxPooling2D(3,3))
model.add(Conv2D(256,(3,3),activation="relu"))
model.add(MaxPooling2D((3,3)))
model.add(Flatten()) 
model.add(Dense(2048,activation="relu"))
model.add(Dense(1024,activation="relu"))
model.add(Dense(512,activation="relu"))
model.add(Dense(2,activation="sigmoid"))
model.compile(loss="sparse_categorical_crossentropy",optimizer="adam",metrics=["accuracy"])
history=model.fit(features,target,epochs=20,validation_data=(x_test,y_test))
# Evaluating the Predictions on the Model

score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
y_pred=[]
for i in range(len(x_test)):
        y_pred.append(model.predict(x_test[i].reshape(1,200,200,3)))
        
len(y_test),len(y_pred)
y_pred[:10]  #to get max probability value we use argmax
#as prediction value returning 3 values array but we want prediction that shows a particular class (ie; 0 or 1 or 2)

y_pred2=[]
for i in range(len(x_test)):
    y_pred2.append(np.argmax(y_pred[i],axis=1)) #it will take index value for which value is maxiumum of that array
y_pred2[:10]
model.summary()

print("*-*"*40)
print("Accuracy Found: ",accuracy_score(y_test,np.array(y_pred2)))
#using adam accuracy was 83%
#using adadelta accuracy was 89%
print("*-*"*40)
print("Confusion Matrix:\n",confusion_matrix(y_test,np.array(y_pred2))) 
print("*-*"*40)
print("Classification Report:\n",classification_report(y_test,np.array(y_pred2)))
print("*-*"*40)

#plt.figure(figsize=(15,9))
plt.title('Loss Comparison',fontsize=20)
plt.plot(history.history['loss'],)
plt.plot(history.history['val_loss'])
plt.legend(['Training Loss','Validation Loss'])
plt.show()


#plt.figure(figsize=(15,9))
plt.title('Accuracy comparison ',fontsize=20)
plt.plot(history.history['accuracy'],)
plt.plot(history.history['val_accuracy'])
plt.legend(['Training Acc','Validation Acc'])
plt.show()
model.save("Corona-Mask-detector.h5")
def getClassName(n):
    if n==0: return 'with mask'
    else: return 'without mask!'
    
cap=cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)
cap.set(10,180)
font = cv2.FONT_HERSHEY_SIMPLEX
while True:
    success,imgOriginal=cap.read()
    img=np.asarray(imgOriginal)
    img=cv2.resize(img,(200,200))
    #img=preprocessing(img)
    #cv2.imshow("Processed Image",img)
    img=img.reshape(1,200,200,3)
    cv2.putText(imgOriginal,"Class: ",(20,35),font,0.75,(0,0,255),2,cv2.LINE_AA)
    cv2.putText(imgOriginal,"Probability: ",(20,75),font,0.75,(0,0,255),2,cv2.LINE_AA)
    model=load_model("Corona-Mask-detector.h5")
    predictions=model.predict(img)
    classIndex=model.predict_classes(img)
    probabilityValue=np.amax(predictions)
    if probabilityValue>0.60:
        cv2.putText(imgOriginal,str(classIndex) + " "+ str(getClassName(classIndex)),(120,35),font,0.75,(0,0,255),2,cv2.LINE_AA)
        cv2.putText(imgOriginal,str(round(probabilityValue*100,2)) + "%",(120,75),font,0.75,(0,0,255),2,cv2.LINE_AA)
    cv2.imshow("Result",imgOriginal)
    if cv2.waitKey(1) and 0xFF==ord("q"):
        break<jupyter_output>WARNING:tensorflow:From <ipython-input-3-2f45909e5fc0>:22: Sequential.predict_classes (from tensorflow.python.keras.engine.sequential) is deprecated and will be removed after 2021-01-01.
Instructions for updating:
Please use instead:* `np.argmax(model.predict(x), axis=-1)`,   if your model does multi-class classification   (e.g. if it uses a `softmax` last-layer activation).* `(model.predict(x) > 0.5).astype("int32")`,   if your model does binary classification   (e.g. if it uses a `sigmoid` last-layer activation).
WARNING:tensorflow:5 out of the last 9 calls to <function Model.make_predict_function.<locals>.predict_function at 0x000001A5206070D0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimenta[...]
{'fraction_non_alphanumeric': 0.15834647048519881, 'fraction_numerical': 0.049570853039061134, 'mean_word_length': 6.705802968960864, 'pattern_counts': {'":': 0, '<': 14, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '314183', 'license': 'Unlicense', 'n_tokens_mistral': 2246, 'n_tokens_neox': 2089, 'n_words': 386, 'path': 'Corona-Mask-Detector_code.ipynb', 'repo_name': 'SibPrasad/Corona-Mask-detector', 'size': '5709'}