{"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 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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.utils import np_utils\nfrom keras.layers.core import Dense, Activation, Dropout\n\nimport pandas as pd\nimport numpy as np\n\n# Read data\ntrain_data = pd.read_csv('../input/digit-recognizer/train.csv')\ntest_data = pd.read_csv('../input/digit-recognizer/test.csv')\ny = train_data.pop(\"label\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.shape(train_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.shape(y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = train_data.values\ny = y.values\nX_test = test_data.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Dense , Dropout , Flatten\nfrom keras.layers.convolutional import Conv2D , MaxPooling2D\nfrom keras.utils import np_utils\n\nfrom sklearn.model_selection import train_test_split\nfrom matplotlib import pyplot","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_val, y_train, y_val = train_test_split(X_train, y, test_size=0.1, random_state=7)\n\nX_train = X_train.reshape((X_train.shape[0], 28, 28, 1)).astype('float32')\nX_val = X_val.reshape((X_val.shape[0], 28, 28, 1)).astype('float32')\n# normalize inputs from 0-255 to 0-1\nX_train = X_train / 255\nX_val = X_val / 255\n# one hot encode outputs\ny_train = np_utils.to_categorical(y_train)\ny_val = np_utils.to_categorical(y_val)\nnum_classes = y_train.shape[1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\ndatagen = ImageDataGenerator(\n        featurewise_center=False,  # set input mean to 0 over the dataset\n        samplewise_center=False,  # set each sample mean to 0\n        featurewise_std_normalization=False,  # divide inputs by std of the dataset\n        samplewise_std_normalization=False,  # divide each input by its std\n        zca_whitening=False,  # apply ZCA whitening\n        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.1, # Randomly zoom image \n        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\n\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\nepochs = 30 # Turn epochs to 30 to get 0.9967 accuracy\nbatch_size = 86","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = \"softmax\"))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n#model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=10, batch_size=256)\n\nmodel.fit_generator(datagen.flow(X_train,y_train, batch_size=batch_size),\n                              epochs = epochs, validation_data = (X_val,y_val),\n                              verbose = 2, steps_per_epoch=X_train.shape[0] // batch_size\n                              , callbacks=[learning_rate_reduction])\n# Final evaluation of the model\n#scores = model.evaluate(X_val, y_val, verbose=0)\n#print(\"Large CNN Error: %.2f%%\" % (100-scores[1]*100))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test = X_test.reshape((X_test.shape[0], 28, 28, 1)).astype('float32')\nX_test = X_test / 255\npreds = model.predict_classes(X_test, verbose=0)\n\ndef write_preds(preds, fname):\n    pd.DataFrame({\"ImageId\": list(range(1,len(preds)+1)), \"Label\": preds}).to_csv(fname, index=False, header=True)\n\nwrite_preds(preds, \"prediction14.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''def larger_model():\n    # create model\n    model = Sequential()\n    model.add(Conv2D(32, (5, 5), input_shape=(28, 28, 1), activation='relu'))\n    model.add(MaxPooling2D())\n    model.add(Conv2D(16, (3, 3), activation='relu'))\n    model.add(MaxPooling2D())\n    model.add(Dropout(0.2))\n    model.add(Flatten())\n  #  model.add(Dense(128, activation='relu'))\n    model.add(Dropout(0.15))\n    model.add(Dense(128, activation='relu'))\n    model.add(Dense(64, activation='relu'))\n    model.add(Dense(num_classes, activation='softmax'))\n    # Compile model\n    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n    return model\n# build the model\nmodel = larger_model()\n# Fit the model\n'''","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"'''from keras.models import Sequential\nfrom keras.utils import np_utils\nfrom keras.layers.core import Dense, Activation, Dropout\n\nimport pandas as pd\nimport numpy as np\n\n# Read data\ntrain = pd.read_csv('../input/digit-recognizer/train.csv')\nlabels = train.ix[:,0].values.astype('int32')\nX_train = (train.ix[:,1:].values).astype('float32')\nX_test = (pd.read_csv('../input/digit-recognizer/test.csv').values).astype('float32')\n\n# convert list of labels to binary class matrix\ny_train = np_utils.to_categorical(labels) \n\n# pre-processing: divide by max and substract mean\n#scale = np.max(X_train)\nX_train /= 255.0\nX_test /= 255.0\n\nmean = np.std(X_train)\nX_train -= mean\nX_test -= mean\n\ninput_dim = X_train.shape[1]\nnb_classes = y_train.shape[1]\n\n# Here's a Deep Dumb MLP (DDMLP)\nmodel = Sequential()\nmodel.add(Dense(128, input_dim=input_dim))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.15))\nmodel.add(Dense(128))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.15))\nmodel.add(Dense(nb_classes))\nmodel.add(Activation('softmax'))\n\n# we'll use categorical xent for the loss, and RMSprop as the optimizer\nmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop')\n\nprint(\"Training...\")\nmodel.fit(X_train, y_train, nb_epoch=10, batch_size=16, validation_split=0.1, verbose=2)\n\nprint(\"Generating test predictions...\")\npreds = model.predict_classes(X_test, verbose=0)\n\ndef write_preds(preds, fname):\n    pd.DataFrame({\"ImageId\": list(range(1,len(preds)+1)), \"Label\": preds}).to_csv(fname, index=False, header=True)\n\nwrite_preds(preds, \"keras-mlp.csv\")\n'''","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}