{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Milestone 2\nIn this milestone we convolutional neural network to train and test a dataset of sports images ,the data consist of 14572 image - 13572 for training, 500 for validation & 500 for testing - made of 100 class","metadata":{"execution":{"iopub.status.busy":"2023-01-09T10:01:29.791682Z","iopub.execute_input":"2023-01-09T10:01:29.792235Z","iopub.status.idle":"2023-01-09T10:01:36.662421Z","shell.execute_reply.started":"2023-01-09T10:01:29.79212Z","shell.execute_reply":"2023-01-09T10:01:36.661243Z"}}},{"cell_type":"markdown","source":"# Importing Libraries","metadata":{}},{"cell_type":"code","source":"# Import libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.layers import *\nfrom keras.models import *\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\nimport os, shutil\nimport warnings\nwarnings.filterwarnings('ignore')\nimport os\nimport matplotlib.pyplot as plt\nfrom PIL import Image","metadata":{"execution":{"iopub.status.busy":"2023-08-26T17:33:04.56442Z","iopub.execute_input":"2023-08-26T17:33:04.564777Z","iopub.status.idle":"2023-08-26T17:33:04.572912Z","shell.execute_reply.started":"2023-08-26T17:33:04.564741Z","shell.execute_reply":"2023-08-26T17:33:04.571847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualise the Images","metadata":{}},{"cell_type":"code","source":"# Let's plot a few images\ntrain_path = \"/kaggle/input/sports-classification/train\"\nvalidation_path = \"/kaggle/input/sports-classification/valid\"\ntest_path = \"/kaggle/input/sports-classification/test\"\n\nimage_categories = os.listdir('/kaggle/input/sports-classification/train')\n\ndef plot_images(image_categories):\n    \n    # Create a figure\n    plt.figure(figsize=(12, 12))\n    for i, v in enumerate(image_categories):\n        \n        # Load images for the ith category\n        image_path = train_path + '/' + v\n        images_in_folder = os.listdir(image_path)\n        first_image_of_folder = images_in_folder[0]\n        first_image_path = image_path + '/' + first_image_of_folder\n        img = image.load_img(first_image_path)\n        img_arr = image.img_to_array(img)/255.0\n        \n        \n        # Create Subplot and plot the images\n        plt.subplot(10, 10, i+1)\n        plt.imshow(img_arr)\n        plt.title(v)\n        plt.axis('off')\n        \n    plt.show()\n\n# Call the function\nplot_images(image_categories)","metadata":{"execution":{"iopub.status.busy":"2023-08-26T17:33:04.574696Z","iopub.execute_input":"2023-08-26T17:33:04.574955Z","iopub.status.idle":"2023-08-26T17:33:11.333765Z","shell.execute_reply.started":"2023-08-26T17:33:04.574924Z","shell.execute_reply":"2023-08-26T17:33:11.330984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare the Dataset","metadata":{}},{"cell_type":"code","source":"# Creating Image Data Generator for train, validation and test set\n\n# 1. Train Set\ntrain_gen = ImageDataGenerator(rescale = 1.0/255.0) # Normalise the data\ntrain_image_generator = train_gen.flow_from_directory(\n                                            train_path,\n                                            target_size=(150, 150),\n                                            batch_size=32,\n                                            class_mode='categorical')\n\n# 2. Validation Set\nval_gen = ImageDataGenerator(rescale = 1.0/255.0) # Normalise the data\nval_image_generator = train_gen.flow_from_directory(\n                                            validation_path,\n                                            target_size=(150, 150),\n                                            batch_size=32,\n                                            class_mode='categorical')\n\n# 3. Test Set\ntest_gen = ImageDataGenerator(rescale = 1.0/255.0) # Normalise the data\ntest_image_generator = train_gen.flow_from_directory(\n                                            test_path,\n                                            target_size=(150, 150),\n                                            batch_size=32,\n                                            class_mode='categorical')","metadata":{"execution":{"iopub.status.busy":"2023-08-26T17:33:11.336603Z","iopub.execute_input":"2023-08-26T17:33:11.337129Z","iopub.status.idle":"2023-08-26T17:33:12.357105Z","shell.execute_reply.started":"2023-08-26T17:33:11.337049Z","shell.execute_reply":"2023-08-26T17:33:12.347226Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Print the class encodings done by the generators\nclass_map = dict([(v, k) for k, v in train_image_generator.class_indices.items()])\nprint(class_map)","metadata":{"execution":{"iopub.status.busy":"2023-08-26T17:33:12.359058Z","iopub.execute_input":"2023-08-26T17:33:12.359442Z","iopub.status.idle":"2023-08-26T17:33:12.366342Z","shell.execute_reply.started":"2023-08-26T17:33:12.359406Z","shell.execute_reply":"2023-08-26T17:33:12.365362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Building a CNN model","metadata":{}},{"cell_type":"code","source":"# Build a custom sequential CNN model\n\nmodel = Sequential() # model object\n\n# Add Layers\nmodel.add(Conv2D(filters=32, kernel_size=3, strides=1, padding='same', activation='relu', input_shape=[150, 150, 3]))\nmodel.add(MaxPooling2D(2))\nmodel.add(Conv2D(filters=64, kernel_size=3, strides=1, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(2))\nmodel.add(Conv2D(filters=128, kernel_size=3, strides=1, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(2))\nmodel.add(Conv2D(filters=64, kernel_size=3, strides=1, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(2))\nmodel.add(Conv2D(filters=32, kernel_size=3, strides=1, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(2))\n\n# Flatten the feature map\nmodel.add(Flatten())\n\n# Add the fully connected layers\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(100, activation='softmax'))\n\n# print the model summary\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-08-26T17:33:12.368966Z","iopub.execute_input":"2023-08-26T17:33:12.370113Z","iopub.status.idle":"2023-08-26T17:33:12.512596Z","shell.execute_reply.started":"2023-08-26T17:33:12.370028Z","shell.execute_reply":"2023-08-26T17:33:12.51141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile and fit the model\nearly_stopping = keras.callbacks.EarlyStopping(patience=50) # Set up callbacks\nmodel.compile(optimizer='Adam', loss='categorical_crossentropy', metrics='accuracy')\nhist = model.fit(train_image_generator, \n                 epochs=20, \n                 verbose=1, \n                 validation_data=val_image_generator, \n\n                 callbacks=early_stopping)\nmodel.save('model.tfl')","metadata":{"execution":{"iopub.status.busy":"2023-08-26T17:44:17.797816Z","iopub.execute_input":"2023-08-26T17:44:17.798525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Model trained for 20 Epochs**","metadata":{}},{"cell_type":"code","source":"# Plot the error and accuracy\nh = hist.history\nplt.style.use('ggplot')\nplt.figure(figsize=(10, 5))\nplt.plot(h['loss'], c='red', label='Training Loss')\nplt.plot(h['val_loss'], c='red', linestyle='--', label='Validation Loss')\nplt.plot(h['accuracy'], c='blue', label='Training Accuracy')\nplt.plot(h['val_accuracy'], c='blue', linestyle='--', label='Validation Accuracy')\nplt.xlabel(\"Number of Epochs\")\nplt.legend(loc='best')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Performance Evaluation","metadata":{}},{"cell_type":"code","source":"# Predict the accuracy for the test set\n#print(test_image_generator)\nmodel.evaluate(test_image_generator)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Testing the Model\ntest_image_path = '/kaggle/input/sports-classification/test/boxing/3.jpg'\n\ndef generate_predictions(test_image_path, actual_label):\n    \n    # 1. Load and preprocess the image\n    test_img = image.load_img(test_image_path, target_size=(150, 150))\n    test_img_arr = image.img_to_array(test_img)/255.0\n    test_img_input = test_img_arr.reshape((1, test_img_arr.shape[0], test_img_arr.shape[1], test_img_arr.shape[2]))\n\n    # 2. Make Predictions\n    predicted_label = np.argmax(model.predict(test_img_input))\n    predicted_vegetable = class_map[predicted_label]\n    plt.figure(figsize=(4, 4))\n    plt.imshow(test_img_arr)\n    plt.title(\"Predicted Label: {}, Actual Label: {}\".format(predicted_vegetable, actual_label))\n    plt.grid()\n    plt.axis('off')\n    plt.show()\n\n# call the function\ngenerate_predictions(test_image_path, actual_label='boxing')","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}