{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30587,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"**UAS DEEP LEARNING**","metadata":{}},{"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 seaborn as sns\nimport matplotlib.pyplot as plt\n# import warnings\nimport warnings\n# filter warnings\nwarnings.filterwarnings('ignore')\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 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.","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:36:56.587882Z","iopub.execute_input":"2023-11-23T22:36:56.588338Z","iopub.status.idle":"2023-11-23T22:36:56.596210Z","shell.execute_reply.started":"2023-11-23T22:36:56.588304Z","shell.execute_reply":"2023-11-23T22:36:56.594850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Mengimport Library yang Dibutuhkan","metadata":{}},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n# import warnings\nimport warnings\n# filter warnings\nwarnings.filterwarnings('ignore')","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:36:56.603381Z","iopub.execute_input":"2023-11-23T22:36:56.603766Z","iopub.status.idle":"2023-11-23T22:36:56.610351Z","shell.execute_reply.started":"2023-11-23T22:36:56.603735Z","shell.execute_reply":"2023-11-23T22:36:56.609102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:36:56.616340Z","iopub.execute_input":"2023-11-23T22:36:56.616755Z","iopub.status.idle":"2023-11-23T22:36:56.625625Z","shell.execute_reply.started":"2023-11-23T22:36:56.616715Z","shell.execute_reply":"2023-11-23T22:36:56.624865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Menyiapkan Dataset untuk training**","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv(\"../input/digit-recognizer/train.csv\")\nprint(train.shape)\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:36:56.627460Z","iopub.execute_input":"2023-11-23T22:36:56.627780Z","iopub.status.idle":"2023-11-23T22:36:59.412398Z","shell.execute_reply.started":"2023-11-23T22:36:56.627751Z","shell.execute_reply":"2023-11-23T22:36:59.411490Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Ukuran dari datset ini adalah 42000 Baris dan 785 kolom.","metadata":{}},{"cell_type":"markdown","source":"**Menyiapkan dataset untuk testing**","metadata":{}},{"cell_type":"code","source":"# read test \ntest= pd.read_csv(\"../input/digit-recognizer/test.csv\")\nprint(test.shape)\ntest.head()","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:36:59.414096Z","iopub.execute_input":"2023-11-23T22:36:59.414616Z","iopub.status.idle":"2023-11-23T22:37:01.121414Z","shell.execute_reply.started":"2023-11-23T22:36:59.414585Z","shell.execute_reply":"2023-11-23T22:37:01.120148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Tahap Pre-Processing","metadata":{}},{"cell_type":"markdown","source":"**Memisah antara label dan juga fitur**","metadata":{}},{"cell_type":"code","source":"Y_train = train[\"label\"]\nX_train = train.drop(labels = [\"label\"],axis = 1) ","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:01.122735Z","iopub.execute_input":"2023-11-23T22:37:01.123189Z","iopub.status.idle":"2023-11-23T22:37:01.213299Z","shell.execute_reply.started":"2023-11-23T22:37:01.123153Z","shell.execute_reply":"2023-11-23T22:37:01.212338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Visualisasi distribusi masing masing label**","metadata":{}},{"cell_type":"code","source":"sns.countplot(train, x=\"label\")","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:01.216741Z","iopub.execute_input":"2023-11-23T22:37:01.217790Z","iopub.status.idle":"2023-11-23T22:37:01.453933Z","shell.execute_reply.started":"2023-11-23T22:37:01.217727Z","shell.execute_reply":"2023-11-23T22:37:01.453073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Sample data**","metadata":{}},{"cell_type":"code","source":"sample_img = X_train.iloc[113].values\nsample_img = sample_img.reshape((28,28))\nplt.imshow(sample_img, cmap='gray')\nplt.axis(\"off\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:01.455384Z","iopub.execute_input":"2023-11-23T22:37:01.455979Z","iopub.status.idle":"2023-11-23T22:37:01.520768Z","shell.execute_reply.started":"2023-11-23T22:37:01.455947Z","shell.execute_reply":"2023-11-23T22:37:01.520009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Normalisasi\n\nKami melakukan normalisasi tingkat grayscale untuk mengurangi pengaruh perbedaan pencahayaan.\nJika kami melakukan normalisasi, CNN akan bekerja lebih cepat.","metadata":{}},{"cell_type":"code","source":"X_train = X_train / 255.0\nnew_test = test/255.0\nprint('Shape X_train : ', X_train.shape)\nprint('Shape test: ', new_test.shape)","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:01.522762Z","iopub.execute_input":"2023-11-23T22:37:01.523601Z","iopub.status.idle":"2023-11-23T22:37:01.672640Z","shell.execute_reply.started":"2023-11-23T22:37:01.523557Z","shell.execute_reply":"2023-11-23T22:37:01.671761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Reshaping\n\nGambar-gambar data training dan testing dengan ukuran (28 x 28)\nKami melakukan reshaping pada semua data menjadi matriks 3D berukuran 28x28x1.\nKeras memerlukan dimensi tambahan di bagian akhir yang sesuai dengan saluran. Gambar-gambar kami berwarna abu-abu sehingga hanya menggunakan satu saluran.","metadata":{}},{"cell_type":"code","source":"X_train = X_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)\nprint(\"x_train shape: \",X_train.shape)\nprint(\"test shape: \",test.shape)","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:01.673514Z","iopub.execute_input":"2023-11-23T22:37:01.673797Z","iopub.status.idle":"2023-11-23T22:37:01.680419Z","shell.execute_reply.started":"2023-11-23T22:37:01.673770Z","shell.execute_reply":"2023-11-23T22:37:01.679563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Label Encoding\n","metadata":{}},{"cell_type":"code","source":"from keras.utils import to_categorical # convert to one-hot-encoding\nY_train = to_categorical(Y_train)","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:01.681785Z","iopub.execute_input":"2023-11-23T22:37:01.682582Z","iopub.status.idle":"2023-11-23T22:37:01.692252Z","shell.execute_reply.started":"2023-11-23T22:37:01.682548Z","shell.execute_reply":"2023-11-23T22:37:01.691090Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train Test Split\n\nSize data testing adalah 20 %.\nSize data training adalah 80%.","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"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.2, random_state=42)\nprint(\"x_train shape\",X_train.shape)\nprint(\"x_test shape\",X_val.shape)\nprint(\"y_train shape\",Y_train.shape)\nprint(\"y_test shape\",Y_val.shape)","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:01.693717Z","iopub.execute_input":"2023-11-23T22:37:01.694692Z","iopub.status.idle":"2023-11-23T22:37:02.178084Z","shell.execute_reply.started":"2023-11-23T22:37:01.694645Z","shell.execute_reply":"2023-11-23T22:37:02.176951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(X_train[333][:,:,0],cmap='gray')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:02.181212Z","iopub.execute_input":"2023-11-23T22:37:02.181578Z","iopub.status.idle":"2023-11-23T22:37:02.427454Z","shell.execute_reply.started":"2023-11-23T22:37:02.181546Z","shell.execute_reply":"2023-11-23T22:37:02.425593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Membuat Modedl CNN","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom keras.utils import to_categorical # convert to one-hot-encoding\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop,Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\n\nmodel = Sequential()\n#\nmodel.add(Conv2D(filters = 8, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n#\nmodel.add(Conv2D(filters = 16, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\n# fully connected\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = \"softmax\"))","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:02.429577Z","iopub.execute_input":"2023-11-23T22:37:02.430014Z","iopub.status.idle":"2023-11-23T22:37:02.541034Z","shell.execute_reply.started":"2023-11-23T22:37:02.429978Z","shell.execute_reply":"2023-11-23T22:37:02.539347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999)","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:02.542517Z","iopub.execute_input":"2023-11-23T22:37:02.543350Z","iopub.status.idle":"2023-11-23T22:37:02.552880Z","shell.execute_reply.started":"2023-11-23T22:37:02.543292Z","shell.execute_reply":"2023-11-23T22:37:02.551710Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer = optimizer , loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:02.554118Z","iopub.execute_input":"2023-11-23T22:37:02.554469Z","iopub.status.idle":"2023-11-23T22:37:02.567756Z","shell.execute_reply.started":"2023-11-23T22:37:02.554430Z","shell.execute_reply":"2023-11-23T22:37:02.566662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Menentukan jumlah epoch dan batch**","metadata":{}},{"cell_type":"code","source":"epochs = 10  # for better result increase the epochs\nbatch_size = 250","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:02.569132Z","iopub.execute_input":"2023-11-23T22:37:02.569598Z","iopub.status.idle":"2023-11-23T22:37:02.576234Z","shell.execute_reply.started":"2023-11-23T22:37:02.569557Z","shell.execute_reply":"2023-11-23T22:37:02.573670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Data Augmentation**","metadata":{}},{"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=5,  # randomly rotate images in the range 5 degrees\n        zoom_range = 0.1, # Randomly zoom image 10%\n        width_shift_range=0.1,  # randomly shift images horizontally 10%\n        height_shift_range=0.1,  # randomly shift images vertically 10%\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\ndatagen.fit(X_train)","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:02.577458Z","iopub.execute_input":"2023-11-23T22:37:02.577843Z","iopub.status.idle":"2023-11-23T22:37:02.701586Z","shell.execute_reply.started":"2023-11-23T22:37:02.577795Z","shell.execute_reply":"2023-11-23T22:37:02.700220Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Fitting Model**","metadata":{}},{"cell_type":"code","source":"# Fit the model\nhistory = model.fit_generator(datagen.flow(X_train,Y_train, batch_size=batch_size),\n                              epochs = epochs, validation_data = (X_val,Y_val), steps_per_epoch=X_train.shape[0] // batch_size)","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:37:02.703148Z","iopub.execute_input":"2023-11-23T22:37:02.703506Z","iopub.status.idle":"2023-11-23T22:40:18.054037Z","shell.execute_reply.started":"2023-11-23T22:37:02.703476Z","shell.execute_reply":"2023-11-23T22:40:18.052868Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Evaluasi Model CNN**","metadata":{}},{"cell_type":"code","source":"# Plot the loss and accuracy curves for training and validation \nplt.plot(history.history['val_loss'], color='b', label=\"validation loss\")\nplt.title(\"Test Loss\")\nplt.xlabel(\"Number of Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:41:16.355710Z","iopub.execute_input":"2023-11-23T22:41:16.356390Z","iopub.status.idle":"2023-11-23T22:41:16.659978Z","shell.execute_reply.started":"2023-11-23T22:41:16.356347Z","shell.execute_reply":"2023-11-23T22:41:16.658894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Confusion Matrix**","metadata":{}},{"cell_type":"code","source":"# confusion matrix\nimport seaborn as sns\n# Predict the values from the validation dataset\nY_pred = model.predict(X_val)\n# Convert predictions classes to one hot vectors \nY_pred_classes = np.argmax(Y_pred,axis = 1) \n# Convert validation observations to one hot vectors\nY_true = np.argmax(Y_val,axis = 1) \n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \n# plot the confusion matrix\nf,ax = plt.subplots(figsize=(8, 8))\nsns.heatmap(confusion_mtx, annot=True, linewidths=0.01,cmap=\"Greens\",linecolor=\"gray\", fmt= '.1f',ax=ax)\nplt.xlabel(\"Predicted Label\")\nplt.ylabel(\"True Label\")\nplt.title(\"Confusion Matrix\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-23T22:41:38.855437Z","iopub.execute_input":"2023-11-23T22:41:38.855878Z","iopub.status.idle":"2023-11-23T22:41:41.302001Z","shell.execute_reply.started":"2023-11-23T22:41:38.855843Z","shell.execute_reply":"2023-11-23T22:41:41.301026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}