{"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":"import numpy as np \nimport pandas as pd \nimport os\nfrom tensorflow import keras\nimport tensorflow as tf\nfrom keras import Sequential\nfrom keras.layers import Dense, Conv2D, MaxPooling2D, Activation, BatchNormalization, Flatten, Dropout\nfrom keras.utils.np_utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\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))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-09-19T11:10:28.546359Z","iopub.execute_input":"2023-09-19T11:10:28.547174Z","iopub.status.idle":"2023-09-19T11:10:37.092731Z","shell.execute_reply.started":"2023-09-19T11:10:28.547138Z","shell.execute_reply":"2023-09-19T11:10:37.091436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:10:37.095212Z","iopub.execute_input":"2023-09-19T11:10:37.096408Z","iopub.status.idle":"2023-09-19T11:10:52.713495Z","shell.execute_reply.started":"2023-09-19T11:10:37.096367Z","shell.execute_reply":"2023-09-19T11:10:52.712183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from py7zr import unpack_7zarchive\nimport shutil\n\nshutil.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\")\n\nclasses = train_labels['label'].unique()\nprint(classes)","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:10:52.716667Z","iopub.execute_input":"2023-09-19T11:10:52.717378Z","iopub.status.idle":"2023-09-19T11:11:52.761536Z","shell.execute_reply.started":"2023-09-19T11:10:52.717338Z","shell.execute_reply":"2023-09-19T11:11:52.759177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if 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)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:11:52.764836Z","iopub.execute_input":"2023-09-19T11:11:52.765233Z","iopub.status.idle":"2023-09-19T11:11:59.103307Z","shell.execute_reply.started":"2023-09-19T11:11:52.765198Z","shell.execute_reply":"2023-09-19T11:11:59.102339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /kaggle/temp/valid\n!ls /kaggle/temp/train","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:11:59.104741Z","iopub.execute_input":"2023-09-19T11:11:59.105128Z","iopub.status.idle":"2023-09-19T11:12:01.098822Z","shell.execute_reply.started":"2023-09-19T11:11:59.105094Z","shell.execute_reply":"2023-09-19T11:12:01.097479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32, (3,3), padding='same', input_shape=(32,32,3)))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(32, (3,3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(2*32, (3,3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(2*32, (3,3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.3))\n\nmodel.add(Conv2D(4*32, (3,3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(4*32, (3,3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.4))\n\nmodel.add(Flatten())\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:12:01.100434Z","iopub.execute_input":"2023-09-19T11:12:01.101289Z","iopub.status.idle":"2023-09-19T11:12:05.401477Z","shell.execute_reply.started":"2023-09-19T11:12:01.101250Z","shell.execute_reply":"2023-09-19T11:12:05.400736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.optimizers import Adam\nopt = Adam(learning_rate=1.0e-4)\n\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:12:05.402579Z","iopub.execute_input":"2023-09-19T11:12:05.402928Z","iopub.status.idle":"2023-09-19T11:12:05.424229Z","shell.execute_reply.started":"2023-09-19T11:12:05.402894Z","shell.execute_reply":"2023-09-19T11:12:05.423505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer= opt , metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:12:05.425424Z","iopub.execute_input":"2023-09-19T11:12:05.425761Z","iopub.status.idle":"2023-09-19T11:12:05.451567Z","shell.execute_reply.started":"2023-09-19T11:12:05.425729Z","shell.execute_reply":"2023-09-19T11:12:05.450664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_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=128)\nvalid_generator = valid_datagen.flow_from_directory(directory='/kaggle/temp/valid/', shuffle=True, target_size=(32,32),batch_size=128)","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:12:05.453112Z","iopub.execute_input":"2023-09-19T11:12:05.453839Z","iopub.status.idle":"2023-09-19T11:12:06.835411Z","shell.execute_reply.started":"2023-09-19T11:12:05.453807Z","shell.execute_reply":"2023-09-19T11:12:06.834424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.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)","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:12:06.836912Z","iopub.execute_input":"2023-09-19T11:12:06.837263Z","iopub.status.idle":"2023-09-19T11:37:39.738456Z","shell.execute_reply.started":"2023-09-19T11:12:06.837231Z","shell.execute_reply":"2023-09-19T11:37:39.737313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unpack_archive('/kaggle/input/cifar-10/test.7z','/kaggle/temp/test')\n\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:37:39.743096Z","iopub.execute_input":"2023-09-19T11:37:39.743406Z","iopub.status.idle":"2023-09-19T11:57:13.612695Z","shell.execute_reply.started":"2023-09-19T11:37:39.743378Z","shell.execute_reply":"2023-09-19T11:57:13.611558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unregister_unpack_format('7zip')","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:57:13.614527Z","iopub.execute_input":"2023-09-19T11:57:13.615227Z","iopub.status.idle":"2023-09-19T11:57:13.622423Z","shell.execute_reply.started":"2023-09-19T11:57:13.615190Z","shell.execute_reply":"2023-09-19T11:57:13.621546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\n\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-19T11:57:13.623934Z","iopub.execute_input":"2023-09-19T11:57:13.624580Z","iopub.status.idle":"2023-09-19T11:57:22.350246Z","shell.execute_reply.started":"2023-09-19T11:57:13.624545Z","shell.execute_reply":"2023-09-19T11:57:22.349040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_gen.reset()\npredictions_vecs = model.predict(test_gen)\n\npredictions_final = np.argmax(predictions_vecs, axis=1)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:57:22.355908Z","iopub.execute_input":"2023-09-19T11:57:22.358575Z","iopub.status.idle":"2023-09-19T11:59:22.213557Z","shell.execute_reply.started":"2023-09-19T11:57:22.358533Z","shell.execute_reply":"2023-09-19T11:59:22.212495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(type(train_generator.class_indices))\nprint(train_generator.class_indices)\n\nclasses = {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\n\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:59:22.214911Z","iopub.execute_input":"2023-09-19T11:59:22.215272Z","iopub.status.idle":"2023-09-19T11:59:22.775374Z","shell.execute_reply.started":"2023-09-19T11:59:22.215236Z","shell.execute_reply":"2023-09-19T11:59:22.774284Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv('../input/cifar-10/sampleSubmission.csv',header='infer')\nsub.info()","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:59:22.776971Z","iopub.execute_input":"2023-09-19T11:59:22.777671Z","iopub.status.idle":"2023-09-19T11:59:22.938724Z","shell.execute_reply.started":"2023-09-19T11:59:22.777636Z","shell.execute_reply":"2023-09-19T11:59:22.937789Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['label'] = predicted_classes_final\nsub.to_csv('submission.csv',index=False)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:59:22.940184Z","iopub.execute_input":"2023-09-19T11:59:22.940552Z","iopub.status.idle":"2023-09-19T11:59:23.612842Z","shell.execute_reply.started":"2023-09-19T11:59:22.940503Z","shell.execute_reply":"2023-09-19T11:59:23.611816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('model.h5')","metadata":{"execution":{"iopub.status.busy":"2023-09-19T11:59:23.614475Z","iopub.execute_input":"2023-09-19T11:59:23.614877Z","iopub.status.idle":"2023-09-19T11:59:23.730717Z","shell.execute_reply.started":"2023-09-19T11:59:23.614841Z","shell.execute_reply":"2023-09-19T11:59:23.729694Z"},"trusted":true},"execution_count":null,"outputs":[]}]}