{"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":"markdown","source":"# Assignment 03 trained convnet on CIFAR data using GPU T4 x2\n# Name: Mohammed Bilal Shakeel\n# ID:- 210051726","metadata":{}},{"cell_type":"code","source":"# importing necessary libraries\n!pip install py7zr\n!pip install keras\n!pip install seaborn\nfrom tensorflow import keras \nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nimport os\nimport numpy as np\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix, classification_report\nimport itertools\nimport os\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.layers import Dense, Dropout, Activation,Flatten,Conv2D, MaxPooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.datasets import cifar10 \nimport tensorflow as tf\nfrom tensorflow.keras import layers, models\nfrom py7zr import unpack_7zarchive\nimport shutil\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"execution":{"iopub.status.busy":"2023-09-18T20:27:33.117416Z","iopub.execute_input":"2023-09-18T20:27:33.118121Z","iopub.status.idle":"2023-09-18T20:28:13.810145Z","shell.execute_reply.started":"2023-09-18T20:27:33.118084Z","shell.execute_reply":"2023-09-18T20:28:13.808891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.register_unpack_format('7zip',['.7z'],unpack_7zarchive)\nshutil.unpack_archive('../input/cifar-10/train.7z', '/kaggle/temp/')\ntrain_labels = pd.read_csv(\"../input/cifar-10/trainLabels.csv\", header=\"infer\")\nclasses = train_labels['label'].unique()\nif not os.path.exists(\"/kaggle/temp/valid\"):\n    os.mkdir(\"/kaggle/temp/valid\")\n    \nparent_path_train = \"/kaggle/temp/train\"\nparent_path_valid = \"/kaggle/temp/valid\"\nparent_path_test = \"/kaggle/temp/test\"\n\nfor class1 in classes:\n    path_train = os.path.join(parent_path_train,class1)\n    if not os.path.exists(path_train):\n        os.mkdir(path_train)\n    path_valid = os.path.join(parent_path_valid,class1)\n    if not os.path.exists(path_valid):\n        os.mkdir(path_valid)\n        \nfor (int_ind,row) in train_labels.iterrows():\n    id = str(row[\"id\"])+\".png\"\n    source_path = os.path.join(parent_path_train,id)\n    \n    p=np.random.random()\n    if p<=0.8:\n        target_path = os.path.join(parent_path_train,row[\"label\"],id)\n        os.replace(source_path, target_path)\n    else:\n        target_path = os.path.join(parent_path_valid,row[\"label\"],id)\n        os.replace(source_path, target_path)","metadata":{"execution":{"iopub.status.busy":"2023-09-18T20:28:31.354888Z","iopub.execute_input":"2023-09-18T20:28:31.355365Z","iopub.status.idle":"2023-09-18T20:29:38.371988Z","shell.execute_reply.started":"2023-09-18T20:28:31.355326Z","shell.execute_reply":"2023-09-18T20:29:38.369711Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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# 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.CategoricalCrossentropy(from_logits=True),\n                  metrics=['accuracy'])\n    \ntrain_datagen = ImageDataGenerator(featurewise_center=False,\n                             samplewise_center=False,\n                             featurewise_std_normalization=False,\n                             samplewise_std_normalization=False,\n                             zca_whitening=False,\n                             rotation_range=10,\n                             zoom_range=0.1,\n                             width_shift_range=0.1,\n                             height_shift_range=0.1,\n                             horizontal_flip=False,\n                             vertical_flip=False,\n                             rescale=1./255)\nvalid_datagen = ImageDataGenerator()\n\ntrain_generator = train_datagen.flow_from_directory(directory='/kaggle/temp/train/', shuffle=True, target_size=(32,32),batch_size=256)\nvalid_generator = valid_datagen.flow_from_directory(directory='/kaggle/temp/valid/', shuffle=True, target_size=(32,32),batch_size=256)\n\n# Train the model using MirroredStrategy\nmodel.fit(train_generator,epochs=20, validation_data=valid_generator,steps_per_epoch=train_generator.n//train_generator.batch_size,\n         validation_steps= valid_generator.n//valid_generator.batch_size,workers=8,use_multiprocessing=True)\n\n# Save the model\nmodel.save('/kaggle/working/gpu_trained_model.h5')\n","metadata":{"execution":{"iopub.status.busy":"2023-09-18T20:29:38.374462Z","iopub.execute_input":"2023-09-18T20:29:38.375320Z","iopub.status.idle":"2023-09-18T20:46:52.578907Z","shell.execute_reply.started":"2023-09-18T20:29:38.375281Z","shell.execute_reply":"2023-09-18T20:46:52.577650Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unpack_archive('/kaggle/input/cifar-10/test.7z','/kaggle/temp/test')\nshutil.unregister_unpack_format('7zip')","metadata":{"execution":{"iopub.status.busy":"2023-09-18T20:48:46.638720Z","iopub.execute_input":"2023-09-18T20:48:46.639193Z","iopub.status.idle":"2023-09-18T21:08:46.442818Z","shell.execute_reply.started":"2023-09-18T20:48:46.639158Z","shell.execute_reply":"2023-09-18T21:08:46.441543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\ntest_gen = test_datagen.flow_from_directory(directory='/kaggle/temp/test',target_size=(32,32),batch_size=64,class_mode=None,shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2023-09-18T21:08:46.445320Z","iopub.execute_input":"2023-09-18T21:08:46.445817Z","iopub.status.idle":"2023-09-18T21:08:55.739740Z","shell.execute_reply.started":"2023-09-18T21:08:46.445778Z","shell.execute_reply":"2023-09-18T21:08:55.738715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_gen.reset()\npredictions_vecs = model.predict(test_gen)\npredictions_final = np.argmax(predictions_vecs, axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-09-18T21:08:55.741325Z","iopub.execute_input":"2023-09-18T21:08:55.741718Z","iopub.status.idle":"2023-09-18T21:11:13.809900Z","shell.execute_reply.started":"2023-09-18T21:08:55.741681Z","shell.execute_reply":"2023-09-18T21:11:13.808556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes = {value:key for (key,value) in train_generator.class_indices.items()}\nprint(classes)\n\npredicted_classes=np.empty(shape=300000,dtype=np.dtype('U20'))\n\nind=0\nfor i in predictions_final.tolist():\n    predicted_classes[ind]=classes[i]\n    ind=ind+1\n    \nfilenames_wo_ext = []\nfor fname in test_gen.filenames:\n    filenames_wo_ext.append(int(fname.split(sep=\"/\")[1].split(sep=\".\")[0])-1)\n\npredicted_classes_final = np.empty(shape=300000,dtype=np.dtype('U20'))\npredicted_classes_final[filenames_wo_ext]=predicted_classes","metadata":{"execution":{"iopub.status.busy":"2023-09-18T21:11:13.812892Z","iopub.execute_input":"2023-09-18T21:11:13.813329Z","iopub.status.idle":"2023-09-18T21:11:14.394036Z","shell.execute_reply.started":"2023-09-18T21:11:13.813287Z","shell.execute_reply":"2023-09-18T21:11:14.392934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv('../input/cifar-10/sampleSubmission.csv',header='infer')\nsub.info()\nsub['label'] = predicted_classes_final\nsub.to_csv('gpu_trained_submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2023-09-18T21:11:14.395860Z","iopub.execute_input":"2023-09-18T21:11:14.396681Z","iopub.status.idle":"2023-09-18T21:11:15.280969Z","shell.execute_reply.started":"2023-09-18T21:11:14.396639Z","shell.execute_reply":"2023-09-18T21:11:15.280046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}