{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":63134,"databundleVersionId":6880857,"sourceType":"competition"}],"dockerImageVersionId":30588,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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":"2023-11-21T20:32:36.306309Z","iopub.execute_input":"2023-11-21T20:32:36.306693Z","iopub.status.idle":"2023-11-21T20:32:36.344826Z","shell.execute_reply.started":"2023-11-21T20:32:36.306663Z","shell.execute_reply":"2023-11-21T20:32:36.343646Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# required imports\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom tensorflow.keras import models, layers\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import LearningRateScheduler, EarlyStopping\nfrom sklearn.utils.class_weight import compute_class_weight\n\n\n# directories for the train and test sets\ntrain_dir = \"/kaggle/input/anyas-gojo-revival-aerospace-enigma/train\"\ntest_dir = \"/kaggle/input/anyas-gojo-revival-aerospace-enigma/test\"\n","metadata":{"execution":{"iopub.status.busy":"2023-11-21T20:32:36.346455Z","iopub.execute_input":"2023-11-21T20:32:36.346776Z","iopub.status.idle":"2023-11-21T20:32:36.352737Z","shell.execute_reply.started":"2023-11-21T20:32:36.346749Z","shell.execute_reply":"2023-11-21T20:32:36.351618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# print(train_generator.image_shape)","metadata":{"execution":{"iopub.status.busy":"2023-11-21T20:32:36.353920Z","iopub.execute_input":"2023-11-21T20:32:36.354274Z","iopub.status.idle":"2023-11-21T20:32:36.363963Z","shell.execute_reply.started":"2023-11-21T20:32:36.354241Z","shell.execute_reply":"2023-11-21T20:32:36.363142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Image dimensions and batch size\nimg_size = (128,128)\n# img_size = (256,256)\n# img_size = (150,150)\n\n# 75, 128x128, layer 128, 64\n# 74, 256x256, layer 256, 128\nbatch_size = 32\n\n# Data augmentation for the training set\ntrain_datagen = tf.keras.preprocessing.image.ImageDataGenerator(\n    rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True\n)\n\n# Data generator for the training set\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=img_size,\n    batch_size=batch_size,\n    class_mode='categorical',\n    subset='training',  # Use the training subset\n\n    shuffle=True\n)\n\n# Get class labels\nclass_labels = list(train_generator.class_indices.keys())\n\n# Get image filenames from the test directory\ntest_filenames = os.listdir(test_dir)\n\n# Check if there are images in the test directory\nif len(test_filenames) == 0:\n    raise ValueError(\"No images found in the test directory.\")\n\n# Load and preprocess the test images directly\ntest_images = []\nfor filename in test_filenames:\n    img_path = os.path.join(test_dir, filename)\n    img = load_img(img_path, target_size=img_size)\n    img_array = img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    img_array /= 255.0\n    test_images.append(img_array)\n\ntest_images = np.vstack(test_images)\n\n# Model definition\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Flatten())\n# model.add(layers.Dense(150, activation='relu'))\n# model.add(layers.Dense(75, activation='relu'))\n# model.add(layers.Dense(256, activation='relu'))\nmodel.add(layers.Dense(128, activation='relu'))\nmodel.add(layers.Dense(64, activation = 'relu'))\n# model.add(layers.Dense(32, activation = 'relu'))\nmodel.add(layers.Dense(5, activation='softmax'))  # 5 classes: commercial, glider, helicopter, mig-29, sukhoi\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Model training\nhistory = model.fit(\n    train_generator,\n    epochs=15,  # You may need to adjust the number of epochs based on performance\n)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-21T20:32:36.365658Z","iopub.execute_input":"2023-11-21T20:32:36.365938Z","iopub.status.idle":"2023-11-21T20:37:10.821976Z","shell.execute_reply.started":"2023-11-21T20:32:36.365914Z","shell.execute_reply":"2023-11-21T20:37:10.821037Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Predictions on the test set\ntest_predictions = model.predict(test_images)\n\n# Create a DataFrame to store predictions\npredictions_df = pd.DataFrame({\n    'image_path': test_filenames,\n    'class': [class_labels[np.argmax(pred)] for pred in test_predictions]\n})\n\n# Save predictions to CSV file\npredictions_df.to_csv('predictions.csv', index=False)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-21T20:37:10.823374Z","iopub.execute_input":"2023-11-21T20:37:10.823690Z","iopub.status.idle":"2023-11-21T20:37:11.083455Z","shell.execute_reply.started":"2023-11-21T20:37:10.823664Z","shell.execute_reply":"2023-11-21T20:37:11.082736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}