{"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_minor":4,"nbformat":4,"cells":[{"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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.utils import np_utils\nfrom keras.layers import Dense, Flatten, Input, BatchNormalization, Dropout, Conv2D, MaxPooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport tensorflow as tf\n\nimport pandas as pd\nimport numpy as np\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train =pd.read_csv('../input/digit-recognizer/train.csv')\n\ntest = pd.read_csv('../input/digit-recognizer/test.csv')\n\nX_train = train.iloc[:,1:]\ny_train =train.iloc[:,0]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train = np.array(X_train).reshape(X_train.shape[0],28,28,1)\n\nfrom keras.utils.np_utils import to_categorical\ny_train= to_categorical(y_train)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale = 1./255,\n    rotation_range=20,\n    zoom_range=0.2,\n    width_shift_range = 0.1,\n    height_shift_range = 0.1,\n    \n)\n\nval_datagen = ImageDataGenerator(\n    rescale = 1./255)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX = X_train\ny = y_train\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.10, random_state=42)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow(X_train, y_train, batch_size=64)\nvalidation_generator = val_datagen.flow(X_val, y_val, batch_size=64)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential([\n    \n    Input(shape=(28,28,1)),\n    Conv2D(32, 8, activation='relu', padding='same'),\n    MaxPooling2D(),\n    BatchNormalization(),\n    Dropout(0.4),\n    Conv2D(32, 6, activation='relu', padding='same'),\n    MaxPooling2D(),\n    BatchNormalization(),\n    Dropout(0.4),\n    Conv2D(64, 6, activation='relu', padding='same'),\n    MaxPooling2D(),\n    BatchNormalization(),\n    Dropout(0.3), \n    Conv2D(64, 6, activation='relu', padding='same'),\n    MaxPooling2D(),\n    BatchNormalization(),\n    Dropout(0.3),\n    Flatten(),\n    Dense(256, activation='relu'),\n    BatchNormalization(),\n    Dropout(0.2),\n    Dense(128, activation='relu'),\n    BatchNormalization(),\n    Dropout(0.1),\n    Dense(10, activation='softmax')\n])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model1= model","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"early_stopping = tf.keras.callbacks.EarlyStopping(patience=20)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#history=model.fit(train_generator ,validation_data = validation_generator , epochs=200, callbacks=[early_stopping])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"import seaborn as sns\nimport matplotlib.pyplot as plt\ndef acc_loss_plot():\n    fig, ax = plt.subplots(1,2,figsize=(15,7))\n    ax[0].plot(history.history['accuracy'])\n    ax[0].plot(history.history['val_accuracy'])\n    ax[0].set_title('Accuracy')\n    ax[0].set_ylabel('Accuracy')\n    ax[0].set_xlabel('Epoch')\n    ax[0].legend(['train', 'validation'], loc='lower right')\n    ax[0].grid()\n    ax[1].plot(history.history['loss'])\n    ax[1].plot(history.history['val_loss'])\n    ax[1].set_title('Loss')\n    ax[1].set_ylabel('Loss')\n    ax[1].set_xlabel('Epoch')\n    ax[1].legend(['train', 'validation'], loc='upper right')\n    ax[1].grid()\n    plt.show()\n\nacc_loss_plot()","metadata":{}},{"cell_type":"code","source":"gen =ImageDataGenerator(\n    rescale = 1./255,\n    rotation_range=20,\n    zoom_range=0.2,\n    width_shift_range = 0.1,\n    height_shift_range = 0.1,\n    \n)\n\nmodel1.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])\nbatches = gen.flow(X, y, batch_size=64)\nhistory=model1.fit(batches, epochs=200,callbacks=[early_stopping])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = np.array(test).reshape(-1, 28, 28 , 1) / 255","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = model1.predict(test)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = [np.argmax(x) for x in preds]\nids = [x+1 for x in range(len(preds))]\n\nsub = pd.DataFrame()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['ImageId'] = ids\nsub['Label'] = labels\n\nsub.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n#submissions=pd.DataFrame({\"ImageId\": list(range(1,len(preds)+1)),\n                         #\"Label\": labels})\n#submissions.to_csv(\"DR.csv\", index=False, header=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}