{"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-15T20:35:44.100637Z","iopub.execute_input":"2023-09-15T20:35:44.101348Z","iopub.status.idle":"2023-09-15T20:35:53.190553Z","shell.execute_reply.started":"2023-09-15T20:35:44.101314Z","shell.execute_reply":"2023-09-15T20:35:53.189485Z"},"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-15T20:35:54.868921Z","iopub.execute_input":"2023-09-15T20:35:54.869362Z","iopub.status.idle":"2023-09-15T20:58:11.326369Z","shell.execute_reply.started":"2023-09-15T20:35:54.869322Z","shell.execute_reply":"2023-09-15T20:58:11.325392Z"},"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\n\nfrom sklearn.preprocessing import LabelEncoder\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')\nprint(train_labels)\n\n# Set the directory where your images are located\nimage_directory = '/kaggle/working/test/'\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\ntest_images = np.array(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 TPU, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\n\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\nprint(train_images.shape)\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# Create and compile the model within the TPU strategy scope\nwith strategy.scope():\n    model = create_model()  # Replace with your model creation function\n    model.compile(optimizer='adam',\n                  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n                  metrics=['accuracy'])\n\n# Train the model\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-15T21:44:32.089479Z","iopub.execute_input":"2023-09-15T21:44:32.090290Z","iopub.status.idle":"2023-09-15T21:49:49.444626Z","shell.execute_reply.started":"2023-09-15T21:44:32.090251Z","shell.execute_reply":"2023-09-15T21:49:49.443288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(test_images)","metadata":{"execution":{"iopub.status.busy":"2023-09-15T21:49:59.958603Z","iopub.execute_input":"2023-09-15T21:49:59.959055Z","iopub.status.idle":"2023-09-15T21:51:08.465528Z","shell.execute_reply.started":"2023-09-15T21:49:59.959023Z","shell.execute_reply":"2023-09-15T21:51:08.464052Z"},"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-15T21:27:01.892388Z","iopub.execute_input":"2023-09-15T21:27:01.893869Z","iopub.status.idle":"2023-09-15T21:27:02.384326Z","shell.execute_reply.started":"2023-09-15T21:27:01.893823Z","shell.execute_reply":"2023-09-15T21:27:02.383077Z"},"trusted":true},"execution_count":null,"outputs":[]}]}