{"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":3649,"databundleVersionId":46718,"sourceType":"competition"}],"dockerImageVersionId":30746,"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_count":null,"outputs":[]},{"cell_type":"markdown","source":"<h2 style='color:blue' align='center'>Classification Using Convolutional Neural Network (CNN)</h2>","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import datasets, layers, models\nimport matplotlib.pyplot as plt\nimport numpy as np","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:00:36.467141Z","iopub.execute_input":"2024-07-21T20:00:36.467989Z","iopub.status.idle":"2024-07-21T20:00:36.476421Z","shell.execute_reply.started":"2024-07-21T20:00:36.467948Z","shell.execute_reply":"2024-07-21T20:00:36.475330Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<h4 style=\"color:purple\">Load the dataset</h4>","metadata":{}},{"cell_type":"code","source":"(X_train, y_train), (X_test,y_test) = datasets.cifar10.load_data()\nX_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:00:36.481061Z","iopub.execute_input":"2024-07-21T20:00:36.481935Z","iopub.status.idle":"2024-07-21T20:00:41.621875Z","shell.execute_reply.started":"2024-07-21T20:00:36.481898Z","shell.execute_reply":"2024-07-21T20:00:41.620421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test.shape","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:00:41.623996Z","iopub.execute_input":"2024-07-21T20:00:41.624560Z","iopub.status.idle":"2024-07-21T20:00:41.633005Z","shell.execute_reply.started":"2024-07-21T20:00:41.624523Z","shell.execute_reply":"2024-07-21T20:00:41.631129Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Here we see there are 50000 training images and 1000 test images","metadata":{}},{"cell_type":"code","source":"y_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:00:55.235722Z","iopub.execute_input":"2024-07-21T20:00:55.236110Z","iopub.status.idle":"2024-07-21T20:00:55.244384Z","shell.execute_reply.started":"2024-07-21T20:00:55.236078Z","shell.execute_reply":"2024-07-21T20:00:55.242936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train[:5]","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:00:59.822776Z","iopub.execute_input":"2024-07-21T20:00:59.823183Z","iopub.status.idle":"2024-07-21T20:00:59.830541Z","shell.execute_reply.started":"2024-07-21T20:00:59.823132Z","shell.execute_reply":"2024-07-21T20:00:59.829378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We will convert the 2D array `y_train` into a 1D array for our classification task.","metadata":{}},{"cell_type":"code","source":"y_train = y_train.reshape(-1,)\ny_train[:5]","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:02:16.186074Z","iopub.execute_input":"2024-07-21T20:02:16.187050Z","iopub.status.idle":"2024-07-21T20:02:16.194282Z","shell.execute_reply.started":"2024-07-21T20:02:16.187009Z","shell.execute_reply":"2024-07-21T20:02:16.193095Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test = y_test.reshape(-1,)","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:02:22.009196Z","iopub.execute_input":"2024-07-21T20:02:22.009784Z","iopub.status.idle":"2024-07-21T20:02:22.016528Z","shell.execute_reply.started":"2024-07-21T20:02:22.009741Z","shell.execute_reply":"2024-07-21T20:02:22.015040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes = [\"airplane\",\"automobile\",\"bird\",\"cat\",\"deer\",\"dog\",\"frog\",\"horse\",\"ship\",\"truck\"]","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:02:28.340117Z","iopub.execute_input":"2024-07-21T20:02:28.340526Z","iopub.status.idle":"2024-07-21T20:02:28.345778Z","shell.execute_reply.started":"2024-07-21T20:02:28.340494Z","shell.execute_reply":"2024-07-21T20:02:28.344567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_sample(X, y, index):\n    plt.figure(figsize = (15,2))\n    plt.imshow(X[index])\n    plt.xlabel(classes[y[index]])","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:02:47.839050Z","iopub.execute_input":"2024-07-21T20:02:47.839941Z","iopub.status.idle":"2024-07-21T20:02:47.845777Z","shell.execute_reply.started":"2024-07-21T20:02:47.839898Z","shell.execute_reply":"2024-07-21T20:02:47.844462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_sample(X_train, y_train, 0)","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:02:52.421687Z","iopub.execute_input":"2024-07-21T20:02:52.422068Z","iopub.status.idle":"2024-07-21T20:02:52.609574Z","shell.execute_reply.started":"2024-07-21T20:02:52.422039Z","shell.execute_reply":"2024-07-21T20:02:52.608414Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_sample(X_train, y_train, 1)","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:02:57.893119Z","iopub.execute_input":"2024-07-21T20:02:57.893582Z","iopub.status.idle":"2024-07-21T20:02:58.102589Z","shell.execute_reply.started":"2024-07-21T20:02:57.893544Z","shell.execute_reply":"2024-07-21T20:02:58.101365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"To normalize the images to a range from 0 to 1, we need to divide each value in the image by 255. Each image has 3 channels (R, G, B), and each value in these channels ranges from 0 to 255. Therefore, the normalization process involves dividing each pixel value by 255.","metadata":{}},{"cell_type":"markdown","source":"<h4 style=\"color:purple\">Normalizing the training data</h4>","metadata":{}},{"cell_type":"code","source":"X_train = X_train / 255.0\nX_test = X_test / 255.0","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:03:35.926624Z","iopub.execute_input":"2024-07-21T20:03:35.927889Z","iopub.status.idle":"2024-07-21T20:03:36.622740Z","shell.execute_reply.started":"2024-07-21T20:03:35.927844Z","shell.execute_reply":"2024-07-21T20:03:36.621176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<h4 style=\"color:purple\">Build simple artificial neural network for image classification</h4>","metadata":{}},{"cell_type":"code","source":"ann = models.Sequential([\n        layers.Flatten(input_shape=(32,32,3)),\n        layers.Dense(3000, activation='relu'),\n        layers.Dense(1000, activation='relu'),\n        layers.Dense(10, activation='sigmoid')    \n    ])\n\nann.compile(optimizer='SGD',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n\nann.fit(X_train, y_train, epochs=5)","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:03:48.379176Z","iopub.execute_input":"2024-07-21T20:03:48.379602Z","iopub.status.idle":"2024-07-21T20:08:56.349975Z","shell.execute_reply.started":"2024-07-21T20:03:48.379570Z","shell.execute_reply":"2024-07-21T20:08:56.348919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**As we can see that at the end of the 5th epoch, accuracy is at around 49.78%**","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix , classification_report\nimport numpy as np\ny_pred = ann.predict(X_test)\ny_pred_classes = [np.argmax(element) for element in y_pred]\n\nprint(\"Classification Report: \\n\", classification_report(y_test, y_pred_classes))","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:09:12.025796Z","iopub.execute_input":"2024-07-21T20:09:12.026191Z","iopub.status.idle":"2024-07-21T20:09:17.286840Z","shell.execute_reply.started":"2024-07-21T20:09:12.026146Z","shell.execute_reply":"2024-07-21T20:09:17.285622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<h4 style=\"color:purple\">Now let us build a convolutional neural network to train our images</h4>","metadata":{}},{"cell_type":"code","source":"cnn = models.Sequential([\n    layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu', input_shape=(32, 32, 3)),\n    layers.MaxPooling2D((2, 2)),\n    \n    layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu'),\n    layers.MaxPooling2D((2, 2)),\n    \n    layers.Flatten(),\n    layers.Dense(64, activation='relu'),\n    layers.Dense(10, activation='softmax')\n])","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:20:02.477263Z","iopub.execute_input":"2024-07-21T20:20:02.477668Z","iopub.status.idle":"2024-07-21T20:20:02.539328Z","shell.execute_reply.started":"2024-07-21T20:20:02.477638Z","shell.execute_reply":"2024-07-21T20:20:02.538224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:20:10.070890Z","iopub.execute_input":"2024-07-21T20:20:10.071321Z","iopub.status.idle":"2024-07-21T20:20:10.083819Z","shell.execute_reply.started":"2024-07-21T20:20:10.071285Z","shell.execute_reply":"2024-07-21T20:20:10.082505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn.fit(X_train, y_train, epochs=5)","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:20:17.075038Z","iopub.execute_input":"2024-07-21T20:20:17.075457Z","iopub.status.idle":"2024-07-21T20:25:30.848254Z","shell.execute_reply.started":"2024-07-21T20:20:17.075420Z","shell.execute_reply":"2024-07-21T20:25:30.847035Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"With a Convolutional Neural Network (CNN), after 5 epochs, the accuracy reached approximately 71.71%, which is a significant improvement over the Artificial Neural Network (ANN). CNNs are highly effective for image classification tasks and provide excellent accuracy. \n\nAdditionally, the computational requirements are lower compared to a simple ANN, as max-pooling reduces the image dimensions while still preserving important features.\n","metadata":{}},{"cell_type":"code","source":"cnn.evaluate(X_test,y_test)","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:25:33.758232Z","iopub.execute_input":"2024-07-21T20:25:33.758944Z","iopub.status.idle":"2024-07-21T20:25:36.826559Z","shell.execute_reply.started":"2024-07-21T20:25:33.758909Z","shell.execute_reply":"2024-07-21T20:25:36.825482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = cnn.predict(X_test)\ny_pred[:5]","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:25:38.707033Z","iopub.execute_input":"2024-07-21T20:25:38.707499Z","iopub.status.idle":"2024-07-21T20:25:41.366892Z","shell.execute_reply.started":"2024-07-21T20:25:38.707463Z","shell.execute_reply":"2024-07-21T20:25:41.364604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_classes = [np.argmax(element) for element in y_pred]\ny_classes[:5]","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:25:43.840765Z","iopub.execute_input":"2024-07-21T20:25:43.841150Z","iopub.status.idle":"2024-07-21T20:25:43.872687Z","shell.execute_reply.started":"2024-07-21T20:25:43.841116Z","shell.execute_reply":"2024-07-21T20:25:43.871508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test[:5]","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:25:45.351684Z","iopub.execute_input":"2024-07-21T20:25:45.352090Z","iopub.status.idle":"2024-07-21T20:25:45.361774Z","shell.execute_reply.started":"2024-07-21T20:25:45.352056Z","shell.execute_reply":"2024-07-21T20:25:45.360719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_sample(X_test, y_test,3)","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:25:47.098038Z","iopub.execute_input":"2024-07-21T20:25:47.098865Z","iopub.status.idle":"2024-07-21T20:25:47.289043Z","shell.execute_reply.started":"2024-07-21T20:25:47.098828Z","shell.execute_reply":"2024-07-21T20:25:47.287929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes[y_classes[3]]","metadata":{"execution":{"iopub.status.busy":"2024-07-21T20:25:49.284669Z","iopub.execute_input":"2024-07-21T20:25:49.285063Z","iopub.status.idle":"2024-07-21T20:25:49.291902Z","shell.execute_reply.started":"2024-07-21T20:25:49.285031Z","shell.execute_reply":"2024-07-21T20:25:49.290811Z"},"trusted":true},"execution_count":null,"outputs":[]}]}