{"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":30587,"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 matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport matplotlib.image as mpimg\n%matplotlib inline\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 itertools\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":"2023-12-07T16:29:29.508858Z","iopub.execute_input":"2023-12-07T16:29:29.510145Z","iopub.status.idle":"2023-12-07T16:29:30.222494Z","shell.execute_reply.started":"2023-12-07T16:29:29.510106Z","shell.execute_reply":"2023-12-07T16:29:30.220962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Load the Dataset","metadata":{}},{"cell_type":"code","source":"# read train\ntrain = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\nprint(train.shape)\nprint(test.shape)\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:30.224961Z","iopub.execute_input":"2023-12-07T16:29:30.225630Z","iopub.status.idle":"2023-12-07T16:29:33.450903Z","shell.execute_reply.started":"2023-12-07T16:29:30.225587Z","shell.execute_reply":"2023-12-07T16:29:33.449752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#put labels into y_train variable\n#Y_train = train[\"label\"]\nY_train = train.iloc[:, 0]  # İlk sütunun tüm satırlarını alır\n#Drop label column\nX_train = train.drop(labels=[\"label\"], axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:33.452537Z","iopub.execute_input":"2023-12-07T16:29:33.452829Z","iopub.status.idle":"2023-12-07T16:29:33.515948Z","shell.execute_reply.started":"2023-12-07T16:29:33.452804Z","shell.execute_reply":"2023-12-07T16:29:33.514080Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train.head()","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:33.518040Z","iopub.execute_input":"2023-12-07T16:29:33.518396Z","iopub.status.idle":"2023-12-07T16:29:33.538867Z","shell.execute_reply.started":"2023-12-07T16:29:33.518365Z","shell.execute_reply":"2023-12-07T16:29:33.538105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y_train.head()","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:33.541365Z","iopub.execute_input":"2023-12-07T16:29:33.541907Z","iopub.status.idle":"2023-12-07T16:29:33.556165Z","shell.execute_reply.started":"2023-12-07T16:29:33.541879Z","shell.execute_reply":"2023-12-07T16:29:33.554394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y_train.value_counts()","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:33.557917Z","iopub.execute_input":"2023-12-07T16:29:33.558267Z","iopub.status.idle":"2023-12-07T16:29:33.571667Z","shell.execute_reply.started":"2023-12-07T16:29:33.558237Z","shell.execute_reply":"2023-12-07T16:29:33.569992Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Check for null and missing values","metadata":{}},{"cell_type":"code","source":"# Check the data\nnull_info = X_train.isnull().any().describe()\n\nprint(null_info)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:33.576602Z","iopub.execute_input":"2023-12-07T16:29:33.577614Z","iopub.status.idle":"2023-12-07T16:29:33.594235Z","shell.execute_reply.started":"2023-12-07T16:29:33.577548Z","shell.execute_reply":"2023-12-07T16:29:33.591526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"null_info = test.isnull().any().describe()\nprint(null_info)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:33.596135Z","iopub.execute_input":"2023-12-07T16:29:33.596579Z","iopub.status.idle":"2023-12-07T16:29:33.612144Z","shell.execute_reply.started":"2023-12-07T16:29:33.596544Z","shell.execute_reply":"2023-12-07T16:29:33.609251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot some samples\nimg = X_train.iloc[6].values\nimg = img.reshape((28,28))\nplt.imshow(img, cmap=\"gray\")\nplt.title(train.iloc[6,0])\nplt.axis(\"off\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:33.614399Z","iopub.execute_input":"2023-12-07T16:29:33.614887Z","iopub.status.idle":"2023-12-07T16:29:33.723984Z","shell.execute_reply.started":"2023-12-07T16:29:33.614845Z","shell.execute_reply":"2023-12-07T16:29:33.722466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot some samples\nimg = X_train.iloc[3].values\nimg = img.reshape((28,28))\nplt.imshow(img, cmap=\"gray\")\nplt.title(train.iloc[3,0])\nplt.axis(\"off\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:33.725656Z","iopub.execute_input":"2023-12-07T16:29:33.726385Z","iopub.status.idle":"2023-12-07T16:29:33.826593Z","shell.execute_reply.started":"2023-12-07T16:29:33.726355Z","shell.execute_reply":"2023-12-07T16:29:33.825783Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Normalization\n\n* We perform a grayscale normalization to reduce the effect of illumination's differences.\n\n* Moreover the CNN converg faster on [0..1] data than on [0..255].","metadata":{}},{"cell_type":"code","source":"# normalize the data\nX_train = X_train / 255\ntest = test / 255\nprint(\"x_train shape: \", X_train.shape)\nprint(\"test shape: \", test.shape)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:33.827719Z","iopub.execute_input":"2023-12-07T16:29:33.828622Z","iopub.status.idle":"2023-12-07T16:29:33.926322Z","shell.execute_reply.started":"2023-12-07T16:29:33.828590Z","shell.execute_reply":"2023-12-07T16:29:33.925495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Reshape","metadata":{}},{"cell_type":"code","source":"# reshape\nX_train = X_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)\nprint(\"x_train shape: \", X_train.shape)\nprint(\"test shape: \", test.shape)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:33.927541Z","iopub.execute_input":"2023-12-07T16:29:33.927786Z","iopub.status.idle":"2023-12-07T16:29:33.935516Z","shell.execute_reply.started":"2023-12-07T16:29:33.927762Z","shell.execute_reply":"2023-12-07T16:29:33.933998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Label Encoding\n# Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])\nfrom tensorflow.keras.utils import to_categorical # convert to one-hot-encoding\nY_train = to_categorical(Y_train, num_classes=10)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:33.937265Z","iopub.execute_input":"2023-12-07T16:29:33.938694Z","iopub.status.idle":"2023-12-07T16:29:37.134200Z","shell.execute_reply.started":"2023-12-07T16:29:33.938649Z","shell.execute_reply":"2023-12-07T16:29:37.131321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Labels are 10 digits numbers from 0 to 9. We need to encode these lables to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0]).","metadata":{}},{"cell_type":"code","source":"# train_test_split\nfrom sklearn.model_selection import train_test_split\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size=0.1, random_state=2)\nprint(\"x_train shape: \",X_train.shape)\nprint(\"x_test shape: \",X_val.shape)\nprint(\"y_train shape: \",Y_train.shape)\nprint(\"y_test shape: \",Y_val.shape)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:37.138111Z","iopub.execute_input":"2023-12-07T16:29:37.139238Z","iopub.status.idle":"2023-12-07T16:29:37.423120Z","shell.execute_reply.started":"2023-12-07T16:29:37.139208Z","shell.execute_reply":"2023-12-07T16:29:37.421047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Convolutional Neural Network (CNN)","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom tensorflow.keras.utils import to_categorical  # convert to one-hot encoding\nfrom keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Convolution2D, MaxPooling2D, Conv2D\nfrom keras.optimizers import RMSprop, Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:37.425387Z","iopub.execute_input":"2023-12-07T16:29:37.425820Z","iopub.status.idle":"2023-12-07T16:29:37.433188Z","shell.execute_reply.started":"2023-12-07T16:29:37.425784Z","shell.execute_reply":"2023-12-07T16:29:37.432261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\n#\nmodel.add(Conv2D(filters=32, kernel_size=(5,5), padding=\"Same\",\n                 activation=\"relu\", input_shape=(28,28,1)))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.15))\n\n#\nmodel.add(Conv2D(filters=32, kernel_size=(3,3), padding=\"Same\",\n                activation=\"relu\"))\nmodel.add(Dropout(0.2))\n\n#\nmodel.add(Conv2D(filters=16, kernel_size=(3,3), padding=\"Same\",\n                activation=\"relu\"))\nmodel.add(Dropout(0.2))\n\n# Fully Connected\nmodel.add(Flatten())\nmodel.add(Dense(256, activation=\"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation='softmax'))","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:37.435398Z","iopub.execute_input":"2023-12-07T16:29:37.437015Z","iopub.status.idle":"2023-12-07T16:29:37.600080Z","shell.execute_reply.started":"2023-12-07T16:29:37.436962Z","shell.execute_reply":"2023-12-07T16:29:37.598883Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Define Optimizer","metadata":{}},{"cell_type":"code","source":"optimizer = Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:37.601381Z","iopub.execute_input":"2023-12-07T16:29:37.601702Z","iopub.status.idle":"2023-12-07T16:29:37.612908Z","shell.execute_reply.started":"2023-12-07T16:29:37.601676Z","shell.execute_reply":"2023-12-07T16:29:37.611786Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Compile Model","metadata":{}},{"cell_type":"code","source":"model.compile(optimizer = optimizer, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:37.614751Z","iopub.execute_input":"2023-12-07T16:29:37.615203Z","iopub.status.idle":"2023-12-07T16:29:37.634056Z","shell.execute_reply.started":"2023-12-07T16:29:37.615162Z","shell.execute_reply":"2023-12-07T16:29:37.632962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Epochs and Batch Size","metadata":{}},{"cell_type":"code","source":"epochs = 10\nbatch_size=64","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:37.636031Z","iopub.execute_input":"2023-12-07T16:29:37.636601Z","iopub.status.idle":"2023-12-07T16:29:37.644727Z","shell.execute_reply.started":"2023-12-07T16:29:37.636555Z","shell.execute_reply":"2023-12-07T16:29:37.643725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Data Augmentation","metadata":{}},{"cell_type":"code","source":"# data augmentation\ndatagen = ImageDataGenerator(\n        featurewise_center=False,  # set input mean to 0 over the dataset\n        samplewise_center=False,  # set each sample mean to 0\n        featurewise_std_normalization=False,  # divide inputs by std of the dataset\n        samplewise_std_normalization=False,  # divide each input by its std\n        zca_whitening=False,  # dimesion reduction\n        rotation_range=5,  # randomly rotate images in the range 5 degrees\n        zoom_range = 0.2, # Randomly zoom image 10%\n        width_shift_range=0.2,  # randomly shift images horizontally 10%\n        height_shift_range=0.2,  # randomly shift images vertically 10%\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\ndatagen.fit(X_train)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:37.646901Z","iopub.execute_input":"2023-12-07T16:29:37.647387Z","iopub.status.idle":"2023-12-07T16:29:37.727407Z","shell.execute_reply.started":"2023-12-07T16:29:37.647345Z","shell.execute_reply":"2023-12-07T16:29:37.726318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Fit the Model","metadata":{}},{"cell_type":"code","source":"history = model.fit_generator(datagen.flow(X_train, Y_train, batch_size=batch_size),\n                             epochs=epochs, validation_data = (X_val, Y_val), steps_per_epoch=X_train.shape[0]//batch_size)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:29:37.728661Z","iopub.execute_input":"2023-12-07T16:29:37.728956Z","iopub.status.idle":"2023-12-07T16:35:50.081900Z","shell.execute_reply.started":"2023-12-07T16:29:37.728931Z","shell.execute_reply":"2023-12-07T16:35:50.081186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Evaluate the model\n* Test Loss Visualization\n* Confusion matrix","metadata":{}},{"cell_type":"code","source":"# Plot the loss and accuracy curves for training and validation \nplt.plot(history.history[\"val_loss\"], color=\"green\", label=\"validation loss\")\nplt.title(\"Test Loss\")\nplt.xlabel(\"Number of Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:35:50.083332Z","iopub.execute_input":"2023-12-07T16:35:50.084737Z","iopub.status.idle":"2023-12-07T16:35:50.287362Z","shell.execute_reply.started":"2023-12-07T16:35:50.084696Z","shell.execute_reply":"2023-12-07T16:35:50.285932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot the loss and accuracy curves for training and validation \nplt.plot(history.history[\"val_accuracy\"], color=\"blue\", label=\"validation accuracy\")\nplt.title(\"Test Accuracy\")\nplt.xlabel(\"Number of Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:35:50.288832Z","iopub.execute_input":"2023-12-07T16:35:50.289173Z","iopub.status.idle":"2023-12-07T16:35:50.500026Z","shell.execute_reply.started":"2023-12-07T16:35:50.289144Z","shell.execute_reply":"2023-12-07T16:35:50.498816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Look at confusion matrix \n\ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, cm[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n\n# Predict the values from the validation dataset\nY_pred = model.predict(X_val)\n# Convert predictions classes to one hot vectors \nY_pred_classes = np.argmax(Y_pred,axis = 1) \n# Convert validation observations to one hot vectors\nY_true = np.argmax(Y_val,axis = 1) \n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \n# plot the confusion matrix\nplot_confusion_matrix(confusion_mtx, classes = range(10)) ","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:35:50.501447Z","iopub.execute_input":"2023-12-07T16:35:50.501719Z","iopub.status.idle":"2023-12-07T16:35:52.192125Z","shell.execute_reply.started":"2023-12-07T16:35:50.501695Z","shell.execute_reply":"2023-12-07T16:35:52.190302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display some error results \n\n# Errors are difference between predicted labels and true labels\nerrors = (Y_pred_classes - Y_true != 0)\n\nY_pred_classes_errors = Y_pred_classes[errors]\nY_pred_errors = Y_pred[errors]\nY_true_errors = Y_true[errors]\nX_val_errors = X_val[errors]\n\ndef display_errors(errors_index,img_errors,pred_errors, obs_errors):\n    \"\"\" This function shows 6 images with their predicted and real labels\"\"\"\n    n = 0\n    nrows = 2\n    ncols = 3\n    fig, ax = plt.subplots(nrows,ncols,sharex=True,sharey=True)\n    for row in range(nrows):\n        for col in range(ncols):\n            error = errors_index[n]\n            ax[row,col].imshow((img_errors[error]).reshape((28,28)))\n            ax[row,col].set_title(\"Predicted label :{}\\nTrue label :{}\".format(pred_errors[error],obs_errors[error]))\n            n += 1\n\n# Probabilities of the wrong predicted numbers\nY_pred_errors_prob = np.max(Y_pred_errors,axis = 1)\n\n# Predicted probabilities of the true values in the error set\ntrue_prob_errors = np.diagonal(np.take(Y_pred_errors, Y_true_errors, axis=1))\n\n# Difference between the probability of the predicted label and the true label\ndelta_pred_true_errors = Y_pred_errors_prob - true_prob_errors\n\n# Sorted list of the delta prob errors\nsorted_dela_errors = np.argsort(delta_pred_true_errors)\n\n# Top 6 errors \nmost_important_errors = sorted_dela_errors[-6:]\n\n# Show the top 6 errors\ndisplay_errors(most_important_errors, X_val_errors, Y_pred_classes_errors, Y_true_errors)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:35:52.193994Z","iopub.execute_input":"2023-12-07T16:35:52.194346Z","iopub.status.idle":"2023-12-07T16:35:53.078338Z","shell.execute_reply.started":"2023-12-07T16:35:52.194315Z","shell.execute_reply":"2023-12-07T16:35:53.077080Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss, accuracy = model.evaluate(X_train, Y_train)\nprint(\"Final training loss: {:.8f}\".format(loss))\nprint(\"Final training accuracy: {:.4%}\".format(accuracy))","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:35:53.079991Z","iopub.execute_input":"2023-12-07T16:35:53.080455Z","iopub.status.idle":"2023-12-07T16:36:03.476791Z","shell.execute_reply.started":"2023-12-07T16:35:53.080385Z","shell.execute_reply":"2023-12-07T16:36:03.475623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred_test = model.predict(X_val)\ny_pred_test = np.argmax(y_pred_test, axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:36:03.478381Z","iopub.execute_input":"2023-12-07T16:36:03.478807Z","iopub.status.idle":"2023-12-07T16:36:04.651600Z","shell.execute_reply.started":"2023-12-07T16:36:03.478771Z","shell.execute_reply":"2023-12-07T16:36:04.650337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({'ImageId': range(1, len(X_val) + 1), 'Label': y_pred_test})\nsubmission.to_csv(\"tf_mnist_result.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:36:04.653369Z","iopub.execute_input":"2023-12-07T16:36:04.653729Z","iopub.status.idle":"2023-12-07T16:36:04.666188Z","shell.execute_reply.started":"2023-12-07T16:36:04.653702Z","shell.execute_reply":"2023-12-07T16:36:04.665201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10, 10))\nfor i in range(25):\n    plt.subplot(5, 5, i + 1)\n    plt.imshow(X_train[i].reshape(28, 28), cmap='gray')\n    plt.title(Y_train[i])\n    plt.axis('off')\n\nplt.show()\n\n# Plot training and validation accuracy\nplt.figure(figsize=(12, 6))\nsns.set_style(\"whitegrid\")\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()\n\n# Plot training and validation loss\nplt.figure(figsize=(12, 6))\nsns.set_style(\"whitegrid\")\nplt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:36:04.667697Z","iopub.execute_input":"2023-12-07T16:36:04.667967Z","iopub.status.idle":"2023-12-07T16:36:06.799662Z","shell.execute_reply.started":"2023-12-07T16:36:04.667944Z","shell.execute_reply":"2023-12-07T16:36:06.798471Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# predict results\nresults = model.predict(test)\n\n# select the indix with the maximum probability\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:36:06.801401Z","iopub.execute_input":"2023-12-07T16:36:06.802487Z","iopub.status.idle":"2023-12-07T16:36:17.208762Z","shell.execute_reply.started":"2023-12-07T16:36:06.802448Z","shell.execute_reply":"2023-12-07T16:36:17.207310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1).astype(int)\n\nsubmission.to_csv(\"cnn_mnist_datagen.csv\",index=False)","metadata":{"execution":{"iopub.status.busy":"2023-12-07T16:40:09.777698Z","iopub.execute_input":"2023-12-07T16:40:09.778147Z","iopub.status.idle":"2023-12-07T16:40:09.816295Z","shell.execute_reply.started":"2023-12-07T16:40:09.778116Z","shell.execute_reply":"2023-12-07T16:40:09.815144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}