{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport keras\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files \n# under the input directory\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(\"../input/Kannada-MNIST/train.csv\")\ntest_df = pd.read_csv(\"../input/Kannada-MNIST/test.csv\")\ntrain_additional_df = pd.read_csv(\"../input/Kannada-MNIST/Dig-MNIST.csv\")\n\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.concat([train_df,train_additional_df], ignore_index=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(train_df[\"label\"])\nplt.title(\"number of example for each label\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## convert pixel values to image"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images = train_df.iloc[:,1:].values\nprint(f\"shape of train_images:{train_images.shape}\")\n\ntrain_images = train_images.reshape(-1,28,28,1)\nprint(f\"shape of train_images:{train_images.shape}\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## get labels"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_labels = train_df.label\ntrain_labels.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12,8))\nfor i in range(1,33):\n    plt.subplot(4,8,i)\n    randomIndex = np.random.randint(0,train_images.shape[0])\n    plt.imshow(train_images[randomIndex,:,:,0],cmap=\"gray\")\n    plt.title(train_labels[randomIndex])\n    plt.axis(\"off\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nX_train, X_val, y_train, y_val = train_test_split(train_images, train_labels, test_size = 0.1, random_state = 0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_images = test_df.iloc[:,1:].values\nprint(f\"shape of test_images:{test_images.shape}\")\n\ntest_images = test_images.reshape(-1,28,28,1)\nprint(f\"shape of test_images:{test_images.shape}\")\n\ntest_images = test_images / 255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_id = test_df.id\ntest_id[:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(\n            rescale=1./255,\n            rotation_range=20,\n            width_shift_range=0.2,\n            height_shift_range=0.2,\n            shear_range=0.2,\n            zoom_range=0.2,\n            fill_mode='nearest'\n)\n\nvalidation_datagen = ImageDataGenerator(\n            rescale=1./255\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout,\\\n                                    Flatten, Dense, BatchNormalization, ZeroPadding2D, LeakyReLU\nfrom tensorflow.keras.regularizers import l2\n\nlamda = 0.0\nalpha = 0.1\n\nmodel = tf.keras.models.Sequential([\n    Conv2D(64, (3,3), input_shape=(28, 28, 1), padding=\"same\", kernel_regularizer=l2(lamda)),\n    BatchNormalization(),\n    LeakyReLU(alpha),\n    Conv2D(64, (3,3), padding=\"same\", kernel_regularizer=l2(lamda)),\n    BatchNormalization(),\n    LeakyReLU(alpha),\n    MaxPooling2D(2, 2),\n    Dropout(0.2),\n    \n    Conv2D(128, (3,3), padding=\"same\", kernel_regularizer=l2(lamda)),\n    BatchNormalization(),\n    LeakyReLU(alpha),\n    Conv2D(128, (3,3), padding=\"same\", kernel_regularizer=l2(lamda)),\n    BatchNormalization(),\n    LeakyReLU(alpha),\n    MaxPooling2D(2,2),\n    Dropout(0.2),\n    \n    Conv2D(256, (3,3), padding=\"same\", kernel_regularizer=l2(lamda)),\n    BatchNormalization(),\n    LeakyReLU(alpha),\n    Conv2D(256, (3,3), padding=\"same\", kernel_regularizer=l2(lamda)),\n    BatchNormalization(),\n    LeakyReLU(alpha),\n    MaxPooling2D(2,2),\n    Dropout(0.2),\n    \n    Flatten(),\n    Dense(1024, kernel_regularizer=l2(lamda)),\n    BatchNormalization(),\n    LeakyReLU(alpha),\n    Dense(128, kernel_regularizer=l2(lamda)),\n    BatchNormalization(),\n    LeakyReLU(alpha),\n    Dense(10, activation='softmax')\n])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=\"sgd\",\n              # categorical_crossentropy is for one-hot vector\n              # sparse_categorical_crossentropy is for only label\n              loss='sparse_categorical_crossentropy',\n              metrics = ['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=5,\n                                                  verbose=0, mode='auto')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_check_point = keras.callbacks.ModelCheckpoint('../input/best_model.hdf5', monitor='val_acc',\n                                                       verbose=0, save_best_only=True, mode='auto')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(\n                train_datagen.flow(X_train, y_train, batch_size=128),\n                validation_data=validation_datagen.flow(X_val,y_val),\n                epochs=50,\n                callbacks=[early_stopping,model_check_point],\n                verbose=2\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i = np.argmin(history.history[\"val_loss\"])\nvl = f'{history.history[\"val_loss\"][i]:.3f}'\nva = f'{history.history[\"val_acc\"][i] * 100:.3f}'\nprint(f'val_loss:{vl}')\nprint(f'val_acc:{va}%')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import requests\n\ndef send_line_notification(message):\n    line_token = 'EdfDlQndHEEyffeozYDp6dem5IY8rReixPI51L63bX0'  # 終わったら無効化する\n    endpoint = 'https://notify-api.line.me/api/notify'\n    message = \"\\n{}\".format(message)\n    payload = {'message': message}\n    headers = {'Authorization': 'Bearer {}'.format(line_token)}\n    requests.post(endpoint, data=payload, headers=headers)\n\nmessage = f'val_loss:{vl},val_acc:{va}%'\n# send_line_notification(message)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"acc      = history.history['acc']\nval_acc  = history.history['val_acc']\nloss     = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs   = range(len(acc))\n\n\n# Plot training and validation accuracy per epoch\nplt.plot(epochs,acc)\nplt.plot(epochs,val_acc)\nplt.ylim(0.7,1.0)\nplt.title('Training and validation accuracy')\nplt.figure()\n\n# Plot training and validation loss per epoch\nplt.plot(epochs,loss)\nplt.plot(epochs,val_loss)\nplt.title('Training and validation loss')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.load_model('../input/best_model.hdf5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = model.predict_classes(test_images)\ny_pred[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(y_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame({\n    \"id\":test_id,\n    \"label\":y_pred\n})\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv(\"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":1}