{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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","execution":{"iopub.status.busy":"2024-07-16T21:04:54.50097Z","iopub.execute_input":"2024-07-16T21:04:54.501469Z","iopub.status.idle":"2024-07-16T21:04:54.517084Z","shell.execute_reply.started":"2024-07-16T21:04:54.501432Z","shell.execute_reply":"2024-07-16T21:04:54.51578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Define a simple ResNet block\ndef resnet_block(input_tensor, filters, kernel_size=3):\n    x = layers.Conv2D(filters, kernel_size, padding='same', activation='relu')(input_tensor)\n    x = layers.Conv2D(filters, kernel_size, padding='same', activation=None)(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Add()([x, input_tensor])\n    x = layers.Activation('relu')(x)\n    return x\n\n# Classical CNN model with additional convolutional layer and ResNet blocks\ndef create_classical_model():\n    inputs = layers.Input(shape=(28, 28, 1))\n    x = layers.Conv2D(32, (3, 3), activation='relu')(inputs)\n    x = layers.MaxPooling2D((2, 2))(x)\n    x = layers.Conv2D(64, (3, 3), activation='relu')(x)\n    x = layers.MaxPooling2D((2, 2))(x)\n    x = layers.Conv2D(128, (3, 3), activation='relu')(x)\n    x = layers.MaxPooling2D((2, 2))(x)\n    \n    # ResNet blocks\n    x = resnet_block(x, 128)\n    x = resnet_block(x, 128)\n\n    x = layers.Flatten()(x)\n    x = layers.Dense(64, activation='relu')(x)\n    x = layers.Dense(10, activation='softmax')(x)\n    model = tf.keras.Model(inputs=inputs, outputs=x)\n    return model\n\nclassical_model = create_classical_model()\n\n# Load MNIST dataset\nmnist = tf.keras.datasets.mnist\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train = x_train[..., tf.newaxis] / 255.0\nx_test = x_test[..., tf.newaxis] / 255.0\n\n# Compile and train the model\nclassical_model.compile(optimizer='adam',\n                        loss='sparse_categorical_crossentropy',\n                        metrics=['accuracy'])\n\nclassical_model.fit(x_train, y_train, epochs=30, batch_size=64, validation_split=0.1)\n\n# Evaluate the model\ntest_loss, test_acc = classical_model.evaluate(x_test, y_test, verbose=2)\nprint(f'Test accuracy: {test_acc}')\n\n# Load test dataset for submission\ndf_test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\npredictions = classical_model.predict(df_test.values.reshape(-1, 28, 28, 1) / 255.0)\npredicted_labels = np.argmax(predictions, axis=1)\n\nprint(\"Predictions:\")\nprint(predicted_labels)\n\nsubmission = pd.DataFrame({'ImageId': list(range(1, len(predicted_labels) + 1)),\n                           'Label': predicted_labels})\nsubmission.to_csv('submission.csv', index=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-07-23T08:18:11.412698Z","iopub.execute_input":"2024-07-23T08:18:11.413418Z","iopub.status.idle":"2024-07-23T08:19:58.212394Z","shell.execute_reply.started":"2024-07-23T08:18:11.413387Z","shell.execute_reply":"2024-07-23T08:19:58.211452Z"},"trusted":true},"execution_count":null,"outputs":[]}]}