{"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"}],"dockerImageVersionId":30648,"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-02-06T21:42:25.702877Z","iopub.execute_input":"2024-02-06T21:42:25.703230Z","iopub.status.idle":"2024-02-06T21:42:26.882970Z","shell.execute_reply.started":"2024-02-06T21:42:25.703201Z","shell.execute_reply":"2024-02-06T21:42:26.881986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install tensorflow","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:42:26.884399Z","iopub.execute_input":"2024-02-06T21:42:26.884806Z","iopub.status.idle":"2024-02-06T21:42:40.670680Z","shell.execute_reply.started":"2024-02-06T21:42:26.884779Z","shell.execute_reply":"2024-02-06T21:42:40.669747Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # Suppress TensorFlow info and warning messages\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization\nfrom keras.datasets import mnist\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import LearningRateScheduler\nimport warnings\n\n# Ignore warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:42:40.672085Z","iopub.execute_input":"2024-02-06T21:42:40.672391Z","iopub.status.idle":"2024-02-06T21:42:56.096991Z","shell.execute_reply.started":"2024-02-06T21:42:40.672363Z","shell.execute_reply":"2024-02-06T21:42:56.096129Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('../input/digit-recognizer/train.csv')\ntest = pd.read_csv('../input/digit-recognizer/test.csv')\ntraining_data = pd.read_csv('../input/digit-recognizer/train.csv')","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:42:56.099323Z","iopub.execute_input":"2024-02-06T21:42:56.099894Z","iopub.status.idle":"2024-02-06T21:43:03.968606Z","shell.execute_reply.started":"2024-02-06T21:42:56.099865Z","shell.execute_reply":"2024-02-06T21:43:03.967807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"(X_train, y_train), (X_test, y_test) = mnist.load_data()\nX_train = np.vstack((X_train, X_test))\ny_train = np.concatenate([y_train, y_test])\nX_train = X_train.reshape(-1, 28, 28, 1)\nprint(X_train.shape, y_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:43:03.969810Z","iopub.execute_input":"2024-02-06T21:43:03.970156Z","iopub.status.idle":"2024-02-06T21:43:04.450981Z","shell.execute_reply.started":"2024-02-06T21:43:03.970124Z","shell.execute_reply":"2024-02-06T21:43:04.450043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv').values\ny_val = train[:,0].astype('int32')\nX_val = train[:,1:].astype('float32')\nX_val = X_val.reshape(-1,28,28,1)\nprint(X_val.shape, y_val.shape)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:43:04.452271Z","iopub.execute_input":"2024-02-06T21:43:04.452634Z","iopub.status.idle":"2024-02-06T21:43:07.023852Z","shell.execute_reply.started":"2024-02-06T21:43:04.452600Z","shell.execute_reply":"2024-02-06T21:43:07.022921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(figsize=(20,20))\nfor i in range(6):\n    ax = fig.add_subplot(1, 6, i+1, xticks=[], yticks=[])\n    ax.imshow(X_train[i].reshape(28,28), cmap='gray')\n    ax.set_title(str(y_train[i]))","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:43:07.025086Z","iopub.execute_input":"2024-02-06T21:43:07.025372Z","iopub.status.idle":"2024-02-06T21:43:07.417610Z","shell.execute_reply.started":"2024-02-06T21:43:07.025345Z","shell.execute_reply":"2024-02-06T21:43:07.416674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train = X_train.astype('float32')/255\nX_val = X_val.astype('float32')/255\nX_test = X_test.astype('float32')/255","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:43:07.418831Z","iopub.execute_input":"2024-02-06T21:43:07.419092Z","iopub.status.idle":"2024-02-06T21:43:07.566947Z","shell.execute_reply.started":"2024-02-06T21:43:07.419069Z","shell.execute_reply":"2024-02-06T21:43:07.565866Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.utils import to_categorical\n\n# Assuming y_train and y_val are your label arrays\ny_train = to_categorical(y_train, num_classes=10)\ny_val = to_categorical(y_val, num_classes=10)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:43:07.568353Z","iopub.execute_input":"2024-02-06T21:43:07.569124Z","iopub.status.idle":"2024-02-06T21:43:07.576083Z","shell.execute_reply.started":"2024-02-06T21:43:07.569086Z","shell.execute_reply":"2024-02-06T21:43:07.575201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D\n\n# define the model\nmodel = Sequential()\nmodel.add(Conv2D(filters=64, kernel_size=3, padding='same', activation='relu', input_shape=(28,28,1)))\nmodel.add(Conv2D(filters=64, kernel_size=3, padding='same', activation='relu'))\nmodel.add(Conv2D(filters=128, kernel_size=3, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=128, kernel_size=3, padding='same', activation='relu'))\nmodel.add(Conv2D(filters=192, kernel_size=3, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=192, kernel_size=5, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2, padding='same'))\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(10, activation='softmax'))\n# summarize the model\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:43:07.579184Z","iopub.execute_input":"2024-02-06T21:43:07.579550Z","iopub.status.idle":"2024-02-06T21:43:08.615564Z","shell.execute_reply.started":"2024-02-06T21:43:07.579525Z","shell.execute_reply":"2024-02-06T21:43:08.614630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:43:08.616802Z","iopub.execute_input":"2024-02-06T21:43:08.617080Z","iopub.status.idle":"2024-02-06T21:43:08.635453Z","shell.execute_reply.started":"2024-02-06T21:43:08.617056Z","shell.execute_reply":"2024-02-06T21:43:08.634594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint   \nfrom keras.callbacks import ReduceLROnPlateau\n\n# train the model\n#checkpointer = ModelCheckpoint(filepath='mnist.model.best.hdf5', \n#                               verbose=1, save_best_only=True)\nreduce_lr = ReduceLROnPlateau(monitor='loss', factor=0.3, verbose=1,\n                              patience=2, min_lr=0.00000001)\nhist = model.fit(X_train, y_train, batch_size=100, epochs=25,\n          validation_data=(X_val, y_val), callbacks=[reduce_lr],\n          verbose=1, shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:43:08.636556Z","iopub.execute_input":"2024-02-06T21:43:08.636836Z","iopub.status.idle":"2024-02-06T21:52:51.507312Z","shell.execute_reply.started":"2024-02-06T21:43:08.636811Z","shell.execute_reply":"2024-02-06T21:52:51.506440Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Assuming you have already defined and compiled your model as 'model'\n\n# Make predictions on the test data\npredictions = model.predict(X_test, verbose=2)\n\n# Extract the class labels by finding the index of the maximum probability for each prediction\ntestY = predictions.argmax(axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:52:51.508592Z","iopub.execute_input":"2024-02-06T21:52:51.509548Z","iopub.status.idle":"2024-02-06T21:52:53.772325Z","shell.execute_reply.started":"2024-02-06T21:52:51.509518Z","shell.execute_reply":"2024-02-06T21:52:53.771192Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:52:53.774041Z","iopub.execute_input":"2024-02-06T21:52:53.774404Z","iopub.status.idle":"2024-02-06T21:52:55.249196Z","shell.execute_reply.started":"2024-02-06T21:52:53.774377Z","shell.execute_reply":"2024-02-06T21:52:55.248091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test = test.values.astype('float32')\nX_test = X_test.reshape(-1, 28, 28, 1)\nX_test /= 255","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:52:55.250486Z","iopub.execute_input":"2024-02-06T21:52:55.250837Z","iopub.status.idle":"2024-02-06T21:52:55.299928Z","shell.execute_reply.started":"2024-02-06T21:52:55.250809Z","shell.execute_reply":"2024-02-06T21:52:55.299110Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(X_test, verbose=2)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:52:55.301041Z","iopub.execute_input":"2024-02-06T21:52:55.301334Z","iopub.status.idle":"2024-02-06T21:52:59.225654Z","shell.execute_reply.started":"2024-02-06T21:52:55.301309Z","shell.execute_reply":"2024-02-06T21:52:59.224513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({'ImageId': np.arange(1, len(predictions) + 1), 'Label': predictions.argmax(axis=1)})","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:52:59.227178Z","iopub.execute_input":"2024-02-06T21:52:59.227498Z","iopub.status.idle":"2024-02-06T21:52:59.233334Z","shell.execute_reply.started":"2024-02-06T21:52:59.227471Z","shell.execute_reply":"2024-02-06T21:52:59.232358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T21:52:59.234414Z","iopub.execute_input":"2024-02-06T21:52:59.234704Z","iopub.status.idle":"2024-02-06T21:52:59.279406Z","shell.execute_reply.started":"2024-02-06T21:52:59.234666Z","shell.execute_reply":"2024-02-06T21:52:59.278694Z"},"trusted":true},"execution_count":null,"outputs":[]}]}