{"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\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 read-only \"../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# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Importing and Exploring dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, y_train = df.drop('label',axis=1), df.label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(x_train.shape, y_train.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### nice way to count and check data is IMBALANCED or not"},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(y_train)\n\ny_train.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(x_train.shape,x_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Reshaping image in 3 dimensions (-1 FOR ROW, and 28,28,1 FOR COLUMNS)"},{"metadata":{"trusted":true},"cell_type":"code","source":"\nx_train = x_train.values.reshape(-1,28,28,1)\nx_test = x_test.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### no need to normalize, since already done but coverting to float "},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = x_train.astype('float32')\nx_test = x_test.astype('float32')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\ny_train = to_categorical(y_train, num_classes=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(x_train.shape,y_train.shape, x_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train,  X_val, Y_train, Y_val = train_test_split(x_train, y_train, test_size=0.01, random_state=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train.shape, X_val.shape, Y_train.shape, Y_val.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Applying Convolutional Neural Network with Keras support"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPool2D, Flatten\nfrom keras.layers import Dense","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#initialising the CNN\nmodel = Sequential()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### add conv layers prior to pooling"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Step 1- adding TWO convolutional layers\nmodel.add(Conv2D(32,(3,3),input_shape=(28,28,1),activation='relu'))\nmodel.add(Conv2D(32,(3,3),activation='relu'))\n#Step 2-pooling\nmodel.add(MaxPool2D(pool_size=(2,2)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Step 3-flattening the conv layer\nmodel.add(Flatten())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### output_dim parameter in dense fn is deprecated in new versions"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Step 4-adding fully connected layer\nmodel.add( Dense(128,activation='relu') )\nmodel.add( Dense(10, activation='softmax') )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#compiling the CNN\nmodel.compile( optimizer='adam',loss='categorical_crossentropy', metrics=['accuracy'] )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(X_train,Y_train, batch_size=32,\n                              epochs = 30, validation_data = (X_val,Y_val),\n                              verbose = 1, steps_per_epoch=X_train.shape[0] // 32)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### fitting the CNN to the images\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"result = model.predict(x_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result = np.argmax(result,axis=1)\nresult = pd.Series(result,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),result],axis = 1)\n\nsubmission.to_csv(\"cnn_mnist_submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}