{"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":30918,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten\nfrom tensorflow.keras.optimizers import Adam\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-18T13:53:32.873029Z","iopub.execute_input":"2025-03-18T13:53:32.873468Z","iopub.status.idle":"2025-03-18T13:53:50.568065Z","shell.execute_reply.started":"2025-03-18T13:53:32.873437Z","shell.execute_reply":"2025-03-18T13:53:50.566863Z"}},"outputs":[],"execution_count":null},{"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":{"iopub.status.busy":"2025-03-18T13:53:50.569700Z","iopub.execute_input":"2025-03-18T13:53:50.570440Z","iopub.status.idle":"2025-03-18T13:53:50.579153Z","shell.execute_reply.started":"2025-03-18T13:53:50.570401Z","shell.execute_reply":"2025-03-18T13:53:50.577727Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load data dari Kaggle\ntrain_df = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest_df = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n\n# Lihat 5 data pertama\ntrain_df.head()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-18T13:53:50.581395Z","iopub.execute_input":"2025-03-18T13:53:50.581802Z","iopub.status.idle":"2025-03-18T13:53:56.127324Z","shell.execute_reply.started":"2025-03-18T13:53:50.581771Z","shell.execute_reply":"2025-03-18T13:53:56.125861Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Pisahkan fitur dan label dari data pelatihan\nX_train = train_df.drop(columns=['label']).values\ny_train = train_df['label'].values\n\n# Konversi data ke bentuk array numpy\nX_test = test_df.values\n\n# Normalisasi pixel ke rentang [0,1]\nX_train = X_train / 255.0\nX_test = X_test / 255.0\n\n# Ubah label menjadi one-hot encoding\ny_train = keras.utils.to_categorical(y_train, num_classes=10)\n\n# Reshape input ke bentuk gambar 28x28 (Tidak diperlukan untuk MLP, tapi untuk pemahaman)\nX_train = X_train.reshape(-1, 28*28)  # MLP butuh input dalam bentuk vektor 1D\nX_test = X_test.reshape(-1, 28*28)\n\nprint(f\"Shape X_train: {X_train.shape}, y_train: {y_train.shape}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-18T13:53:56.128663Z","iopub.execute_input":"2025-03-18T13:53:56.128984Z","iopub.status.idle":"2025-03-18T13:53:56.478928Z","shell.execute_reply.started":"2025-03-18T13:53:56.128948Z","shell.execute_reply":"2025-03-18T13:53:56.477530Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Bangun model MLP\n# Perbaikan kode model MLP\nmodel = Sequential([\n    keras.Input(shape=(784,)),  # Definisikan input layer secara eksplisit\n    Dense(512, activation='relu'),  # Hidden layer pertama\n    Dense(256, activation='relu'),  # Hidden layer kedua\n    Dense(128, activation='relu'),  # Hidden layer ketiga\n    Dense(10, activation='softmax')  # Output layer untuk klasifikasi 10 kelas\n])\n\n# Compile model\nmodel.compile(optimizer=Adam(learning_rate=0.001),\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n\n# Ringkasan model\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-18T13:53:56.480365Z","iopub.execute_input":"2025-03-18T13:53:56.480735Z","iopub.status.idle":"2025-03-18T13:53:56.615360Z","shell.execute_reply.started":"2025-03-18T13:53:56.480706Z","shell.execute_reply":"2025-03-18T13:53:56.614383Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Latih model dengan 10 epoch dan batch_size=32\nhistory = model.fit(X_train, y_train, epochs=10, batch_size=32, validation_split=0.2)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-18T13:53:56.616414Z","iopub.execute_input":"2025-03-18T13:53:56.616710Z","iopub.status.idle":"2025-03-18T13:55:27.366353Z","shell.execute_reply.started":"2025-03-18T13:53:56.616685Z","shell.execute_reply":"2025-03-18T13:55:27.365273Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plot loss dan akurasi\nplt.figure(figsize=(12, 4))\n\n# Plot akurasi\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.title('Akurasi Model')\n\n# Plot loss\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.title('Loss Model')\n\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-18T13:57:58.833345Z","iopub.execute_input":"2025-03-18T13:57:58.833780Z","iopub.status.idle":"2025-03-18T13:57:59.321387Z","shell.execute_reply.started":"2025-03-18T13:57:58.833750Z","shell.execute_reply":"2025-03-18T13:57:59.320336Z"}},"outputs":[],"execution_count":null}]}