{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":5441,"databundleVersionId":38425,"sourceType":"competition"},{"sourceId":9900,"sourceType":"datasetVersion","datasetId":6209},{"sourceId":110819,"sourceType":"datasetVersion","datasetId":57539},{"sourceId":110930,"sourceType":"datasetVersion","datasetId":57578}],"dockerImageVersionId":11543,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline \nimport cv2\nimport os","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-07-17T15:52:05.819512Z","iopub.execute_input":"2025-07-17T15:52:05.819794Z","iopub.status.idle":"2025-07-17T15:52:05.825433Z","shell.execute_reply.started":"2025-07-17T15:52:05.819744Z","shell.execute_reply":"2025-07-17T15:52:05.824487Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Handling Data ","metadata":{}},{"cell_type":"code","source":"num_of_class = 2\nchannels=3\nimage_resize=(200, 200)\nresnet_pooling='avg'\ndense_activation='softmax'\nobject_finction='categorical_crossentropy'\nmetricss=['accuracy']\nnum_of_epochs=10\nearly_stop=4\nsteps_epoch_train=10\nstpes_epoch_test=10\nbatch_size_train=100\nbatch_size_validate=100\nbatch_size_test=1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T16:56:10.443406Z","iopub.execute_input":"2025-07-17T16:56:10.443667Z","iopub.status.idle":"2025-07-17T16:56:10.448145Z","shell.execute_reply.started":"2025-07-17T16:56:10.443619Z","shell.execute_reply":"2025-07-17T16:56:10.447429Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Read pretrained NN (resnet50)","metadata":{}},{"cell_type":"code","source":"from tensorflow.python.keras.applications import ResNet50\nfrom tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.layers import Dense","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T15:52:05.835197Z","iopub.execute_input":"2025-07-17T15:52:05.835424Z","iopub.status.idle":"2025-07-17T15:52:05.843248Z","shell.execute_reply.started":"2025-07-17T15:52:05.835380Z","shell.execute_reply":"2025-07-17T15:52:05.842510Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"resnet_weights = '/kaggle/input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T15:52:05.844033Z","iopub.execute_input":"2025-07-17T15:52:05.844197Z","iopub.status.idle":"2025-07-17T15:52:05.852087Z","shell.execute_reply.started":"2025-07-17T15:52:05.844166Z","shell.execute_reply":"2025-07-17T15:52:05.851482Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(ResNet50(include_top=False, pooling=resnet_pooling, weights=resnet_weights))\n\nmodel.add(Dense(num_of_class, activation=dense_activation))\n\nmodel.layers[0].trainable=False","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T15:52:05.853170Z","iopub.execute_input":"2025-07-17T15:52:05.853380Z","iopub.status.idle":"2025-07-17T15:52:14.905246Z","shell.execute_reply.started":"2025-07-17T15:52:05.853327Z","shell.execute_reply":"2025-07-17T15:52:14.904536Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T15:52:14.906405Z","iopub.execute_input":"2025-07-17T15:52:14.906708Z","iopub.status.idle":"2025-07-17T15:52:14.916355Z","shell.execute_reply.started":"2025-07-17T15:52:14.906636Z","shell.execute_reply":"2025-07-17T15:52:14.915671Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.optimizers import Adam  \n\nadam = Adam(lr=0.001)  \nmodel.compile(optimizer=adam, loss=object_finction, metrics=metricss)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T15:53:04.561260Z","iopub.execute_input":"2025-07-17T15:53:04.561538Z","iopub.status.idle":"2025-07-17T15:53:04.662674Z","shell.execute_reply.started":"2025-07-17T15:53:04.561483Z","shell.execute_reply":"2025-07-17T15:53:04.662158Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.applications.resnet50 import preprocess_input\nfrom keras.preprocessing.image import ImageDataGenerator\n\nimage_size = image_resize\n\ndata_gen = ImageDataGenerator(preprocessing_function=preprocess_input)\n\ntrain_gen = data_gen.flow_from_directory('../input/catsdogs-trainvalid-80pc-prepd/trainvalidfull4keras/trainvalidfull4keras/train',\n                                        target_size=image_size,\n                                        batch_size=batch_size_train,\n                                        class_mode='categorical')\n\nvalid_gen = data_gen.flow_from_directory('../input/catsdogs-trainvalid-80pc-prepd/trainvalidfull4keras/trainvalidfull4keras/valid',\n                                        target_size=image_size,\n                                        batch_size=batch_size_validate,\n                                        class_mode='categorical')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T17:11:34.805999Z","iopub.execute_input":"2025-07-17T17:11:34.806284Z","iopub.status.idle":"2025-07-17T17:11:42.881020Z","shell.execute_reply.started":"2025-07-17T17:11:34.806228Z","shell.execute_reply":"2025-07-17T17:11:42.880120Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.python.keras.callbacks import EarlyStopping, ModelCheckpoint\n\ncb_early_stopper = EarlyStopping(monitor = 'val_loss', patience = early_stop)\ncb_checkpointer = ModelCheckpoint(filepath = '../working/best.hdf5', monitor = 'val_loss', save_best_only = True, mode = 'auto')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T17:44:27.713674Z","iopub.execute_input":"2025-07-17T17:44:27.713978Z","iopub.status.idle":"2025-07-17T17:44:27.717764Z","shell.execute_reply.started":"2025-07-17T17:44:27.713933Z","shell.execute_reply":"2025-07-17T17:44:27.717096Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit_generator(train_gen, \n                    steps_per_epoch=steps_epoch_train,\n                   epochs=num_of_epochs,\n                   validation_data=valid_gen,\n                   validation_steps=stpes_epoch_test,\n                   callbacks=[cb_early_stopper, cb_checkpointer])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T17:52:39.137918Z","iopub.execute_input":"2025-07-17T17:52:39.138184Z","iopub.status.idle":"2025-07-17T17:54:43.722889Z","shell.execute_reply.started":"2025-07-17T17:52:39.138133Z","shell.execute_reply":"2025-07-17T17:54:43.722298Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Make Prediction with test file","metadata":{}},{"cell_type":"code","source":"test_gen = data_gen.flow_from_directory('/kaggle/input/test-files-prepd/',\n                                       target_size=image_size,\n                                        batch_size=batch_size_test,\n                                        class_mode=None,\n                                       shuffle=False,\n                                       seed=123)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T18:05:44.029847Z","iopub.execute_input":"2025-07-17T18:05:44.030089Z","iopub.status.idle":"2025-07-17T18:06:23.567206Z","shell.execute_reply.started":"2025-07-17T18:05:44.030051Z","shell.execute_reply":"2025-07-17T18:06:23.566585Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_gen.reset()\n\npred = model.predict_generator(test_gen, steps = len(test_gen), verbose = 1)\n\npredicted_class_indices = np.argmax(pred, axis = 1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T18:09:24.938205Z","iopub.execute_input":"2025-07-17T18:09:24.938478Z","iopub.status.idle":"2025-07-17T18:13:43.611438Z","shell.execute_reply.started":"2025-07-17T18:09:24.938439Z","shell.execute_reply":"2025-07-17T18:13:43.610918Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dir = '/kaggle/input/test-files-prepd/'\n\nf, ax = plt.subplots(5, 5, figsize=(15, 15))\n\nstart = 50\nfor idx, i in enumerate(range(start, start + 25)):\n    if i >= len(test_gen.filenames):\n        break\n\n    imgBGR = cv2.imread(test_dir + test_gen.filenames[i])\n    imgRGB = cv2.cvtColor(imgBGR, cv2.COLOR_BGR2RGB)\n    \n    # a if condition else b\n    predicted_class = \"Dog\" if predicted_class_indices[i] else \"Cat\"\n\n    ax[idx // 5, idx % 5].imshow(imgRGB)\n    ax[idx // 5, idx % 5].axis('off')\n    ax[idx // 5, idx % 5].set_title(f\"Predicted: {predicted_class}\")  \n\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-17T18:25:22.613596Z","iopub.execute_input":"2025-07-17T18:25:22.613897Z","iopub.status.idle":"2025-07-17T18:25:24.220116Z","shell.execute_reply.started":"2025-07-17T18:25:22.613850Z","shell.execute_reply":"2025-07-17T18:25:24.219221Z"}},"outputs":[],"execution_count":null}]}