{"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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:06:35.458031Z","iopub.execute_input":"2023-09-18T14:06:35.459213Z","iopub.status.idle":"2023-09-18T14:06:53.640645Z","shell.execute_reply.started":"2023-09-18T14:06:35.459176Z","shell.execute_reply":"2023-09-18T14:06:53.639427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import py7zr\nimport os\n\n# Define the paths to the .7z files\ntrain_7z_path = '/kaggle/input/cifar-10/train.7z'\ntest_7z_path = '/kaggle/input/cifar-10/test.7z'\n\n# Define the extraction paths\nextraction_path = '/kaggle/working/'\n\n# Unzip the train dataset\nwith py7zr.SevenZipFile(train_7z_path, mode='r') as z:\n    z.extractall(path=extraction_path)\n\n# Unzip the test dataset\nwith py7zr.SevenZipFile(test_7z_path, mode='r') as z:\n    z.extractall(path=extraction_path)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:07:08.794652Z","iopub.execute_input":"2023-09-18T14:07:08.795219Z","iopub.status.idle":"2023-09-18T14:27:31.897256Z","shell.execute_reply.started":"2023-09-18T14:07:08.795176Z","shell.execute_reply":"2023-09-18T14:27:31.896293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nfrom PIL import Image\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models\nfrom sklearn.preprocessing import LabelEncoder\n\n# Set the directory where your images are located\nimage_directory = '/kaggle/working/train/'\n\n# List all files in the directory\nimage_files = os.listdir(image_directory)\n\n# Initialize an empty list to store the images\nimage_list = []\n\n# Loop through the image files and load them into the list\nfor filename in image_files:\n    # Check if the file is a PNG image\n    if filename.endswith('.png'):\n        img = Image.open(os.path.join(image_directory, filename))\n        \n        # Ensure the image is of the correct size (32x32)\n        img = img.resize((32, 32))\n        \n        # Convert the image to a NumPy array\n        img_array = np.array(img)\n        \n        # Append the image array to the list\n        image_list.append(img_array)\n\n# Convert the list of images to a NumPy ndarray\ntrain_images = np.array(image_list)\n\ntrain_labels = pd.read_csv('/kaggle/input/cifar-10/trainLabels.csv')\n\n# Set the directory where your test images are located\ntest_image_directory = '/kaggle/working/test/'\n\n# List all files in the directory\ntest_image_files = os.listdir(test_image_directory)\n\n# Initialize an empty list to store the test images\ntest_image_list = []\n\n# Loop through the test image files and load them into the list\nfor filename in image_files:\n    # Check if the file is a PNG image\n    if filename.endswith('.png'):\n        img = Image.open(os.path.join(test_image_directory, filename))\n        \n        # Ensure the image is of the correct size (32x32)\n        img = img.resize((32, 32))\n        \n        # Convert the image to a NumPy array\n        img_array = np.array(img)\n        \n        # Append the test image array to the list\n        test_image_list.append(img_array)\n\n# Convert the list of test images to a NumPy ndarray\ntest_images = np.array(test_image_list)\n\n# Normalize pixel values to be between 0 and 1\ntrain_images, test_images = train_images / 255.0, test_images / 255.0\n\n# Detect GPUs, if available\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n    try:\n        # Currently, memory growth needs to be the same across GPUs\n        for gpu in gpus:\n            tf.config.experimental.set_memory_growth(gpu, True)\n        logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n        print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n    except RuntimeError as e:\n        print(e)\n\n# Create and compile the model\ndef create_model():\n    model = models.Sequential([\n        layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),\n        layers.MaxPooling2D((2, 2)),\n        layers.Conv2D(64, (3, 3), activation='relu'),\n        layers.MaxPooling2D((2, 2)),\n        layers.Conv2D(64, (3, 3), activation='relu'),\n        layers.Flatten(),\n        layers.Dense(64, activation='relu'),\n        layers.Dense(10)\n    ])\n    return model\n\n# Assuming train_labels contain string labels like 'frog', 'cat', 'dog'\nlabel_encoder = LabelEncoder()\ntrain_labels_encoded = label_encoder.fit_transform(train_labels['label'])  # Assuming 'label' is the column with labels\n\n# Convert the data type of labels to int32\ntrain_labels_encoded = train_labels_encoded.astype(np.int32)\n\n# Ensure train_images contains image data in np.float32 format\ntrain_images = train_images.astype(np.float32)\n\n# Define the MirroredStrategy for two GPUs\nstrategy = tf.distribute.MirroredStrategy(devices=['/GPU:0', '/GPU:1'])\n\nprint(\"Number of devices: {}\".format(strategy.num_replicas_in_sync))\n\n# Create and compile the model within the MirroredStrategy scope\nwith strategy.scope():\n    model = create_model()\n    model.compile(optimizer='adam',\n                  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n                  metrics=['accuracy'])\n\n# Train the model using MirroredStrategy\nhistory = model.fit(train_images, train_labels_encoded, epochs=20, validation_split=0.2)\n\n# Save the model\nmodel.save('/kaggle/working/my_model.h5')\n","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:32:00.005517Z","iopub.execute_input":"2023-09-18T14:32:00.005870Z","iopub.status.idle":"2023-09-18T14:38:09.425292Z","shell.execute_reply.started":"2023-09-18T14:32:00.005841Z","shell.execute_reply":"2023-09-18T14:38:09.424291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(test_images.shape)\npredictions = model.predict(test_images)","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:42:25.906023Z","iopub.execute_input":"2023-09-18T14:42:25.906458Z","iopub.status.idle":"2023-09-18T14:42:38.137263Z","shell.execute_reply.started":"2023-09-18T14:42:25.906422Z","shell.execute_reply":"2023-09-18T14:42:38.136221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a DataFrame for the submission\nsubmission_df = pd.DataFrame({\n    'id': range(1, len(test_images) + 1),\n    'label': np.argmax(predictions, axis=1)\n})\n\n# Decode the labels\nclass_labels = label_encoder.inverse_transform(submission_df['label'])\n\n# Update the 'label' column with class labels\nsubmission_df['label'] = class_labels\n\n# Save the submission file with class labels\nsubmission_df.to_csv('/kaggle/working/submission.csv', index=False)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:43:11.505380Z","iopub.execute_input":"2023-09-18T14:43:11.505936Z","iopub.status.idle":"2023-09-18T14:43:11.721237Z","shell.execute_reply.started":"2023-09-18T14:43:11.505895Z","shell.execute_reply":"2023-09-18T14:43:11.720181Z"},"trusted":true},"execution_count":null,"outputs":[]}]}