{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","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":30698,"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)\nimport tensorflow as tf \nfrom sklearn.model_selection import train_test_split\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","execution":{"iopub.status.busy":"2024-05-27T13:46:14.461226Z","iopub.execute_input":"2024-05-27T13:46:14.462180Z","iopub.status.idle":"2024-05-27T13:46:14.471299Z","shell.execute_reply.started":"2024-05-27T13:46:14.462137Z","shell.execute_reply":"2024-05-27T13:46:14.470236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Preparation","metadata":{}},{"cell_type":"markdown","source":"### Importing Datasets\n","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-05-27T13:46:16.742845Z","iopub.execute_input":"2024-05-27T13:46:16.743236Z","iopub.status.idle":"2024-05-27T13:46:20.979086Z","shell.execute_reply.started":"2024-05-27T13:46:16.743206Z","shell.execute_reply":"2024-05-27T13:46:20.978258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Data Preprocessing","metadata":{}},{"cell_type":"code","source":"y = train['label'] # defining our target variable\nx = train.drop(['label'] , axis = 1) # creating the input variable for the classification","metadata":{"execution":{"iopub.status.busy":"2024-05-27T13:46:28.554254Z","iopub.execute_input":"2024-05-27T13:46:28.554769Z","iopub.status.idle":"2024-05-27T13:46:28.639677Z","shell.execute_reply.started":"2024-05-27T13:46:28.554733Z","shell.execute_reply":"2024-05-27T13:46:28.638698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"normalized_x = x.astype('float32')/255.0 # normalizing our input data to make the result more numerically stable","metadata":{"execution":{"iopub.status.busy":"2024-05-27T13:46:32.599868Z","iopub.execute_input":"2024-05-27T13:46:32.600331Z","iopub.status.idle":"2024-05-27T13:46:32.715484Z","shell.execute_reply.started":"2024-05-27T13:46:32.600299Z","shell.execute_reply":"2024-05-27T13:46:32.714445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Split the normalized input features and target variable into training and validation sets,\n# with 10% of the data reserved for validation, ensuring consistency with a random seed of 10\n# and shuffling the data before splitting.\nx_train,x_val,y_train,y_val = train_test_split(normalized_x, y, test_size=0.1, random_state=10, shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:35:09.272515Z","iopub.execute_input":"2024-05-27T14:35:09.273335Z","iopub.status.idle":"2024-05-27T14:35:09.528769Z","shell.execute_reply.started":"2024-05-27T14:35:09.273274Z","shell.execute_reply":"2024-05-27T14:35:09.527687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train.shape # checking the shape of x_train","metadata":{"execution":{"iopub.status.busy":"2024-05-27T13:46:32.945479Z","iopub.execute_input":"2024-05-27T13:46:32.945784Z","iopub.status.idle":"2024-05-27T13:46:32.951797Z","shell.execute_reply.started":"2024-05-27T13:46:32.945758Z","shell.execute_reply":"2024-05-27T13:46:32.950795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reshape x_train and x_val using NumPy arrays obtained from Pandas DataFrames to make it suitable for the model.\nx_train_np = x_train.values.reshape(-1, 28, 28, 1)\nx_val_np = x_val.values.reshape(-1, 28, 28, 1)\n\n# Ensure y_train and y_val are numpy arrays if they are not already\ny_train_np = y_train.values if isinstance(y_train, pd.DataFrame) else y_train\ny_val_np = y_val.values if isinstance(y_val, pd.DataFrame) else y_val","metadata":{"_kg_hide-output":false,"execution":{"iopub.status.busy":"2024-05-27T13:46:33.050273Z","iopub.execute_input":"2024-05-27T13:46:33.051174Z","iopub.status.idle":"2024-05-27T13:46:33.056764Z","shell.execute_reply.started":"2024-05-27T13:46:33.051139Z","shell.execute_reply":"2024-05-27T13:46:33.055632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"-------------------------","metadata":{}},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"markdown","source":"### Model outline\n","metadata":{}},{"cell_type":"code","source":"# Define the sizes of the input, output, and hidden layers for the neural network.\ninput_size = 784\noutput_size = 10\nhidden_layer_size = 200\n\n# Creating the model\n# - Flatten layer to flatten the input images into 1D arrays.\n# - Two dense (fully connected) layers with ReLU activation function for feature extraction.\n# - Final dense layer with softmax activation function for classification, outputting probabilities for each class.\nmodel = tf.keras.Sequential([\n                            tf.keras.layers.Flatten(input_shape=(28,28,1)), # flatten the input images into 1D arrays.\n                            tf.keras.layers.Dense(hidden_layer_size, activation='relu'),\n                            tf.keras.layers.Dense(hidden_layer_size, activation='relu'),\n                            tf.keras.layers.Dense(output_size, activation='softmax')   \n                            ])","metadata":{"execution":{"iopub.status.busy":"2024-05-27T13:48:30.800105Z","iopub.execute_input":"2024-05-27T13:48:30.800848Z","iopub.status.idle":"2024-05-27T13:48:30.835611Z","shell.execute_reply.started":"2024-05-27T13:48:30.800816Z","shell.execute_reply":"2024-05-27T13:48:30.834834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile the model with the Adam optimizer, sparse categorical crossentropy loss function,\n# and accuracy metric for evaluation.\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:45:33.481409Z","iopub.execute_input":"2024-05-27T14:45:33.482461Z","iopub.status.idle":"2024-05-27T14:45:33.504182Z","shell.execute_reply.started":"2024-05-27T14:45:33.482425Z","shell.execute_reply":"2024-05-27T14:45:33.503264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training","metadata":{}},{"cell_type":"code","source":"num_epochs = 8 # Defining the number of epochs\n\nmodel.fit(x_train_np, y_train_np, epochs = num_epochs, validation_data=(x_val_np, y_val_np), verbose=2) # Training the model","metadata":{"execution":{"iopub.status.busy":"2024-05-27T13:48:31.062784Z","iopub.execute_input":"2024-05-27T13:48:31.063127Z","iopub.status.idle":"2024-05-27T13:48:56.059077Z","shell.execute_reply.started":"2024-05-27T13:48:31.063087Z","shell.execute_reply":"2024-05-27T13:48:56.058124Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Model Summary","metadata":{}},{"cell_type":"code","source":"print(model.summary())","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:47:12.170562Z","iopub.execute_input":"2024-05-27T14:47:12.171228Z","iopub.status.idle":"2024-05-27T14:47:12.197760Z","shell.execute_reply.started":"2024-05-27T14:47:12.171197Z","shell.execute_reply":"2024-05-27T14:47:12.196743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"-------------------","metadata":{}},{"cell_type":"markdown","source":"# Testing","metadata":{}},{"cell_type":"code","source":"# Preparing our test data for prediction\ntest_data_np = test.values.reshape(-1, 28, 28, 1).astype('float32')/255.0\ntest_data_np.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:07:37.129804Z","iopub.execute_input":"2024-05-27T14:07:37.130516Z","iopub.status.idle":"2024-05-27T14:07:37.182349Z","shell.execute_reply.started":"2024-05-27T14:07:37.130483Z","shell.execute_reply":"2024-05-27T14:07:37.181337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Test data shape:\", test_data_np.shape)\nprint(\"Test data type:\", test_data_np.dtype)","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:07:37.302943Z","iopub.execute_input":"2024-05-27T14:07:37.303827Z","iopub.status.idle":"2024-05-27T14:07:37.308749Z","shell.execute_reply.started":"2024-05-27T14:07:37.303795Z","shell.execute_reply":"2024-05-27T14:07:37.307802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Predict labels for the test data\npredictions = model.predict(test_data_np)\n\n# Convert predicted probabilities to class labels\npredicted_labels = np.argmax(predictions, axis=1)\n\nprint(\"Predicted labels:\", predicted_labels[:10]) \n","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:48:37.101375Z","iopub.execute_input":"2024-05-27T14:48:37.102418Z","iopub.status.idle":"2024-05-27T14:48:39.222697Z","shell.execute_reply.started":"2024-05-27T14:48:37.102384Z","shell.execute_reply":"2024-05-27T14:48:39.221688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output_df = pd.DataFrame({'ImageId': range(1, len(predicted_labels) + 1), 'Label': predicted_labels})\noutput_df.to_csv('predicted_labels.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-05-27T14:56:34.466852Z","iopub.execute_input":"2024-05-27T14:56:34.467804Z","iopub.status.idle":"2024-05-27T14:56:34.518511Z","shell.execute_reply.started":"2024-05-27T14:56:34.467770Z","shell.execute_reply":"2024-05-27T14:56:34.517595Z"},"trusted":true},"execution_count":null,"outputs":[]}]}