{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","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":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":{"iopub.status.busy":"2025-06-05T17:32:56.349349Z","iopub.execute_input":"2025-06-05T17:32:56.349819Z","iopub.status.idle":"2025-06-05T17:32:56.714865Z","shell.execute_reply.started":"2025-06-05T17:32:56.349791Z","shell.execute_reply":"2025-06-05T17:32:56.713786Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load training and testing datasets\ntrain_data = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T17:33:00.047264Z","iopub.execute_input":"2025-06-05T17:33:00.048057Z","iopub.status.idle":"2025-06-05T17:33:07.672838Z","shell.execute_reply.started":"2025-06-05T17:33:00.048005Z","shell.execute_reply":"2025-06-05T17:33:07.671757Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\n\n# === Assume train_data and test_data are already loaded as DataFrames ===\n# train_data has 785 columns: 'label' + pixel0..pixel783\n# test_data has 784 columns: pixel0..pixel783\n\n# Split training data\nlabel_col = 'label'\nX_train = train_data.drop(columns=[label_col]).values\ny_train = train_data[label_col].values\n\n# Test data (no labels in test_data)\nX_test = test_data.values\n\n# One-hot encode the labels\ny_train = tf.keras.utils.to_categorical(y_train)\n\n# Standardize features\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\n# Define the neural network model\nmodel = tf.keras.Sequential([\n    tf.keras.layers.Dense(128, activation='relu', input_shape=(X_train.shape[1],)),  # Corrected shape\n    tf.keras.layers.Dense(64, activation='relu'),\n    tf.keras.layers.Dense(y_train.shape[1], activation='softmax')\n])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Train the model\nhistory = model.fit(X_train, y_train, epochs=25, batch_size=32, validation_split=0.2, verbose=1)\n\n# --- If you have true test labels, add them here ---\n# Example:\n# y_test = pd.read_csv('test_labels.csv')['label'].values\n# y_test = tf.keras.utils.to_categorical(y_test)\n# loss, accuracy = model.evaluate(X_test, y_test)\n\n# For now, just print prediction samples (if y_test not available)\ndef visualize_predictions(model, X, num_samples=5):\n    predictions = model.predict(X)\n    y_pred = np.argmax(predictions, axis=1)\n\n    for i in range(num_samples):\n        print(f\"Sample {i+1}\")\n        print(f\"Predicted Label: {y_pred[i]}\")\n        print()\n\nvisualize_predictions(model, X_test[:5])\n\n# Plot training history\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Model Accuracy Over Epochs')\nplt.legend()\nplt.show()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T17:33:23.968198Z","iopub.execute_input":"2025-06-05T17:33:23.968530Z","iopub.status.idle":"2025-06-05T17:35:32.147845Z","shell.execute_reply.started":"2025-06-05T17:33:23.968509Z","shell.execute_reply":"2025-06-05T17:35:32.146983Z"}},"outputs":[],"execution_count":null}]}