{"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":"2023-09-22T18:57:16.701205Z","iopub.execute_input":"2023-09-22T18:57:16.701731Z","iopub.status.idle":"2023-09-22T18:57:16.713815Z","shell.execute_reply.started":"2023-09-22T18:57:16.701689Z","shell.execute_reply":"2023-09-22T18:57:16.712532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Kaggle Environment - Assignment 3 Deep Learning**","metadata":{}},{"cell_type":"markdown","source":"Load Libraries","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.keras.regularizers import l2\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom tensorflow.keras import datasets\nfrom keras.utils import to_categorical\nimport numpy as np\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn')\nimport seaborn as sns\nsns.set_style('darkgrid')\n","metadata":{"execution":{"iopub.status.busy":"2023-09-22T18:57:20.209057Z","iopub.execute_input":"2023-09-22T18:57:20.210244Z","iopub.status.idle":"2023-09-22T18:57:20.223621Z","shell.execute_reply.started":"2023-09-22T18:57:20.210194Z","shell.execute_reply":"2023-09-22T18:57:20.222318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"check if using GPU","metadata":{}},{"cell_type":"code","source":"print(\"TensorFlow version:\", tf.__version__)\nif tf.config.list_physical_devices('GPU'):\n    print(\"TensorFlow is using GPU!\")\nelse:\n    print(\"TensorFlow is not using GPU.\")","metadata":{"execution":{"iopub.status.busy":"2023-09-22T17:27:22.223814Z","iopub.execute_input":"2023-09-22T17:27:22.224480Z","iopub.status.idle":"2023-09-22T17:27:22.624136Z","shell.execute_reply.started":"2023-09-22T17:27:22.224443Z","shell.execute_reply":"2023-09-22T17:27:22.622886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load training data\n(training_images, training_labels), (testing_images, testing_labels) = datasets.cifar10.load_data()\n# One-hot encode the labels\ntraining_labels_one_hot = to_categorical(training_labels, num_classes=10)\ntesting_labels_one_hot = to_categorical(testing_labels, num_classes=10)\nprint('x_train shape => ' , training_images.shape)\nprint('x_test shape => ' , testing_images.shape)\nprint('training_labels shape => ' , training_labels.shape)\nprint('testing_labels shape => ' , testing_labels.shape)\ntraining_images, testing_images = training_images / 255, testing_images / 255\n\n# Load test data (For submission to check on kaggle dataset)\ntest_files = ['/kaggle/input/cifar-10/test/' + str(i) + '.png' for i in range(1, 300001)]","metadata":{"execution":{"iopub.status.busy":"2023-09-22T17:27:23.784561Z","iopub.execute_input":"2023-09-22T17:27:23.785133Z","iopub.status.idle":"2023-09-22T17:27:30.418275Z","shell.execute_reply.started":"2023-09-22T17:27:23.785098Z","shell.execute_reply":"2023-09-22T17:27:30.417223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**ConvNet Model**","metadata":{}},{"cell_type":"code","source":"def create_model():\n    model = tf.keras.models.Sequential([\n        tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(32, 32, 3)),\n        tf.keras.layers.MaxPooling2D(2, 2),\n        tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n        tf.keras.layers.MaxPooling2D(2,2),\n        tf.keras.layers.Flatten(),\n        tf.keras.layers.Dense(512, activation='relu'),\n        tf.keras.layers.Dense(10, activation='softmax')\n    ])\n    return model\n#We used 2D convolutional layer, with 32 filters and size of each filter is 3x3\n#input shape is 32x32x3 is because its 32x32 pixel image of rgb","metadata":{"execution":{"iopub.status.busy":"2023-09-22T17:27:52.801434Z","iopub.execute_input":"2023-09-22T17:27:52.801835Z","iopub.status.idle":"2023-09-22T17:27:52.808959Z","shell.execute_reply.started":"2023-09-22T17:27:52.801803Z","shell.execute_reply":"2023-09-22T17:27:52.807624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Enable GPU\nstrategy = tf.distribute.MirroredStrategy()\nwith strategy.scope():\n    model = create_model()\n    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-09-22T17:27:56.079925Z","iopub.execute_input":"2023-09-22T17:27:56.080316Z","iopub.status.idle":"2023-09-22T17:28:00.725804Z","shell.execute_reply.started":"2023-09-22T17:27:56.080286Z","shell.execute_reply":"2023-09-22T17:28:00.724710Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Train the model\nmodel.fit(training_images, training_labels_one_hot, epochs=10, batch_size=64, validation_data=(testing_images, testing_labels_one_hot))","metadata":{"execution":{"iopub.status.busy":"2023-09-22T17:28:18.325637Z","iopub.execute_input":"2023-09-22T17:28:18.326024Z","iopub.status.idle":"2023-09-22T17:30:14.642998Z","shell.execute_reply.started":"2023-09-22T17:28:18.325994Z","shell.execute_reply":"2023-09-22T17:30:14.641950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#save model for future use\nmodel.save(\"cifar-gpu-model.h5\")","metadata":{"execution":{"iopub.status.busy":"2023-09-22T18:57:25.479311Z","iopub.execute_input":"2023-09-22T18:57:25.479812Z","iopub.status.idle":"2023-09-22T18:57:25.591372Z","shell.execute_reply.started":"2023-09-22T18:57:25.479773Z","shell.execute_reply":"2023-09-22T18:57:25.590122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Test model on kaggle test data**","metadata":{}},{"cell_type":"code","source":"import glob\nif not os.path.exists('test') or len(glob.glob(f'test/test/*')) != 300000:\n    !pip install py7zr\n\n    import py7zr\n\n    with py7zr.SevenZipFile('/kaggle/input/cifar-10/test.7z', 'r') as archive:\n        archive.extractall(path='test')","metadata":{"execution":{"iopub.status.busy":"2023-09-22T17:30:29.767771Z","iopub.execute_input":"2023-09-22T17:30:29.768174Z","iopub.status.idle":"2023-09-22T17:50:28.963617Z","shell.execute_reply.started":"2023-09-22T17:30:29.768141Z","shell.execute_reply":"2023-09-22T17:50:28.962373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import load_img, img_to_array\nimport os\ndef load_images_from_folder(folder_path, target_size=(32, 32), limit=None):\n    \"\"\"\n    Load a limited number of images from a specified folder into a numpy array.\n    \n    Parameters:\n    - folder_path: path to the folder containing images.\n    - target_size: tuple specifying the size to resize images to.\n    - limit: number of images to load. If None, all images are loaded.\n    \n    Returns:\n    - A numpy array containing the loaded images from the folder.\n    \"\"\"\n    image_files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]\n    \n    # If limit is specified, take only the first 'limit' files\n    if limit:\n        image_files = image_files[:limit]\n        \n    images = [img_to_array(load_img(os.path.join(folder_path, f), target_size=target_size)) for f in image_files]\n    return np.array(images)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T18:57:42.754822Z","iopub.execute_input":"2023-09-22T18:57:42.755292Z","iopub.status.idle":"2023-09-22T18:57:42.764802Z","shell.execute_reply.started":"2023-09-22T18:57:42.755258Z","shell.execute_reply":"2023-09-22T18:57:42.763578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Load saved model and then runu predictions on kaggle test data**","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\nmodel = load_model(\"cifar-gpu-model.h5\")","metadata":{"execution":{"iopub.status.busy":"2023-09-22T18:58:56.699048Z","iopub.execute_input":"2023-09-22T18:58:56.699577Z","iopub.status.idle":"2023-09-22T18:58:56.857694Z","shell.execute_reply.started":"2023-09-22T18:58:56.699540Z","shell.execute_reply":"2023-09-22T18:58:56.856461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file_names = os.listdir('test/test')","metadata":{"execution":{"iopub.status.busy":"2023-09-22T19:00:26.866277Z","iopub.execute_input":"2023-09-22T19:00:26.866910Z","iopub.status.idle":"2023-09-22T19:00:27.152228Z","shell.execute_reply.started":"2023-09-22T19:00:26.866843Z","shell.execute_reply":"2023-09-22T19:00:27.151066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load and preprocess the images\nfrom tensorflow.keras.preprocessing.image import load_img\nfolder_path = 'test/test'\nkaggle_testing_dataset = load_images_from_folder(folder_path, limit=50)\nkaggle_test_dataset_normalized = kaggle_testing_dataset / 255.0\n\n# Make predictions\npredictions = model.predict(kaggle_test_dataset_normalized)\n\n# Visualize some test images with their predicted labels\nclass_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\nplt.figure(figsize=(10, 10))\nfor i in range(25):\n    plt.subplot(5, 5, i+1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    \n    plt.imshow(load_img('test/test/'+file_names[i]), cmap=plt.cm.binary)\n    plt.xlabel(class_names[np.argmax(predictions[i])])\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-22T19:03:31.739702Z","iopub.execute_input":"2023-09-22T19:03:31.740159Z","iopub.status.idle":"2023-09-22T19:03:36.186623Z","shell.execute_reply.started":"2023-09-22T19:03:31.740120Z","shell.execute_reply":"2023-09-22T19:03:36.183613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a submission file\nsubmission = pd.DataFrame({'Label': [class_names[i] for i in predictions.argmax(axis=1)]})\nsubmission['id'] = submission.index\n\nsubmission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-09-22T19:05:27.286696Z","iopub.execute_input":"2023-09-22T19:05:27.288269Z","iopub.status.idle":"2023-09-22T19:05:27.321452Z","shell.execute_reply.started":"2023-09-22T19:05:27.288218Z","shell.execute_reply":"2023-09-22T19:05:27.319801Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}