{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"pip install py7zr","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"#Unzip zipped data set\nimport py7zr\n\nwith py7zr.SevenZipFile('/kaggle/input/cifar-10/train.7z', mode='r') as z:\n    z.extractall(path='/kaggle/working')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\n\ndf = pd.read_csv('/kaggle/input/cifar-10/trainLabels.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classes = {\"airplane\":1,\"automobile\":2,\"bird\":3,\"cat\":4,\"deer\":5,\"dog\":6,\"frog\":7,\"horse\":8,\"ship\":9,\"truck\":10}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# TensorFlow and tf.keras\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D, BatchNormalization, Activation, Conv2DTranspose\nfrom keras.regularizers import l2\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport os\ndirectory = '/kaggle/working/train'\ntrain_images = np.zeros((50000,32,32,3))\ntrain_labels = np.zeros((50000,1))\niter = 0\nfor filename in os.listdir(directory):\n    img = image.load_img(os.path.join(directory,filename), target_size=(32, 32,3))\n    x = image.img_to_array(img)\n    name = filename.split('.')[0]\n    train_images[iter] = x\n    keys = df[df.id == int(name)].label.to_string().split(' ')[-1]\n    train_labels[iter] = classes[keys]\n    iter = iter + 1\n    \ntrain_images.shape\ntrain_labels.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images = train_images.reshape([-1, 32, 32, 3]).astype(np.float32) / 255\ntrain_labels = train_labels.astype(np.int32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images=train_images.repeat(3,0)\ntrain_labels=train_labels.repeat(3,0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.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    plt.imshow(train_images[i])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator( width_shift_range=0.1,height_shift_range=0.1, horizontal_flip=True,rotation_range=10, validation_split=0.05)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_labels_new = np.squeeze(train_labels)\ntrain_labels_new = train_labels_new -1\ntrain_labels_new = keras.utils.to_categorical(train_labels_new, 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# The Model\nmymodel = Sequential([\n   Conv2D(32, 3, padding='same', input_shape = (32,32,3)),\n    Activation('relu'),\n    BatchNormalization(),\n    Conv2D(64, 3, padding='same'),\n    Activation('relu'),\n    BatchNormalization(),\n    Conv2D(64, 3),\n    Activation('relu'),\n    MaxPooling2D(pool_size=(2, 2), strides=(2,2)),\n    Dropout(0.25),\n    Conv2D(128, 5, padding='same'),\n    Activation('relu'),\n    BatchNormalization(),\n    Conv2D(128, 5, padding = 'same'),\n    Activation('relu'),\n    MaxPooling2D(pool_size=(2, 2), strides=(2,2)),\n    Dropout(0.25),\n    Conv2D(256, 5, padding='same', name = 'conv_last'),\n    Activation('relu'),\n    BatchNormalization(),\n    MaxPooling2D(pool_size=(2, 2), strides=(2,2)),\n    Dropout(0.25),\n    Conv2D(512, 2),\n    Flatten(),\n    Dense(256, activation = 'relu',kernel_regularizer=l2(0.01)),\n    Dropout(0.25),\n    Dense(512, activation = 'relu',kernel_regularizer=l2(0.01)),\n    Dropout(0.25),\n    Dense(1024, activation = 'relu',kernel_regularizer=l2(0.01)),\n    BatchNormalization(),\n    Dense(10, activation = 'softmax')\n])\nmymodel.compile(optimizer='adam',\n              loss='kullback_leibler_divergence',#loss='sparse_categorical_crossentropy', \n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = mymodel.fit_generator(datagen.flow(train_images, train_labels_new,batch_size=128), epochs=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"rm -r /kaggle/working/train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with py7zr.SevenZipFile('/kaggle/input/cifar-10/test.7z', mode='r') as z:\n    z.extractall(path='/kaggle/working')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class_dict = {0:\"airplane\",1:\"automobile\",2:\"bird\",3:\"cat\",4:\"deer\",5:\"dog\",6:\"frog\",7:\"horse\",8:\"ship\",9:\"truck\"}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"import csv\ndirectory = '/kaggle/working/test'\n\nwith open('mySubmision.csv', 'w', newline='') as op:\n    myWritter = csv.writer(op)\n    myWritter.writerow(['id','label'])\n    for filename in os.listdir(directory):\n        img = image.load_img(os.path.join(directory,filename), target_size=(32, 32, 3))\n        x = image.img_to_array(img)\n        x = np.expand_dims(x, axis=0)\n        x = x/255.0\n        id = filename.split('.')[0]\n        prediction = np.argmax(mymodel.predict(x))\n        myWritter.writerow([id,class_dict[prediction]])\n\n    \nprint(\"Done\")","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":1}