{"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)\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.optimizers import RMSprop\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\nfrom keras.datasets import mnist\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":"# Load the data\ntrain = pd.read_csv('../input/train.csv')\nlabels = train.iloc[:,0].values.astype('int32')\nX_train = (train.iloc[:,1:].values).astype('float32')\nX_test = (pd.read_csv('../input/test.csv').values).astype('float32')\n\n#reshape into images\nX_train = X_train.reshape(-1,28,28,1)\nX_test = X_test.reshape(-1,28,28,1)\n\n# one hot encoding\ny_train = tf.keras.utils.to_categorical(labels) \n\n\nprint(\"Check data\")\nprint(labels)\nprint(X_train[0].shape)\nprint(y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3f5ec9e52cc5ecd1f60751f18fc7ff726aaee91b"},"cell_type":"code","source":"# Load Data from Keras MNIST\n(train_imagesRaw, train_labelsRaw), (test_imagesRaw, test_labelsRaw) = mnist.load_data()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"55567d001436cec94b10423190e5708774bb67c6"},"cell_type":"code","source":"#reshape into images\nX_train_keras = train_imagesRaw.reshape(-1,28,28,1)\nX_test_keras = test_imagesRaw.reshape(-1,28,28,1)\n\nprint(\"X_train_keras\",X_train_keras.shape)\nprint(\"X_test_keras\",X_test_keras.shape)\n\ntrain_labels_keras = tf.keras.utils.to_categorical(train_labelsRaw)\ntest_labels_keras = tf.keras.utils.to_categorical(test_labelsRaw)\nprint(\"train_labels_keras \",train_labels_keras.shape)\nprint(\"test_labels_keras \", test_labels_keras.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9c62b5190aa12b060e90673098e89a3f1db936c4"},"cell_type":"code","source":"# merge datasets\n\ntrain_images = np.concatenate((X_train_keras,X_train,X_test_keras), axis=0)\nprint(\"new Concatenated train_images \", train_images.shape)\nprint(\"_\"*50)\n\ntrain_labels = np.concatenate((train_labels_keras,y_train,test_labels_keras), axis=0)\nprint(\"new Concatenated train_labels \", train_labels.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2068b5fcd6c5c6e485369b9155bc69395b089e48"},"cell_type":"code","source":"#visualize an image\n\nfig = plt.figure()\nplt.imshow(X_train[0][:,:,0], cmap='gray', interpolation='none')\nplt.xticks([])\nplt.yticks([])\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"507b5aaa6dd199b9847adb5de9e11ee7f92267b7"},"cell_type":"code","source":"# super simple data pre process\nscale = np.max(train_images)\ntrain_images /= scale\nX_test /= scale\n\n\n#visualize scales\n\nprint(\"Max: {}\".format(scale))\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1c4c71fa80f1d87ecbbb571b191e57272cdc54fd"},"cell_type":"code","source":"# Here we define the input and output layer sizes\ninput_size = train_images.shape\nn_logits = train_labels.shape[1]\n\nprint(\"Input: {}\".format(input_size))\nprint(\"Output: {}\".format(n_logits))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"38858692c060a70cd1c9b5045c6395388da09e34"},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n\n# Set a learning rate annealer\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\n\nepochs = 30\nbatch_size = 512\n#get validation data\n\nX_train, X_val, Y_train, Yval = train_test_split(train_images, train_labels, train_size = 0.90)\n\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,"scrolled":false,"_uuid":"cbadf392e7c59659105a83494be97cfed4dd87a1"},"cell_type":"code","source":"# Here we define our keras model\nmodel = tf.keras.Sequential()\nmodel.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3),padding='same', activation='relu', input_shape=input_size[1:]))\nmodel.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=None))\nmodel.add(tf.keras.layers.Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu'))\nmodel.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))\nmodel.add(tf.keras.layers.Dropout(0.25))\nmodel.add(tf.keras.layers.Flatten())\nmodel.add(tf.keras.layers.Dense(256, activation='relu'))\nmodel.add(tf.keras.layers.Dense(256, activation='relu'))\nmodel.add(tf.keras.layers.Dense(256, activation='relu'))\nmodel.add(tf.keras.layers.Dropout(0.5))\nmodel.add(tf.keras.layers.Dense(n_logits, activation='softmax'))\n\noptimizer = tf.keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\n\n\n# Set a learning rate annealer\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\n\n\nmodel.compile(loss='categorical_crossentropy',\n              optimizer=optimizer,\n              metrics=['accuracy'])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ff1a61066e27fe3cd82820530b9f50b8c22c640c"},"cell_type":"code","source":"# Fit the model\nhistory = model.fit_generator(datagen.flow(X_train,Y_train, batch_size=batch_size),\n                              epochs = epochs, validation_data = (X_val,Yval),\n                              verbose = 1, steps_per_epoch=X_train.shape[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8e831a0319e3ee14be5f01fe0fcfdeb1989ffd58"},"cell_type":"code","source":"# generate predictions\npredictions = model.predict_classes(X_test, verbose=0)\n\nprint(predictions)\npd.DataFrame({\"ImageId\": list(range(1,len(predictions)+1)), \"Label\": predictions}).to_csv(\"preds.csv\", index=False, header=True)\n","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}