{"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 matplotlib.pyplot as plt\n%matplotlib inline\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":"train_df = pd.read_csv(\"../input/train.csv\")\ntest_df = pd.read_csv(\"../input/test.csv\")\ntest_df.head()\nprint(test_df.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4692af89b81a8f498f42215848281df50b693aeb"},"cell_type":"code","source":"train_X = train_df.iloc[:,1:].values.astype(\"float32\")\ntrain_Y = train_df.iloc[:,0].values.astype(\"int\")\ntest_X = test_df.values.astype(\"float32\")\nprint(train_X.shape)\ntrain_X = train_X /255.\ntest_X = test_X / 255.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3ea7d167aa9265ee669cdd79918353e346a47bbd"},"cell_type":"code","source":"train_X = train_X.reshape((train_X.shape[0],28,28))\nfor i in range(0,3):\n    plt.subplot(130 + (i+1))\n    plt.imshow(train_X[i],cmap='gray')\n    plt.title(train_Y[i])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d142aa277f02f36bfd80caba1511ce9601e0a22a"},"cell_type":"code","source":"train_X = train_X.reshape((train_X.shape[0],28,28,1))\ntest_X = test_X.reshape((test_X.shape[0],28,28,1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"566e61962de1ca7825b5ff20fbb7970051fab66e"},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\nprint(train_Y.shape)\ntrain_Y = to_categorical(train_Y)\nprint(train_Y.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c6863a7f6fa19506fca91fd2410658d6576fef56"},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain_X, val_X,train_Y,val_Y = train_test_split(train_X, train_Y,test_size=0.1, random_state=42)\nprint(val_X.shape)\nprint(train_X.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cc58b74e9a0d720fa9387abb7b9f4b48206c99eb"},"cell_type":"code","source":"from keras.preprocessing import image\ngen = image.ImageDataGenerator(rotation_range=10, zoom_range=0.1, width_shift_range=0.08, height_shift_range=0.08)\nbatch_size=64\ntrain_batches = gen.flow(train_X, train_Y, batch_size=batch_size)\nval_batches = gen.flow(val_X, val_Y, batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"43a14697aab7148a312b4dae35399841d2482266"},"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 Dense, Conv2D, Flatten, MaxPooling2D, BatchNormalization\nfrom keras.optimizers import Adam","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4072296d1cdd20c2f76f442acdcff48c13537613"},"cell_type":"code","source":"def create_model():\n    model = Sequential()\n    model.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(28,28,1)))\n    BatchNormalization(axis=1)\n    model.add(Dropout(0.2))\n    model.add(MaxPooling2D())\n    model.add(Conv2D(48, kernel_size=3, activation='relu'))\n    BatchNormalization(axis=1)\n    model.add(Dropout(0.2))\n    model.add(MaxPooling2D())\n    model.add(Conv2D(32, kernel_size=3, activation='relu'))\n    BatchNormalization(axis=1)\n    model.add(Flatten())\n    BatchNormalization(axis=1)\n    model.add(Dense(512,activation='relu'))\n    BatchNormalization(axis=1)\n    model.add(Dense(10,activation='softmax'))\n    model.compile(optimizer=Adam(lr=0.002), loss='categorical_crossentropy', metrics=['accuracy'])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"004b363fef6df81eaa453dfbf1b30ae892b9ba63"},"cell_type":"code","source":"model = create_model()\nmodel.summary()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d120618dbf3cc94b4db2c07a9bdbbe4000d465e4"},"cell_type":"code","source":"history = model.fit_generator(generator=train_batches, steps_per_epoch=train_batches.n / batch_size, validation_data=val_batches, validation_steps=val_batches.n / batch_size, epochs=20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"681ac6284d61d7c5127ac344cf496f8a7cc84e14"},"cell_type":"code","source":"plt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1af2dcf506e71867c86a818e27ce23f4890a7e1e"},"cell_type":"code","source":"predictions = model.predict_classes(test_X, verbose=0)\n\nplt.imshow(test_X[0][:,:,0])\nprint(predictions[0])\nsubmissions=pd.DataFrame({\"ImageId\": list(range(1,len(predictions)+1)),\n                         \"Label\": predictions})\nsubmissions.to_csv(\"DR.csv\", index=False, header=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b2988d43afbd904c502c3eec1edc98d4b6e0ecab"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"93a79001844f3e2500f810a18a8fb86449df23ad"},"cell_type":"code","source":"","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}