{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"}],"dockerImageVersionId":30775,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np, matplotlib.pyplot as plt, seaborn as sns, pickle, tensorflow as tf\nfrom sklearn.metrics import confusion_matrix as conf_mtx, ConfusionMatrixDisplay, classification_report as cls_rpt\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.models import model_from_json as mfj\nfrom tensorflow.keras.models import Sequential as seq\nfrom tensorflow.keras.utils import to_categorical as to_cat\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization","metadata":{"execution":{"iopub.status.busy":"2024-10-01T12:50:08.511133Z","iopub.execute_input":"2024-10-01T12:50:08.512154Z","iopub.status.idle":"2024-10-01T12:50:08.518196Z","shell.execute_reply.started":"2024-10-01T12:50:08.512106Z","shell.execute_reply":"2024-10-01T12:50:08.517149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Loading CIFAR-10 Data\n(xtr, ytr), (xts, yts) = cifar10.load_data()\nprint(xtr.shape, xts.shape)\nprint(ytr.shape, yts.shape)\n\nxtr = xtr.astype('float32') / 255.0\nxts = xts.astype('float32') / 255.0\nytr = to_cat(ytr, 10)\nyts = to_cat(yts, 10)\n\nclass_labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']","metadata":{"execution":{"iopub.status.busy":"2024-10-01T12:52:19.246809Z","iopub.execute_input":"2024-10-01T12:52:19.248243Z","iopub.status.idle":"2024-10-01T12:52:20.294186Z","shell.execute_reply.started":"2024-10-01T12:52:19.248186Z","shell.execute_reply":"2024-10-01T12:52:20.293361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# AlexNet Model on TF\nalexnet = seq([\n    Conv2D(96, kernel_size=(5, 5), strides=(1, 1), activation='relu', input_shape=(32, 32, 3)),\n    MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),\n    BatchNormalization(),\n\n    Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu'),\n    MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),\n    BatchNormalization(),\n\n    Conv2D(384, kernel_size=(3, 3), padding='same', activation='relu'),\n    Conv2D(384, kernel_size=(3, 3), padding='same', activation='relu'),\n    Conv2D(256, kernel_size=(3, 3), padding='same', activation='relu'),\n    MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),\n    BatchNormalization(),\n\n    Flatten(),\n    Dense(4096, activation='relu'),\n    Dropout(0.5),\n    BatchNormalization(),\n\n    Dense(4096, activation='relu'),\n    Dropout(0.5),\n    BatchNormalization(),\n\n    Dense(10, activation='softmax')\n])\n\nalexnet.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\nalexnet.summary()","metadata":{"execution":{"iopub.status.busy":"2024-10-01T12:54:13.149951Z","iopub.execute_input":"2024-10-01T12:54:13.150347Z","iopub.status.idle":"2024-10-01T12:54:13.726049Z","shell.execute_reply.started":"2024-10-01T12:54:13.150300Z","shell.execute_reply":"2024-10-01T12:54:13.725149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hist = alexnet.fit(xtr, ytr, epochs=40, validation_split=0.2)","metadata":{"execution":{"iopub.status.busy":"2024-10-01T12:55:55.856652Z","iopub.execute_input":"2024-10-01T12:55:55.857503Z","iopub.status.idle":"2024-10-01T13:05:33.541510Z","shell.execute_reply.started":"2024-10-01T12:55:55.857463Z","shell.execute_reply":"2024-10-01T13:05:33.540601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plotting Accuracy and Loss\ntr_ls = hist.history['loss']\nval_ls = hist.history['val_loss']\ntr_acc = hist.history['accuracy']\nval_acc = hist.history['val_accuracy']\n\nplt.figure(figsize=(10, 5))\nplt.plot(tr_acc, label='Training Accuracy')\nplt.plot(val_acc, label='Validation Accuracy')\nplt.title('AlexNet Training and Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-01T13:06:35.894314Z","iopub.execute_input":"2024-10-01T13:06:35.894718Z","iopub.status.idle":"2024-10-01T13:06:36.173940Z","shell.execute_reply.started":"2024-10-01T13:06:35.894679Z","shell.execute_reply":"2024-10-01T13:06:36.172925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Confusion Matrix\nypr = alexnet.predict(xts)\nypr_cls = np.argmax(ypr, axis=1)\nytrue_cls = np.argmax(yts, axis=1)\n\ncm = conf_mtx(ypr_cls, ytrue_cls)\nplt.figure(figsize=(10, 8))\nsns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=range(10), yticklabels=range(10))\nplt.title('Confusion Matrix')\nplt.ylabel('True Label')\nplt.xlabel('Predicted Label')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-01T13:10:51.841559Z","iopub.execute_input":"2024-10-01T13:10:51.842460Z","iopub.status.idle":"2024-10-01T13:10:54.052902Z","shell.execute_reply.started":"2024-10-01T13:10:51.842414Z","shell.execute_reply":"2024-10-01T13:10:54.051923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Classification Report\nprint(cls_rpt(ytrue_cls, ypr_cls, target_names=class_labels))","metadata":{"execution":{"iopub.status.busy":"2024-10-01T13:10:56.895398Z","iopub.execute_input":"2024-10-01T13:10:56.896164Z","iopub.status.idle":"2024-10-01T13:10:56.914299Z","shell.execute_reply.started":"2024-10-01T13:10:56.896124Z","shell.execute_reply":"2024-10-01T13:10:56.913237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"config = alexnet.to_json()\nweights = alexnet.get_weights()\n\nmod_data = {\n    'model_config': config,\n    'model_weights': weights\n}\n\nwith open('alexnet.pkl', 'wb') as f:\n    pickle.dump(mod_data, f)","metadata":{"execution":{"iopub.status.busy":"2024-10-01T13:10:58.947718Z","iopub.execute_input":"2024-10-01T13:10:58.948548Z","iopub.status.idle":"2024-10-01T13:10:59.374200Z","shell.execute_reply.started":"2024-10-01T13:10:58.948506Z","shell.execute_reply":"2024-10-01T13:10:59.373148Z"},"trusted":true},"execution_count":null,"outputs":[]}]}