{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"#last version\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau, CSVLogger","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":"train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAINING_LOGS_FILE = \"training_logs.csv\"\nMODEL_SUMMARY_FILE = \"model_summary.txt\"\nMODEL_FILE = \"model.h5\"\nTRAINING_PLOT_FILE = \"training.png\"\nVALIDATION_PLOT_FILE = \"validation.png\"\nKAGGLE_SUBMISSION_FILE = \"MNISTsubmission.csv\"\n\nGOOGLE_COLAB = True\n\n#if GOOGLE_COLAB:\n#!pip install livelossplot\n#from livelossplot import PlotLossesKeras\n\n#if GOOGLE_COLAB:\n#!pip install google.colab\n\nVERBOSITY = 1\nEPOCHS = 3\nBATCH_SIZE = 512\nCLASSES = 10\nCHANNELS = 1\nIMAGE_SIZE = 28\nIMAGE_WIDTH, IMAGE_HEIGHT = IMAGE_SIZE, IMAGE_SIZE\nVALIDATION_RATIO = 0.1\n\n#if GOOGLE_COLAB:\n#from google.colab import drive, files","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y = train[\"label\"]\ny","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = train.drop(labels = [\"label\"], axis = 1) \nx","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reshape data\nx = x.values.reshape(-1, IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)\ntest = test.values.reshape(-1, IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)\n\n# One-Hot encoding\ny = to_categorical(y, num_classes=CLASSES)\n\n# Prepare training/validation sets\nx_training, x_validation, y_training, y_validation = train_test_split(x,\n                                                                      y,\n                                                                      test_size=VALIDATION_RATIO,\n                                                                      shuffle = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Model (0.995)\nmodel = Sequential()\n\nmodel.add(Conv2D(filters=32,\n                 kernel_size=(5,5),\n                 padding='Same', \n                 activation='relu',\n                 input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)))\nmodel.add(Conv2D(filters=32,\n                 kernel_size=(5,5),\n                 padding='Same', \n                 activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.5))\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(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Flatten())\nmodel.add(Dense(8192, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(2048, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(CLASSES, activation=\"softmax\"))\n\nmodel.compile(optimizer=RMSprop(lr=0.0001,\n                                rho=0.9,\n                                epsilon=1e-08,\n                                decay=0.00001),\n              loss=\"categorical_crossentropy\",\n              metrics=[\"accuracy\"])\n\nwith open(MODEL_SUMMARY_FILE,\"w\") as fh:\n    model.summary(print_fn=lambda line: fh.write(line + \"\\n\"))\n\n# Data augmentation\ndata_generator = ImageDataGenerator(rescale=1./255,\n                                    rotation_range=1,\n                                    zoom_range=0.1, \n                                    width_shift_range=0.05,\n                                    height_shift_range=0.05)\ndata_generator.fit(x_training)\n\n# Training\nhistory = model.fit_generator(data_generator.flow(x_training,\n                                                  y_training,\n                                                  batch_size=BATCH_SIZE),\n                              epochs=EPOCHS,\n                              validation_data=(x_validation, y_validation),\n                              verbose=VERBOSITY,\n                              steps_per_epoch=x_training.shape[0] // BATCH_SIZE,\n                              callbacks=[PlotLossesKeras(),\n                                         CSVLogger(TRAINING_LOGS_FILE,\n                                                   append=False,\n                                                   separator=\";\")])\nmodel.save_weights(MODEL_FILE)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Testing\npredictions = model.predict_classes(test, verbose=1)\npred = pd.array(predictions)\npred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = pd.read_csv('../input/digit-recognizer/sample_submission.csv')  \nresult = sample  \nsample","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(28000):\n    result['Label'][i] = pred[i]\ndf = result    \nresult   \n#! /opt/conda/bin/python3.7 -m pip install --upgrade pip\n#! conda install pandas\ndf.to_csv('result.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Модель 0.996 (2)\n\n\nmodel = Sequential()\n\nmodel.add(Conv2D(filters=16,\n                 kernel_size=(3,3),\n                 padding='Same', \n                 activation='relu',\n                 input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)))\nmodel.add(Conv2D(filters=16,\n                 kernel_size=(3,3),\n                 padding='Same', \n                 activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Conv2D(filters=32, kernel_size=(3,3),padding='Same', \n                 activation='relu'))\nmodel.add(Conv2D(filters=32, kernel_size=(3,3),padding='Same', \n                 activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Flatten())\nmodel.add(Dense(8192, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(2048, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(CLASSES, activation=\"softmax\"))\n\nmodel.compile(optimizer=RMSprop(lr=0.0001,\n                                rho=0.9,\n                                epsilon=1e-08,\n                                decay=0.00001),\n              loss=\"categorical_crossentropy\",\n              metrics=[\"accuracy\"])\n\nwith open(MODEL_SUMMARY_FILE,\"w\") as fh:\n    model.summary(print_fn=lambda line: fh.write(line + \"\\n\"))\n\n# Data augmentation\ndata_generator = ImageDataGenerator(rescale=1./255,\n                                    rotation_range=1,\n                                    zoom_range=0.1, \n                                    width_shift_range=0.05,\n                                    height_shift_range=0.05)\ndata_generator.fit(x_training)\n\n# Training\nhistory = model.fit_generator(data_generator.flow(x_training,\n                                                  y_training,\n                                                  batch_size=BATCH_SIZE),\n                              epochs=EPOCHS,\n                              validation_data=(x_validation, y_validation),\n                              verbose=VERBOSITY,\n                              steps_per_epoch=x_training.shape[0] // BATCH_SIZE,\n                              callbacks=[PlotLossesKeras(),\n                                         CSVLogger(TRAINING_LOGS_FILE,\n                                                   append=False,\n                                                   separator=\";\")])\nmodel.save_weights(MODEL_FILE)\n\n# Testing\npredictions = model.predict_classes(test, verbose=1)\npd.DataFrame({\"ImageId\":list(range(1,len(predictions)+1)),\"Label\":predictions}).to_csv(KAGGLE_SUBMISSION_FILE,index=False,header=True)\n\n# Drawing plots\nepochs = [i for i in range(1, len(history.history['loss'])+1)]\n\nplt.plot(epochs, history.history['loss'], color='blue', label=\"training_loss\")\nplt.plot(epochs, history.history['val_loss'], color='red', label=\"validation_loss\")\nplt.legend(loc='best')\nplt.title('training')\nplt.xlabel('epoch')\nplt.savefig(TRAINING_PLOT_FILE, bbox_inches='tight')\nplt.close()\n\nplt.plot(epochs, history.history['acc'], color='blue', label=\"training_accuracy\")\nplt.plot(epochs, history.history['val_acc'], color='red',label=\"validation_accuracy\")\nplt.legend(loc='best')\nplt.title('validation')\nplt.xlabel('epoch')\nplt.savefig(VALIDATION_PLOT_FILE, bbox_inches='tight')\nplt.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Модель 0.997 VGG19(3)\n\n\nmodel = Sequential()\n\nmodel.add(Conv2D(filters=64,\n                 kernel_size=(3,3),\n                 padding='Same', \n                 activation='relu',\n                 input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)))\nmodel.add(Conv2D(filters=64,\n                 kernel_size=(3,3),\n                 padding='Same', \n                 activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Conv2D(filters=128, kernel_size=(3,3),padding='Same', \n                 activation='relu'))\nmodel.add(Conv2D(filters=128, kernel_size=(3,3),padding='Same', \n                 activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Conv2D(filters=256, kernel_size=(3,3),padding='Same', \n                 activation='relu'))\nmodel.add(Conv2D(filters=256, kernel_size=(3,3),padding='Same', \n                 activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Flatten())\nmodel.add(Dense(4096, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(1000, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(CLASSES, activation=\"softmax\"))\n\nmodel.compile(optimizer=RMSprop(lr=0.0001,\n                                rho=0.9,\n                                epsilon=1e-08,\n                                decay=0.00001),\n              loss=\"categorical_crossentropy\",\n              metrics=[\"accuracy\"])\n\nwith open(MODEL_SUMMARY_FILE,\"w\") as fh:\n    model.summary(print_fn=lambda line: fh.write(line + \"\\n\"))\n\n# Data augmentation\ndata_generator = ImageDataGenerator(rescale=1./255,\n                                    rotation_range=1,\n                                    zoom_range=0.1, \n                                    width_shift_range=0.05,\n                                    height_shift_range=0.05)\ndata_generator.fit(x_training)\n\n# Training\nhistory = model.fit_generator(data_generator.flow(x_training,\n                                                  y_training,\n                                                  batch_size=BATCH_SIZE),\n                              epochs=EPOCHS,\n                              validation_data=(x_validation, y_validation),\n                              verbose=VERBOSITY,\n                              steps_per_epoch=x_training.shape[0] // BATCH_SIZE,\n                              callbacks=[PlotLossesKeras(),\n                                         CSVLogger(TRAINING_LOGS_FILE,\n                                                   append=False,\n                                                   separator=\";\")])\nmodel.save_weights(MODEL_FILE)\n\n# Testing\npredictions = model.predict_classes(test, verbose=1)\npd.DataFrame({\"ImageId\":list(range(1,len(predictions)+1)),\"Label\":predictions}).to_csv(KAGGLE_SUBMISSION_FILE,index=False,header=True)\n\n# Drawing plots\nepochs = [i for i in range(1, len(history.history['loss'])+1)]\n\nplt.plot(epochs, history.history['loss'], color='blue', label=\"training_loss\")\nplt.plot(epochs, history.history['val_loss'], color='red', label=\"validation_loss\")\nplt.legend(loc='best')\nplt.title('training')\nplt.xlabel('epoch')\nplt.savefig(TRAINING_PLOT_FILE, bbox_inches='tight')\nplt.close()\n\nplt.plot(epochs, history.history['acc'], color='blue', label=\"training_accuracy\")\nplt.plot(epochs, history.history['val_acc'], color='red',label=\"validation_accuracy\")\nplt.legend(loc='best')\nplt.title('validation')\nplt.xlabel('epoch')\nplt.savefig(VALIDATION_PLOT_FILE, bbox_inches='tight')\nplt.close()","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}