|
| 1 | +import numpy as np |
| 2 | +import pandas as pd |
| 3 | +import cv2 |
| 4 | +import matplotlib.pyplot as plt |
| 5 | +from tensorflow.keras.models import Model, Sequential |
| 6 | +from tensorflow.keras import layers |
| 7 | +import tensorflow as tf |
| 8 | +from keras.preprocessing.image import img_to_array |
| 9 | +from tensorflow.keras import backend |
| 10 | +from tensorflow.keras.preprocessing.image import ImageDataGenerator |
| 11 | +import os |
| 12 | +from sklearn.metrics import classification_report |
| 13 | +import sklearn.metrics as metrics |
| 14 | +import itertools |
| 15 | +for dirname, _, filenames in os.walk('/kaggle/input'): |
| 16 | + for filename in filenames: |
| 17 | + print(os.path.join(dirname, filename)) |
| 18 | +def data_set(dir_data): |
| 19 | + data=[] |
| 20 | + target=[] |
| 21 | + data_map = { |
| 22 | + 'with_mask':1, |
| 23 | + 'without_mask':0 |
| 24 | + } |
| 25 | + skipped=0 |
| 26 | + root=dir_data+'_annotations.csv' |
| 27 | + df1 = pd.read_csv(root) |
| 28 | + df1.dataframeName = '_annotations.csv' |
| 29 | + nRow, nCol = df1.shape |
| 30 | + for i in range(len(df1)): |
| 31 | + without_mask='without_mask' |
| 32 | + k=dir_data+df1['filename'][i] |
| 33 | + image=cv2.imread(k) |
| 34 | + xmin=int(df1['xmin'][i]) |
| 35 | + ymin=int(df1['ymin'][i]) |
| 36 | + xmax=int(df1['xmax'][i]) |
| 37 | + ymax=int(df1['ymax'][i]) |
| 38 | + #image=image[ymin:ymax, xmin:xmax] |
| 39 | + try: |
| 40 | + # resizing to (70 x 70) |
| 41 | + image = cv2.resize(image,(70,70)) |
| 42 | + except Exception as E: |
| 43 | + skipped += 1 |
| 44 | + print(E) |
| 45 | + continue |
| 46 | + if(df1['class'][i]=='mask'): |
| 47 | + without_mask='with_mask' |
| 48 | + image=img_to_array(image) |
| 49 | + data.append(image) |
| 50 | + target.append(data_map[without_mask]) |
| 51 | + data = np.array(data, dtype="float") / 255.0 |
| 52 | + target = tf.keras.utils.to_categorical(np.array(target), num_classes=2) |
| 53 | + return data, target |
| 54 | +training_data,training_target=data_set('./Face-Mask-Detection/kaggle/input/face-mask-detection/train/') |
| 55 | +testing_data,testing_target=data_set('./Face-Mask-Detection/kaggle/input/face-mask-detection/test/') |
| 56 | +valid_data,valid_target=data_set('./Face-Mask-Detection/kaggle/input/face-mask-detection/valid/') |
| 57 | +plt.figure(0, figsize=(100,100)) |
| 58 | +for i in range(1,10): |
| 59 | + plt.subplot(10,5,i) |
| 60 | + plt.imshow(training_data[i]) |
| 61 | +img_shape=training_data[0].shape |
| 62 | +depth, height, width=3, img_shape[0], img_shape[1] |
| 63 | +img_shape=(height, width, depth) |
| 64 | +chanDim=-1 |
| 65 | +if backend.image_data_format() == "channels_first": #Returns a string, either 'channels_first' or 'channels_last' |
| 66 | + img_shape = (depth, height, width) |
| 67 | + chanDim = 1 |
| 68 | +model=Sequential() |
| 69 | +model.add(layers.Conv2D(32,(3,3),input_shape=img_shape)) |
| 70 | +model.add(layers.MaxPooling2D(pool_size=(2,2))) |
| 71 | +model.add(layers.Conv2D(64,(3,3))) |
| 72 | +model.add(layers.Activation('relu')) |
| 73 | +model.add(layers.MaxPooling2D(pool_size=(2,2))) |
| 74 | +model.add(layers.Conv2D(128,(3,3))) |
| 75 | +model.add(layers.Activation('relu')) |
| 76 | +model.add(layers.MaxPooling2D(pool_size=(2,2))) |
| 77 | +model.add(layers.Conv2D(256,(3,3))) |
| 78 | +model.add(layers.Activation('relu')) |
| 79 | +model.add(layers.MaxPooling2D(pool_size=(2,2))) |
| 80 | +model.add(layers.Flatten()) |
| 81 | +model.add(layers.Dropout(0.5)) |
| 82 | +model.add(layers.Dense(64,activation='relu')) |
| 83 | +model.add(layers.Dropout(0.4)) |
| 84 | +model.add(layers.Dense(2,activation='softmax')) |
| 85 | +adam =tf.keras.optimizers.Adam(0.001) |
| 86 | +model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) |
| 87 | +model.summary() |
| 88 | +aug = ImageDataGenerator(rotation_range=25, width_shift_range=0.1, |
| 89 | + height_shift_range=0.1, shear_range=0.2, zoom_range=0.2, |
| 90 | + horizontal_flip=True, fill_mode="nearest") |
| 91 | +history = model.fit(aug.flow(training_data, training_target, batch_size=10), |
| 92 | + epochs=70, |
| 93 | + validation_data=(valid_data, valid_target), |
| 94 | + verbose=2, |
| 95 | + shuffle=True) |
| 96 | +plt.plot(history.history['accuracy']) |
| 97 | +plt.plot(history.history['val_accuracy']) |
| 98 | +plt.ylabel(['accuracy']) |
| 99 | +plt.xlabel(['epoch']) |
| 100 | +plt.legend(['accuracy', 'val_accuracy']) |
| 101 | +plt.plot(history.history['loss']) |
| 102 | +plt.plot(history.history['val_loss']) |
| 103 | +plt.ylabel(['loss']) |
| 104 | +plt.xlabel(['epoch']) |
| 105 | +plt.legend(['loss', 'val_loss']) |
| 106 | +loss, accuracy = model.evaluate(testing_data,testing_target) |
| 107 | +print('accuracy= ',loss," loss= ",loss) |
| 108 | +yhat = model.predict(testing_data) |
| 109 | +test_pred=np.argmax(yhat,axis=1) |
| 110 | +testing_target=np.argmax(testing_target,axis=1) |
| 111 | +report = classification_report(testing_target, test_pred) |
| 112 | +print(report) |
| 113 | +def plot_confusion_matrix(cm, classes, |
| 114 | + normalize=False, |
| 115 | + title='Confusion matrix', |
| 116 | + cmap=plt.cm.RdYlGn): |
| 117 | + plt.imshow(cm, interpolation='nearest', cmap=cmap) |
| 118 | + plt.title(title) |
| 119 | + plt.colorbar() |
| 120 | + tick_marks = np.arange(len(classes)) |
| 121 | + plt.xticks(tick_marks, classes, rotation=45) |
| 122 | + plt.yticks(tick_marks, classes) |
| 123 | + |
| 124 | + thresh = cm.max() / 2. |
| 125 | + for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): |
| 126 | + plt.text(j, i, cm[i, j], |
| 127 | + horizontalalignment="center", |
| 128 | + color="white" if cm[i, j] > thresh else "black") |
| 129 | + |
| 130 | + plt.tight_layout() |
| 131 | + plt.ylabel('True label') |
| 132 | + plt.xlabel('Predicted label') |
| 133 | + |
| 134 | +confusion = metrics.confusion_matrix(testing_target, test_pred) |
| 135 | +plt.figure() |
| 136 | +plot_confusion_matrix(confusion, classes=['without_mask','with_mask'], title='Confusion matrix') |
0 commit comments