{"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\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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/digit-recognizer/train.csv')\ntest = pd.read_csv('../input/digit-recognizer/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train.shape)\nntrain = train.shape[0]\nprint(test.shape)\nntest = train.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train.dtypes[:5])\nprint(test.dtypes[:5])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ytrain = train['label']\nprint('Shape of ytrain', ytrain.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xtrain = train.drop('label',axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from math import sqrt\ndim = int(sqrt(xtrain.shape[1]))\nprint('The images are {}x{} squares.'.format(dim, dim))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('shape of xtrain:',xtrain.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ytrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns\nsns.set(style='white',context='notebook',palette='deep')\nsns.countplot(ytrain)\nprint(ytrain.shape)\nprint(type(ytrain))\nvals_class = ytrain.value_counts()\nprint(vals_class)\ncls_mean = np.mean(vals_class)\ncls_std = np.std(vals_class, ddof=1)\nprint('The mean amount of elements per class is', cls_mean)\nprint('The Standard deviation in the element per class distribution is', cls_std)\n\nif cls_std > cls_mean * (0.687/2):\n    print('The standard deviation is high')\n    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def check_nan(df):\n    print(df.isnull().any().describe())\n    print('There are missing values' if df.isnull().any().any() else \"There are no missing values\")\n    \n    if df.isnull().any().any():\n        print(df.isnull().sum(axis=0))\n    \n    print()\n    \ncheck_nan(xtrain)\ncheck_nan(test)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n%matplotlib inline\nxtrain_vis = xtrain.values.reshape(ntrain, dim, dim)\n\nfor i in range(0,9):\n    plt.subplot(330 + (i+1))\n    plt.imshow(xtrain_vis[1], cmap = plt.get_cmap('gray'))\n    plt.title(ytrain[i]);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xtrain = xtrain/255.0\ntest = test/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def df_reshape(df):\n    print('Previous shape, pixels are in 1D vector', df.shape)\n    df = df.values.reshape(-1, dim , dim , 1)\n    print('After reshape, pixels are a 28*28*1 3D matrix', df.shape)\n    return df\n\nxtrain = df_reshape(xtrain)\ntest = df_reshape(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\n\nprint(type(ytrain))\n\nnclasses = ytrain.max() - ytrain.min() + 1\nprint('Shape of ytrain before:', ytrain.shape)\n\nytrain = to_categorical(ytrain, num_classes = nclasses)\nprint('Shape pf ytrain after:', ytrain.shape)\n\nprint(type(ytrain))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nseed = 2\nnp.random.seed(seed)\n\nsplit_pct = 0.1\n\nxtrain, xval, ytrain, yval = train_test_split(xtrain,\n                                              ytrain,\n                                              test_size=split_pct,\n                                              random_state=seed,\n                                              shuffle = True,\n                                              stratify = ytrain\n                                              )\nprint(xtrain.shape, ytrain.shape, xval.shape, yval.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import backend as K\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Lambda, Flatten, BatchNormalization\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPool2D\nfrom keras.layers import AveragePooling2D\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.callbacks import LearningRateScheduler","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nets = 5\nmodel = [0]*nets\nfor i in range(nets):\n    model[i] = Sequential()\n    model[i].add(Conv2D(32, kernel_size=3, activation = 'relu',input_shape=(28,28,1)))\n    model[i].add(BatchNormalization())\n    model[i].add(Conv2D(32, kernel_size=3, activation='relu'))\n    model[i].add(BatchNormalization())\n    model[i].add(Conv2D(32, kernel_size=5, strides=2, padding='same',activation='relu'))\n    model[i].add(BatchNormalization())\n    model[i].add(Dropout(0.4))\n    \n    model[i].add(Conv2D(64, kernel_size=3, activation='relu'))\n    model[i].add(BatchNormalization())\n    model[i].add(Conv2D(64, kernel_size=3, activation='relu'))\n    model[i].add(BatchNormalization())\n    model[i].add(Conv2D(64, kernel_size=5, strides = 2, padding='same', activation='relu'))\n    model[i].add(BatchNormalization())\n    model[i].add(Dropout(0.4))\n    \n    model[i].add(Conv2D(128, kernel_size=4, activation='relu'))\n    model[i].add(BatchNormalization())\n    model[i].add(Flatten())\n    model[i].add(Dropout(0.4))\n    model[i].add(Dense(10, activation='softmax'))\n    model[i].compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"raw","source":"datagen = ImageDataGenerator(\n            featurewise_center= True,\n            samplewise_center = True,\n            featurewise_std_normalization=False,\n            samplewise_std_normalization=False,\n            zca_whitening=False,\n            rotation_range=20,\n            zoom_range=0.2,\n            horizontal_flip=True,\n            )\n          \n\n\ndatagen.fit(xtrain)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"annealer = LearningRateScheduler(lambda x: 1e-3 * 0.95 ** x)\nhistory = [0] * nets\nepochs = 45\nfor j in range(nets):\n    print('CNN', j+1)\n    X_train2, X_val2, Y_train2, Y_val2 = train_test_split(xtrain , ytrain , test_size = 0.1)\n    history[j] = model[j].fit_generator(datagen.flow(X_train2, Y_train2, batch_size=64),\n                                       epochs = epochs, \n                                       steps_per_epoch = X_train2.shape[0]//64,\n                                        validation_data = (X_val2, Y_val2), callbacks = [annealer], verbose=1)\n    print('CNN {0:d}: Epochs = {1:d}, Train_accuracy={2:.5f}, Validation accuracy = {3:.5f}'.format(\n                                        j+1, epochs, max(history[j].history['acc']), max(history[j].history['val_acc']) ))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = np.zeros( (test.shape[0],10) ) \nfor j in range(nets):\n    results = results + model[j].predict(test)\nresults = np.argmax(results,axis = 1)\nresults = pd.Series(results,name=\"Label\")\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\nsubmission.to_csv(\"predictions.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":4}