{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense , Dropout , Lambda, Flatten\nfrom keras.optimizers import Adam ,RMSprop\nfrom sklearn.model_selection import train_test_split\nfrom keras import  backend as K\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/train.csv')\nprint(train.shape)\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv('../input/test.csv')\nprint(test.shape)\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = (train.iloc[:,1:].values).astype('float32')\ny_train = (train.iloc[:,0].values).astype('int32')\nX_test = test.values.astype('float32')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Data Visualisation**"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.reshape(X_train.shape[0],28,28)\n\nfor i in range(6,9):\n    plt.subplot(330 + (i+1)) #plots the figure\n    plt.imshow(X_train[i], cmap=plt.get_cmap('gray'))\n    plt.title(y_train[i])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#expand 1 more dimension as 1 for color channnel gray\nX_train=X_train.reshape(X_train.shape[0],28,28,1)\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test = X_test.reshape(X_test.shape[0],28,28,1)\nX_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Preprocess the digits images\n#Feature standarisation\n#to center the data areound mean zero and unit variance","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mean_px = X_train.mean().astype(np.float32)\nstd_px = X_train.std().astype(np.float32)\n\ndef standardize(x):\n    return (x-mean_px)/std_px","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#mean_px\ny_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\ny_train = to_categorical(y_train)\nnum_classes = y_train.shape[1]\nnum_classes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.title(y_train[9])\nplt.plot(y_train[9])\nplt.xticks(range(10))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Designing Neural Network Architecture**"},{"metadata":{"trusted":true},"cell_type":"code","source":"#seed for reproducibility\nseed = 43\nnp.random.seed(seed)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers.core import Lambda, Dense, Flatten, Dropout\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import BatchNormalization, Convolution2D, MaxPooling2D","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Linear Model\n#layer different","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(Lambda(standardize, input_shape = (28,28,1))) #this layer will take given dimension as input\nmodel.add(Flatten())#mak it t 1D\nmodel.add(Dense(10,activation='softmax')) # #type of output and layer will sure that all neurons are connected to previous\nprint(\"input shape\",model.input_shape)\nprint(\"output shape\",model.output_shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.optimizers import RMSprop\nmodel.compile(optimizer=RMSprop(lr=0.001),\n             loss='categorical_crossentropy',\n             metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image\ngen = image.ImageDataGenerator()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from sklearn.model_selection import train_test_split\nX =X_train\ny = y_train\nX_train, X_val, y_train,y_val = train_test_split(X_train, y_train,\n                                                test_size=0.10, random_state=42)\nbatches = gen.flow(X_train,y_train, batch_size=64)\nval_batches = gen.flow(X_val, y_val, batch_size=64)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(generator=batches, steps_per_epoch = batches.n,\n                             epochs=3, validation_data=val_batches,\n                             validation_steps=val_batches.n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_dict=history.history\nhistory_dict.keys()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\nloss_values = history_dict[\"loss\"]\nval_loss_values=history_dict[\"val_loss\"]\nepochs=range(1,len(loss_values)+1)\nplt.plot(epochs, loss_values, 'bo')\nplt.plot(epochs, val_loss_values, 'b+')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.clf()\nacc_values=history_dict['acc']\nval_acc_values=history_dict['val_acc']\n\nplt.plot(epochs, acc_values,'bo')\nplt.plot(epochs, val_acc_values,'b+')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#fully connected model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def get_fc_model():\n#     model = Sequential([\n#         Lambda(standardize, input_shape=(28,28,1)),\n#         Flatten(),\n#         Dense(512, activation='relu'),\n#         Dense(10, activation='softmax')\n#     ])\n#     model.compile(optimizer='Adam', loss='categorical_crossentropy',\n#                  metrics=['accuracy'])\n#     return model\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# fc = get_fc_model()\n# fc.optimizer.lr=0.01","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# history=fc.fit_generator(generator=batches, steps_per_epoch=batches.n, epochs=1, \n#                     validation_data=val_batches, validation_steps=val_batches.n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Convolutional Neural Network","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.layers import Convolution2D,MaxPooling2D\ndef get_cnn_model():\n    model=Sequential([\n        Lambda(standardize, input_shape=(28,28,1)),\n        Convolution2D(32,(3,3), activation='relu'),\n        Convolution2D(32,(3,3), activation='relu'),\n        MaxPooling2D(),\n        Convolution2D(64,(3,3), activation='relu'),\n        Convolution2D(64,(3,3), activation='relu'),\n        MaxPooling2D(),\n        Flatten(),\n        Dense(512, activation='relu'),\n        Dense(10, activation='softmax')\n    ])\n    model.compile(Adam(), loss='categorical_crossentropy',\n                  metrics=['accuracy'])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = get_cnn_model()\nmodel.optimizer.lr=0.01","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(generator=batches, steps_per_epoch=batches.n,\n                             epochs=1,validation_data=val_batches,\n                             validation_steps=val_batches.n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Data Augmentation","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\n# gen =ImageDataGenerator(rotation_range=8, width_shift_range=0.08, shear_range=0.3,\n#                                height_shift_range=0.08, zoom_range=0.08)\n# batches = gen.flow(X_train, y_train, batch_size=64)\n# val_batches = gen.flow(X_val, y_val, batch_size=64)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\n# model.optimizer.lr=0.001\n# history=model.fit_generator(generator=batches, steps_per_epoch=batches.n, epochs=1, \n#                     validation_data=val_batches, validation_steps=val_batches.n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Adding Batch Normalisation","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from keras.layers.normalization import BatchNormalization\n\n# def get_bn_model():\n#     model = Sequential([\n#         Lambda(standardize, input_shape=(28,28,1)),\n#         Convolution2D(32,(3,3), activation='relu'),\n#         BatchNormalization(axis=1),\n#         Convolution2D(32,(3,3), activation='relu'),\n#         MaxPooling2D(),\n#         BatchNormalization(axis=1),\n#         Convolution2D(64,(3,3), activation='relu'),\n#         BatchNormalization(axis=1),\n#         Convolution2D(64,(3,3), activation='relu'),\n#         MaxPooling2D(),\n#         Flatten(),\n#         BatchNormalization(),\n#         Dense(512, activation='relu'),\n#         BatchNormalization(),\n#         Dense(10, activation='softmax')\n#         ])\n#     model.compile(Adam(), loss='categorical_crossentropy', metrics=['accuracy'])\n#     return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model= get_bn_model()\n# model.optimizer.lr=0.01\n# history=model.fit_generator(generator=batches, steps_per_epoch=batches.n, epochs=1, \n#                     validation_data=val_batches, validation_steps=val_batches.n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.optimizer.lr=0.01\n# gen = image.ImageDataGenerator()\n# batches = gen.flow(X, y ,batch_size=64)\n# history = model.fit_generator(generator=batches, steps_per_epoch=batches.n,\n#                              epochs=3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions=model.predict_classes(X_test, verbose=0)\nsubmissions = pd.DataFrame({\"ImageId\":list(range(1,len(predictions)+1)),\n                           \"Label\":predictions})\nsubmissions.to_csv(\"c_m.csv\", index=False, header=True)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}