{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-04-08T03:09:32.241644Z","iopub.execute_input":"2022-04-08T03:09:32.241940Z","iopub.status.idle":"2022-04-08T03:09:33.058833Z","shell.execute_reply.started":"2022-04-08T03:09:32.241887Z","shell.execute_reply":"2022-04-08T03:09:33.058067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"!pip install dlib","metadata":{"execution":{"iopub.status.busy":"2022-03-28T04:16:29.973807Z","iopub.execute_input":"2022-03-28T04:16:29.974056Z"}}},{"cell_type":"code","source":"!pip install dlib","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:09:33.064008Z","iopub.execute_input":"2022-04-08T03:09:33.064268Z","iopub.status.idle":"2022-04-08T03:20:39.514292Z","shell.execute_reply.started":"2022-04-08T03:09:33.064222Z","shell.execute_reply":"2022-04-08T03:20:39.513451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import dlib\nimport cv2\nimport os\nimport re\nimport json\nfrom pylab import *\nfrom PIL import Image, ImageChops, ImageEnhance","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:20:39.518261Z","iopub.execute_input":"2022-04-08T03:20:39.518567Z","iopub.status.idle":"2022-04-08T03:20:40.087906Z","shell.execute_reply.started":"2022-04-08T03:20:39.518512Z","shell.execute_reply":"2022-04-08T03:20:40.086872Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.mkdir('/kaggle/working/dataset')\nos.mkdir('/kaggle/working/dataset/real')\nos.mkdir('/kaggle/working/dataset/fake')","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:20:40.091302Z","iopub.execute_input":"2022-04-08T03:20:40.094182Z","iopub.status.idle":"2022-04-08T03:20:40.101173Z","shell.execute_reply.started":"2022-04-08T03:20:40.091603Z","shell.execute_reply":"2022-04-08T03:20:40.100129Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_frame_folder = '/kaggle/input/deepfake-detection-challenge/train_sample_videos'\nwith open(os.path.join(train_frame_folder, 'metadata.json'), 'r') as file:\n    data = json.load(file)\nlist_of_train_data = [f for f in os.listdir(train_frame_folder) if f.endswith('.mp4')]\ndetector = dlib.get_frontal_face_detector()\nfor vid in list_of_train_data:\n    count = 0\n    cap = cv2.VideoCapture(os.path.join(train_frame_folder, vid))\n    frameRate = cap.get(5)\n    while cap.isOpened():\n        frameId = cap.get(1)\n        ret, frame = cap.read()\n        if ret != True:\n            break\n        if frameId % ((int(frameRate)+1)*1) == 0:\n            face_rects, scores, idx = detector.run(frame, 0)\n            for i, d in enumerate(face_rects):\n                x1 = d.left()\n                y1 = d.top()\n                x2 = d.right()\n                y2 = d.bottom()\n                crop_img = frame[y1:y2, x1:x2]\n                if data[vid]['label'] == 'REAL':\n                    cv2.imwrite('/kaggle/working/dataset/real/'+vid.split('.')[0]+'_'+str(count)+'.png', cv2.resize(crop_img, (128, 128)))\n                elif data[vid]['label'] == 'FAKE':\n                    cv2.imwrite('/kaggle/working/dataset/fake/'+vid.split('.')[0]+'_'+str(count)+'.png', cv2.resize(crop_img, (128, 128)))\n                count+=1","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:35.339588Z","iopub.execute_input":"2022-04-08T03:43:35.339891Z","iopub.status.idle":"2022-04-08T04:23:17.181887Z","shell.execute_reply.started":"2022-04-08T03:43:35.339836Z","shell.execute_reply":"2022-04-08T04:23:17.181049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport cv2\nimport json\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sn\nimport pandas as pd\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix","metadata":{"execution":{"iopub.status.busy":"2022-04-08T04:24:31.549666Z","iopub.execute_input":"2022-04-08T04:24:31.550001Z","iopub.status.idle":"2022-04-08T04:24:36.746945Z","shell.execute_reply.started":"2022-04-08T04:24:31.549929Z","shell.execute_reply":"2022-04-08T04:24:36.746231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"input_shape = (128, 128, 3)\ndata_dir = '/kaggle/working/dataset'\n\nreal_data = [f for f in os.listdir(data_dir+'/real') if f.endswith('.png')]\nfake_data = [f for f in os.listdir(data_dir+'/fake') if f.endswith('.png')]\n\nX = []\nY = []\n\nfor img in real_data:\n    X.append(img_to_array(load_img(data_dir+'/real/'+img)).flatten() / 255.0)\n    Y.append(1)\nfor img in fake_data:\n    X.append(img_to_array(load_img(data_dir+'/fake/'+img)).flatten() / 255.0)\n    Y.append(0)\n\nY_val_org = Y\n\n#Normalization\nX = np.array(X)\nY = to_categorical(Y, 2)\n\n#Reshape\nX = X.reshape(-1, 128, 128, 3)\n\n#Train-Test split\nX_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size = 0.2, random_state=5)","metadata":{"execution":{"iopub.status.busy":"2022-04-08T04:24:46.974835Z","iopub.execute_input":"2022-04-08T04:24:46.975185Z","iopub.status.idle":"2022-04-08T04:24:51.171486Z","shell.execute_reply.started":"2022-04-08T04:24:46.975124Z","shell.execute_reply":"2022-04-08T04:24:51.170517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(Y_train)","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:23.580275Z","iopub.status.idle":"2022-04-08T03:43:23.580856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.applications import InceptionResNetV2\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import InputLayer\nfrom tensorflow.keras.layers import GlobalAveragePooling2D\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.models import Model \nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping\n\ngoogleNet_model = InceptionResNetV2(include_top=False, weights='imagenet', input_shape=input_shape)\ngoogleNet_model.trainable = True\nmodel = Sequential()\nmodel.add(googleNet_model)\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(units=2, activation='softmax'))\nmodel.compile(loss='binary_crossentropy',\n              optimizer=optimizers.Adam(lr=1e-5, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False),\n              metrics=['accuracy'])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-08T04:26:01.884262Z","iopub.execute_input":"2022-04-08T04:26:01.884560Z","iopub.status.idle":"2022-04-08T04:26:23.818822Z","shell.execute_reply.started":"2022-04-08T04:26:01.884509Z","shell.execute_reply":"2022-04-08T04:26:23.817819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"early_stopping = EarlyStopping(monitor='val_loss',\n                               min_delta=0,\n                               patience=2,\n                               verbose=0, mode='auto')\nEPOCHS = 20\nBATCH_SIZE = 100\nhistory = model.fit(X_train, Y_train, batch_size = BATCH_SIZE, epochs = EPOCHS, validation_data = (X_val, Y_val), verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-08T04:26:36.554442Z","iopub.execute_input":"2022-04-08T04:26:36.554785Z","iopub.status.idle":"2022-04-08T04:30:56.883758Z","shell.execute_reply.started":"2022-04-08T04:26:36.554726Z","shell.execute_reply":"2022-04-08T04:30:56.882817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 4))\nt = f.suptitle('Pre-trained InceptionResNetV2 Transfer Learn with Fine-Tuning & Image Augmentation Performance ', fontsize=12)\nf.subplots_adjust(top=0.85, wspace=0.3)\n\nepoch_list = list(range(1,EPOCHS+1))\nax1.plot(epoch_list, history.history['accuracy'], label='Train Accuracy')\nax1.plot(epoch_list, history.history['val_accuracy'], label='Validation Accuracy')\nax1.set_xticks(np.arange(0, EPOCHS+1, 1))\nax1.set_ylabel('Accuracy Value')\nax1.set_xlabel('Epoch #')\nax1.set_title('Accuracy')\nl1 = ax1.legend(loc=\"best\")\n\nax2.plot(epoch_list, history.history['loss'], label='Train Loss')\nax2.plot(epoch_list, history.history['val_loss'], label='Validation Loss')\nax2.set_xticks(np.arange(0, EPOCHS+1, 1))\nax2.set_ylabel('Loss Value')\nax2.set_xlabel('Epoch #')\nax2.set_title('Loss')\nl2 = ax2.legend(loc=\"best\")","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:23.585281Z","iopub.status.idle":"2022-04-08T03:43:23.585862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def print_confusion_matrix(y_true, y_pred):\n    cm = confusion_matrix(y_true, y_pred)\n    print('True positive = ', cm[0][0])\n    print('False positive = ', cm[0][1])\n    print('False negative = ', cm[1][0])\n    print('True negative = ', cm[1][1])\n    print('\\n')\n    df_cm = pd.DataFrame(cm, range(2), range(2))\n    sn.set(font_scale=1.4) # for label size\n    sn.heatmap(df_cm, annot=True, annot_kws={\"size\": 16}) # font size\n    plt.ylabel('Actual label', size = 20)\n    plt.xlabel('Predicted label', size = 20)\n    plt.xticks(np.arange(2), ['Fake', 'Real'], size = 16)\n    plt.yticks(np.arange(2), ['Fake', 'Real'], size = 16)\n    plt.ylim([2, 0])\n    plt.show()\n    \nprint_confusion_matrix(Y_val_org, model.predict_classes(X))","metadata":{"execution":{"iopub.status.busy":"2022-04-08T04:46:11.067402Z","iopub.execute_input":"2022-04-08T04:46:11.067729Z","iopub.status.idle":"2022-04-08T04:46:14.563227Z","shell.execute_reply.started":"2022-04-08T04:46:11.067671Z","shell.execute_reply":"2022-04-08T04:46:14.562292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('deepfake-detection-model.h5')","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:23.588664Z","iopub.status.idle":"2022-04-08T03:43:23.589264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nimport dlib\nimport cv2\nimport os\nimport numpy as np\nfrom PIL import Image, ImageChops, ImageEnhance\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing.image import img_to_array, load_img","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:23.590324Z","iopub.status.idle":"2022-04-08T03:43:23.590909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.__version__","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:23.591954Z","iopub.status.idle":"2022-04-08T03:43:23.592594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = load_model('deepfake-detection-model.h5')","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:23.593695Z","iopub.status.idle":"2022-04-08T03:43:23.594294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"input_shape = (128, 128, 3)\npr_data = []\ndetector = dlib.get_frontal_face_detector()\ncap = cv2.VideoCapture('../input/deepfake-detection-challenge/test_videos/jzmzdispyo.mp4')\nframeRate = cap.get(5)\nwhile cap.isOpened():\n    frameId = cap.get(1)\n    ret, frame = cap.read()\n    if ret != True:\n        break\n    if frameId % ((int(frameRate)+1)*1) == 0:\n        face_rects, scores, idx = detector.run(frame, 0)\n        for i, d in enumerate(face_rects):\n            x1 = d.left()\n            y1 = d.top()\n            x2 = d.right()\n            y2 = d.bottom()\n            crop_img = frame[y1:y2, x1:x2]\n            data = img_to_array(cv2.resize(crop_img, (128, 128))).flatten() / 255.0\n            data = data.reshape(-1, 128, 128, 3)\n            print(model.predict_classes(data))","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:23.595366Z","iopub.status.idle":"2022-04-08T03:43:23.595947Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sklearn.metrics\ncm = sklearn.metrics.accuracy_score(Y_val_org, model.predict_classes(X))","metadata":{"execution":{"iopub.status.busy":"2022-04-08T04:36:10.488721Z","iopub.execute_input":"2022-04-08T04:36:10.489051Z","iopub.status.idle":"2022-04-08T04:36:19.952312Z","shell.execute_reply.started":"2022-04-08T04:36:10.488993Z","shell.execute_reply":"2022-04-08T04:36:19.951498Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(cm)","metadata":{"execution":{"iopub.status.busy":"2022-04-08T04:36:35.804157Z","iopub.execute_input":"2022-04-08T04:36:35.804489Z","iopub.status.idle":"2022-04-08T04:36:35.810254Z","shell.execute_reply.started":"2022-04-08T04:36:35.804416Z","shell.execute_reply":"2022-04-08T04:36:35.809219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install keras_efficientnets\n\nfrom keras_efficientnets import EfficientNetB5","metadata":{"execution":{"iopub.status.busy":"2022-04-08T05:39:47.234459Z","iopub.execute_input":"2022-04-08T05:39:47.235071Z","iopub.status.idle":"2022-04-08T05:39:53.829423Z","shell.execute_reply.started":"2022-04-08T05:39:47.234995Z","shell.execute_reply":"2022-04-08T05:39:53.828526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Defining the model\nbase_model = EfficientNetB5(include_top=False, weights=\"imagenet\", input_shape=input_shape, classes=2)\n\n#Adding the final layers to the above base models where the actual classification is done in the dense layers\n\nmodel1= Sequential()\nmodel1.add(base_model) \nmodel1.add(Flatten())\n\n#Adding the Dense layers along with activation and batch normalization\nmodel1.add(Dense(1024,activation=('relu'),input_dim=512))\n\nmodel1.add(Dense(512,activation=('relu'))) \nmodel1.add(Dense(256,activation=('relu'))) \n#model.add(Dropout(.3))\nmodel1.add(Dense(128,activation=('relu')))\n#model.add(Dropout(.2))\nmodel1.add(Dense(2,activation=('softmax')))\n#Model summary\nmodel1.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-08T05:41:55.955280Z","iopub.execute_input":"2022-04-08T05:41:55.955611Z","iopub.status.idle":"2022-04-08T05:42:08.020929Z","shell.execute_reply.started":"2022-04-08T05:41:55.955557Z","shell.execute_reply":"2022-04-08T05:42:08.019736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size= 200\nepochs=15 \nlearn_rate=.001 \nsgd=SGD(learning_rate=learn_rate,momentum=.9,nesterov=False) \nadam=Adam(learning_rate=learn_rate, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False) \nmodel1.compile(optimizer=sgd,loss='binary_crossentropy',metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-04-08T05:42:35.504480Z","iopub.execute_input":"2022-04-08T05:42:35.504782Z","iopub.status.idle":"2022-04-08T05:42:35.547793Z","shell.execute_reply.started":"2022-04-08T05:42:35.504729Z","shell.execute_reply":"2022-04-08T05:42:35.547133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model1.fit(X_train,Y_train, batch_size = 100, epochs = 25, validation_data = (X_val,Y_val), verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-08T05:45:01.282101Z","iopub.execute_input":"2022-04-08T05:45:01.282422Z","iopub.status.idle":"2022-04-08T05:58:12.645321Z","shell.execute_reply.started":"2022-04-08T05:45:01.282367Z","shell.execute_reply":"2022-04-08T05:58:12.644560Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sklearn.metrics\ncm = sklearn.metrics.accuracy_score(Y_val_org, model1.predict_classes(X))\nprint(cm)","metadata":{"execution":{"iopub.status.busy":"2022-04-08T06:05:00.677909Z","iopub.execute_input":"2022-04-08T06:05:00.678213Z","iopub.status.idle":"2022-04-08T06:05:18.213697Z","shell.execute_reply.started":"2022-04-08T06:05:00.678169Z","shell.execute_reply":"2022-04-08T06:05:18.212857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(os.list'../input/deepfake-detection-challenge/train_sample_videos/metadata.json')","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:23.600566Z","iopub.status.idle":"2022-04-08T03:43:23.601165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import h5py","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:23.602230Z","iopub.status.idle":"2022-04-08T03:43:23.602805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filename = \"./deepfake-detection-model.h5\"\n\nh5 = h5py.File(filename,'r')\nprint(h5)\nh5.close()","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:23.603849Z","iopub.status.idle":"2022-04-08T03:43:23.604447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import keras,os\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, MaxPool2D , Flatten\nfrom keras.preprocessing.image import ImageDataGenerator\nimport numpy as np\nfrom keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.optimizers import SGD,Adam","metadata":{"execution":{"iopub.status.busy":"2022-04-08T04:37:27.644194Z","iopub.execute_input":"2022-04-08T04:37:27.644512Z","iopub.status.idle":"2022-04-08T04:37:27.650313Z","shell.execute_reply.started":"2022-04-08T04:37:27.644456Z","shell.execute_reply":"2022-04-08T04:37:27.648950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = VGG16(include_top = False, weights = 'imagenet', input_shape = input_shape, classes = 2) \nmodel= Sequential() \nmodel.add(base_model) \nmodel.add(Flatten()) \nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-08T05:34:36.034553Z","iopub.execute_input":"2022-04-08T05:34:36.034880Z","iopub.status.idle":"2022-04-08T05:34:36.346435Z","shell.execute_reply.started":"2022-04-08T05:34:36.034822Z","shell.execute_reply":"2022-04-08T05:34:36.345729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.add(Dense(1024,activation=('relu'),input_dim=2))\nmodel.add(Dense(512,activation=('relu'))) \nmodel.add(Dense(256,activation=('relu'))) \n\nmodel.add(Dense(128,activation=('relu')))\n#model.add(Dropout(.2))\nmodel.add(Dense(64,activation=('relu')))\nmodel.add(Dense(32,activation=('relu')))\nmodel.add(Dense(8,activation=('relu'))) \n#model.add(Dropout(.4))\nmodel.add(Dense(2,activation=('softmax'))) \n\n#Checking the final model summary\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-08T05:34:39.844685Z","iopub.execute_input":"2022-04-08T05:34:39.845024Z","iopub.status.idle":"2022-04-08T05:34:39.913860Z","shell.execute_reply.started":"2022-04-08T05:34:39.844966Z","shell.execute_reply":"2022-04-08T05:34:39.913161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size= 200\nepochs=15 \nlearn_rate=.001 \nsgd=SGD(learning_rate=learn_rate,momentum=.9,nesterov=False) \nadam=Adam(learning_rate=learn_rate, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False) \nmodel.compile(optimizer=sgd,loss='binary_crossentropy',metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-04-08T05:34:43.513180Z","iopub.execute_input":"2022-04-08T05:34:43.513485Z","iopub.status.idle":"2022-04-08T05:34:43.547931Z","shell.execute_reply.started":"2022-04-08T05:34:43.513434Z","shell.execute_reply":"2022-04-08T05:34:43.547270Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# channels=3\n# batch_size=25\n# test_batch_size=32 \n# test_steps=1\n# train_path = './dataset/train'\n# test_path = './dataset/test'\n# val_path = './dataset/val'\n# print ( 'test batch size: ' ,test_batch_size, '  test steps: ', test_steps)\n# def scalar(img):    \n#     return img  # EfficientNet expects pixelsin range 0 to 255 so no scaling is required\n# trgen=ImageDataGenerator(preprocessing_function=scalar, horizontal_flip=True)\n# tvgen=ImageDataGenerator(preprocessing_function=scalar)\n# train_generator=trgen.flow_from_directory( directory=train_path , target_size=(224,224), class_mode='binary_crossentrophy',\n#                                     color_mode='rgb', shuffle=True, batch_size=batch_size)\n# test_generator=tvgen.flow_from_directory( directory=test_path, target_size=(224,224), class_mode='binary_crossentrophy',\n#                                     color_mode='rgb', shuffle=False, batch_size=test_batch_size)\n\n# valid_generator=tvgen.flow_from_directory( directory=X_va, target_size=(224,224), class_mode='binary_crossentrophy',\n#                                     color_mode='rgb', shuffle=True, batch_size=batch_size)\n# classes=list(train_generator.class_indices.keys())\n# class_count=len(classes)\n# train_steps=int(np.ceil(len(train_generator.labels)/batch_size))","metadata":{"execution":{"iopub.status.busy":"2022-04-08T03:43:23.612223Z","iopub.status.idle":"2022-04-08T03:43:23.612800Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(X_train,Y_train, batch_size = 500, epochs = 25, validation_data = (X_val,Y_val), verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-08T05:34:49.143932Z","iopub.execute_input":"2022-04-08T05:34:49.144277Z","iopub.status.idle":"2022-04-08T05:38:08.890437Z","shell.execute_reply.started":"2022-04-08T05:34:49.144210Z","shell.execute_reply":"2022-04-08T05:38:08.889527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print_confusion_matrix(Y_val_org, model.predict_classes(X))","metadata":{"execution":{"iopub.status.busy":"2022-04-08T05:38:17.849811Z","iopub.execute_input":"2022-04-08T05:38:17.850142Z","iopub.status.idle":"2022-04-08T05:38:21.396997Z","shell.execute_reply.started":"2022-04-08T05:38:17.850079Z","shell.execute_reply":"2022-04-08T05:38:21.395956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sklearn.metrics\ncm = sklearn.metrics.accuracy_score(Y_val_org, model.predict_classes(X))\nprint(cm)","metadata":{"execution":{"iopub.status.busy":"2022-04-08T05:38:25.003222Z","iopub.execute_input":"2022-04-08T05:38:25.003545Z","iopub.status.idle":"2022-04-08T05:38:28.118608Z","shell.execute_reply.started":"2022-04-08T05:38:25.003488Z","shell.execute_reply":"2022-04-08T05:38:28.117830Z"},"trusted":true},"execution_count":null,"outputs":[]}]}