{"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\n\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom keras.models import Sequential # initialize neural network library\nfrom keras.utils import to_categorical\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 sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom keras.layers import Dense,Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop,Adam,Adamax\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\n\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":"sample = pd.read_csv(\"../input/sample_submission.csv\") #28 * 28 pixel\ntrain =  pd.read_csv(\"../input/train.csv\")\ntest = pd.read_csv(\"../input/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"adca4565b8c4917cf471f6321a9bf7f500758c1c"},"cell_type":"code","source":"img_size = 28 # image consists of 784 pixel which is 28 * 28 ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dec38229aaa31e418d71384a8b8eae4e923a2b81"},"cell_type":"code","source":"Y = train['label'] # target data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2a43b572958a272b89f8156b5e545a801540fbe0"},"cell_type":"code","source":"X = train.drop(['label'],axis = 1) #train data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e67f23e3a12b2e2b27d334edc296d06fa3b3a850"},"cell_type":"code","source":"# Normalize the data\nX = X / 255.0\ntest = test / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6b17da8ba3ade636b8913fc2570bdc6852b85064"},"cell_type":"code","source":"#The first 25 data point in train data and their labels\nplt.figure(figsize = (10,10))\nfor i in range (25) :\n    plt.subplot(5,5,i+1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    plt.xlabel(Y[i])\n    plt.imshow(X.iloc[i,:].values.reshape(img_size,img_size))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f70c5b4444d2d4c626d8ef75eafea0b68e87c175"},"cell_type":"code","source":"# Then lets create x_train, y_train, x_test, y_test arrays\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.15, random_state=42)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a12923ec61b3bbcb072e0df56da5e349e68864de"},"cell_type":"code","source":"print(\"X_train shape is : \",X_train.shape)\nprint(\"Y_train shape is : \", Y_train.shape)\nprint(\"X_test shape is \" , X_test.shape)\nprint(\"Y_test shape is \" , Y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2bcabe7dfbe44b581b8a899a3a446c30abdcc627"},"cell_type":"code","source":"#Firstly I tried logistic regression , to see compare the result with neural networks.\nfrom sklearn import linear_model\nlogreg = linear_model.LogisticRegression(random_state = 42,max_iter= 150,solver = 'sag', tol = 0.1,)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a151cc4f41f75a17eae7689f24ccf834d027e1ae"},"cell_type":"code","source":"Y_train =Y_train.values.reshape(-1,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d45334c14dc6950e627b155942fa7718b18f48bd"},"cell_type":"code","source":"logreg.fit(X_train,Y_train )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1466d7b79d276a07d90610f755b4a4baba98d8fc"},"cell_type":"code","source":"print(\"test accuracy: {} \".format(logreg.score(X_test, Y_test)))\nprint(\"train accuracy: {} \".format(logreg.score(X_train, Y_train)))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"18061c7dd2d75b441f894168d7875329344222c4"},"cell_type":"markdown","source":"# Neural Network part\n<br>\n<br>\n<br>\n<a href= \"https://towardsdatascience.com/how-to-build-your-own-neural-network-from-scratch-in-python-68998a08e4f6\"><img src = \"https://cdn-images-1.medium.com/max/1600/1*sX6T0Y4aa3ARh7IBS_sdqw.png\" alt=\"Neural Network\"></a>\n\n"},{"metadata":{"trusted":true,"_uuid":"f23f845a33fb7a9b1151958037cf9af0ca8311b2"},"cell_type":"code","source":"#keras optimizer for neural network\nadamax =Adamax(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"18b213ebe26633e0e3421061d112c72f74365dc7"},"cell_type":"code","source":"#defining function for building neural network\ndef Classifier() :\n    model = Sequential() # initialize neural network\n    model.add(Dense(units = 240, kernel_initializer = 'uniform', activation = 'relu', input_dim = X_train.shape[1]))\n    model.add(Dense(units = 240, kernel_initializer = 'uniform', activation = 'relu'))\n    model.add(Dense(units = 10, kernel_initializer = 'uniform', activation = 'softmax'))#softmax is used for classification\n    model.compile(optimizer = adamax, loss = 'categorical_crossentropy', metrics = ['accuracy'])\n    return model \n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b1f288eaba0467b890920a708fd3b3978486b78e"},"cell_type":"code","source":"model = Classifier()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f5094f596d6df2b21ea2ab852b937e611c04f5b9"},"cell_type":"code","source":"Y_train = to_categorical(Y_train) #we are using 1 hot encoding here","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0fa9dfe07bc867cb1d41f3a9197126a22cee7796"},"cell_type":"code","source":"history = model.fit(X_train , Y_train,epochs = 10,batch_size = 150 )#fitting our model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4f2c384f44df5dadafb324951be3f8b5fc1ff4d2"},"cell_type":"code","source":"test_loss, test_acc = model.evaluate(X_train, Y_train) #evaluating our model\nprint('Test accuracy:', test_acc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c3c1d9ab20c3dc98e64943cdb93b960c48d8e051"},"cell_type":"code","source":"#Plottling accuracy\nplt.plot(history.history['acc'])\n#plt.plot(history.history['loss'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['accuracy'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"957b26211a193f0b1a28c818a239fddeb3757602"},"cell_type":"code","source":"#Plotting loss values\nplt.plot(history.history['loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['loss'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"80cc9f9a9671210a53575fe977f947f614fa6237"},"cell_type":"code","source":"prediction = model.predict(test) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"57981f4ebeb9303478feb75d0480acbc4909f6fa"},"cell_type":"code","source":"#First 15 samples of test database and result of them . It looks like we are taking corrects results\nplt.figure(figsize = (30,20))\nfor i in range (15):\n    plt.subplot(5,6, 1 + 2*i )\n    plt.imshow(test.iloc[i].values.reshape(img_size,img_size))\n    plt.subplot(5,6,2 +(2*i) )\n    plt.plot(prediction[i])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"310c1c442068e0d37c8c257584e25a9a652f44ff"},"cell_type":"markdown","source":"**Convolutional Neural Network ( CNN) **\n<br>\n<br>\n\n<a href=\"https://medium.com/@RaghavPrabhu/understanding-of-convolutional-neural-network-cnn-deep-learning-99760835f148\"><img src=\"https://cdn-images-1.medium.com/max/1600/1*XbuW8WuRrAY5pC4t-9DZAQ.jpeg\" alt=\"CNN\" border=\"0\"></a>"},{"metadata":{"trusted":true,"_uuid":"13c738c494f421d1ddbcbc3f70b3de14fb0aa086"},"cell_type":"code","source":"#Creating our CNN MODEL\nmodel3 = Sequential()\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"40d684792579f9f0e321871d0392f740d11eb67f"},"cell_type":"code","source":"#Addıng layers to our CNN model\nmodel3.add(Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel3.add(Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel3.add(MaxPool2D(pool_size=(2,2)))\nmodel3.add(Dropout(0.25))\n\nmodel3.add(Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel3.add(Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel3.add(MaxPool2D(pool_size=(2,2)))\nmodel3.add(Dropout(0.25))\n\n\nmodel3.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel3.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel3.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel3.add(Dropout(0.25))\n\n\nmodel3.add(Flatten())\nmodel3.add(Dense(256, activation = \"relu\"))\nmodel3.add(Dropout(0.5))\nmodel3.add(Dense(10, activation = \"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e70f067b650d5cf961c7651f915b4ebf4092e831"},"cell_type":"code","source":"optimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"941bbc9c4aaa1b0d03eca865e77219f8f1f398c4"},"cell_type":"code","source":"model3.compile(optimizer  = optimizer , loss = 'categorical_crossentropy',metrics =['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ada25bddaada3447ef2d47cf5e21cc8ebeb944fb"},"cell_type":"code","source":"# Then lets create x_train, y_train, x_test, y_test arrays\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.15, random_state=42)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b0adcccafe7a30cb7b6bd98c56cb3ea23d2fe978"},"cell_type":"code","source":"#Data Reshaping \nX_train = X_train.values.reshape(-1,28,28,1)\nY_train = to_categorical(Y_train, num_classes = 10)\nX_test = X_test.values.reshape(-1,28,28,1)\nY_test=to_categorical(Y_test , num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4471e153bc2d8edc18d7a09104e22c428ec9241f"},"cell_type":"code","source":"# data augmentation\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,  # dimesion reduction\n        rotation_range=0.5,  # randomly rotate images in the range 5 degrees\n        zoom_range = 0.5, # Randomly zoom image 5%\n        width_shift_range=0.5,  # randomly shift images horizontally 5%\n        height_shift_range=0.5,  # randomly shift images vertically 5%\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3693410f52b64059201132cc5777ba0e4aec00cb"},"cell_type":"code","source":"print(\"x_train shape\",X_train.shape)\nprint(\"x_test shape\",X_test.shape)\nprint(\"y_train shape\",Y_train.shape)\nprint(\"y_test shape\",Y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"07a40005b9db3494afe1e907f835b6ad19063458"},"cell_type":"code","source":"# Fit the model\nhistory = model3.fit_generator(datagen.flow(X_train,Y_train, batch_size=140),\n                              epochs = 10, validation_data = (X_test,Y_test) )#steps_per_epoch=X_train.shape[0] // batch_size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f04f95c99bcb03cc4966451cbaaae2ec954260a4"},"cell_type":"code","source":"model3.evaluate(X_train,Y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8c5d55e1c5dcd2309a690c00127dd94517ef0cf2"},"cell_type":"code","source":"#Evalution of models \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e31e2572a44777a7b3a23e5c68a3d1e2a217f001"},"cell_type":"code","source":"test = test.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"49aa46bf934eaa01ba0876bf6315821db991e77b"},"cell_type":"code","source":"#Submit file\npredictions_class = model3.predict_classes(test, verbose=0)\n\nsubmissions=pd.DataFrame({\"ImageId\": list(range(1,len(predictions_class)+1)),\n                         \"Label\": predictions_class})\nsubmissions.to_csv(\"Submission.csv\", index=False, header=True)\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"359637361290f83a70e963d82b9933def699fc43"},"cell_type":"markdown","source":"* **Im beginner at data science , while I am creating these kernels , ım also learning the topics from resources and other kernels by you . **\n* **I wiil be happy if you will give some feedback on my works . **\n* **Have a good day :)**"},{"metadata":{"trusted":true,"_uuid":"4f3a6ed9f214f84957eec8b7909cfec74b886570"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"657f97a4871a81ba4b3a19e624c263878f5dace9"},"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}