{"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":"gpu","dataSources":[{"sourceId":5048,"databundleVersionId":868335,"sourceType":"competition"}],"dockerImageVersionId":30674,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten\nimport zipfile\nimport os","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:04:21.951771Z","iopub.execute_input":"2024-04-05T00:04:21.952652Z","iopub.status.idle":"2024-04-05T00:04:25.508645Z","shell.execute_reply.started":"2024-04-05T00:04:21.952614Z","shell.execute_reply":"2024-04-05T00:04:25.507634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_path='/kaggle/input/state-farm-distracted-driver-detection/imgs/train'\ntrain= os.listdir(train_path)\ntrain","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:04:41.574612Z","iopub.execute_input":"2024-04-05T00:04:41.575748Z","iopub.status.idle":"2024-04-05T00:04:41.583238Z","shell.execute_reply.started":"2024-04-05T00:04:41.575712Z","shell.execute_reply":"2024-04-05T00:04:41.582325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntrain_dir = train_path\n\n#class_names = ['normal driving', 'texting - right', 'talking on the phone - right', 'texting - left', 'talking on the phone - left', 'operating the radio', 'drinking', 'reaching behind', 'hair and makeup', 'talking to passenger']\nclass_names=['c0','c1','c2','c3','c4','c5','c6','c7','c8','c9']\n\ndef load_images_from_class(class_name, num_images=10):\n    class_dir = os.path.join(train_dir, class_name)\n    images = []\n    for filename in os.listdir(class_dir)[:num_images]:\n        if filename.endswith('.jpg'):\n            image_path = os.path.join(class_dir, filename)\n            image = cv2.imread(image_path)\n            images.append(image)\n    return images\n\nfig, axes = plt.subplots(10, 10, figsize=(20, 20))\n\nfor i, class_name in enumerate(class_names):\n    class_images = load_images_from_class(class_name)\n    for j in range(10):\n        axes[i, j].imshow(cv2.cvtColor(class_images[j], cv2.COLOR_BGR2RGB))\n        axes[i, j].set_title(class_name)\n        axes[i, j].axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:04:42.355192Z","iopub.execute_input":"2024-04-05T00:04:42.355638Z","iopub.status.idle":"2024-04-05T00:04:54.010262Z","shell.execute_reply.started":"2024-04-05T00:04:42.355602Z","shell.execute_reply":"2024-04-05T00:04:54.008703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_images_from_class(class_name, num_images=10):\n    class_dir = os.path.join(train_dir, 'c1')\n    images = []\n    for filename in os.listdir(class_dir)[:num_images]:\n        if filename.endswith('.jpg'):\n            image_path = os.path.join(class_dir, filename)\n            image = cv2.imread(image_path)\n            images.append(image)\n    return images\n\nimg=load_images_from_class(train_dir,5)\nimg[0].shape","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:04:54.011890Z","iopub.execute_input":"2024-04-05T00:04:54.012165Z","iopub.status.idle":"2024-04-05T00:04:54.062491Z","shell.execute_reply.started":"2024-04-05T00:04:54.012142Z","shell.execute_reply":"2024-04-05T00:04:54.061715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n#from tensorflow.keras.applications.imagenet_utils import preprocess_input\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\n\n# Define paths to your train and validation directories\ntest_dir = '/kaggle/input/state-farm-distracted-driver-detection/imgs/test'\n\n# Define ImageDataGenerator for training data with augmentation\ntrain_datagen = ImageDataGenerator(\n   preprocessing_function=preprocess_input,\nrotation_range=20,\nshear_range=0.2,\nzoom_range=0.2,\nhorizontal_flip=True\n)  # 20% validation split\n\n# test_datagen = ImageDataGenerator(\n#     rotation_range=40,\n#     width_shift_range=0.2,\n#     height_shift_range=0.2,\n#     shear_range=0.2,\n#     zoom_range=0.2,\n#     horizontal_flip=True,\n#     fill_mode='nearest'\n# )\n\n# Set batch size\nbatch_size = 32\n\n# Generate batches of augmented data from the train directory\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,                 # Target directory\n    #target_size=(128, 128),      # Resize images to 128*128\n    batch_size=batch_size,     # Number of samples per batch\n    class_mode='categorical',  # Use one-hot encoding for labels\n    shuffle=True\n)\n\n# Generate batches of validation data from the same directory\n# validation_generator = train_datagen.flow_from_directory(\n#     train_dir,                 # Target directory\n#     target_size=(128, 128),      # Resize images to 128*128\n#     batch_size=batch_size,     # Number of samples per batch\n#     class_mode='categorical',  # Use one-hot encoding for labels\n#     subset='validation'        # Specify this as validation set\n# )\n\n\n\n# Inspect the class indices\nprint(\"Class indices:\", train_generator.class_indices)\n\n# # Check the number of classes\nnum_classes = len(train_generator.class_indices)\nprint(\"Number of classes:\", num_classes)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:04:54.063789Z","iopub.execute_input":"2024-04-05T00:04:54.064099Z","iopub.status.idle":"2024-04-05T00:04:58.636055Z","shell.execute_reply.started":"2024-04-05T00:04:54.064072Z","shell.execute_reply":"2024-04-05T00:04:58.635101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(os.listdir(test_dir))\nlen(os.listdir(train_dir))","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:04:58.637991Z","iopub.execute_input":"2024-04-05T00:04:58.638264Z","iopub.status.idle":"2024-04-05T00:04:58.681040Z","shell.execute_reply.started":"2024-04-05T00:04:58.638240Z","shell.execute_reply":"2024-04-05T00:04:58.680121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.applications import ResNet50\n# Load pre-trained ResNet50 model without top layers\nconv_base = ResNet50(weights='imagenet', include_top=False)\n\n# Freeze convolutional base\nconv_base.trainable = False","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:06:16.826510Z","iopub.execute_input":"2024-04-05T00:06:16.827424Z","iopub.status.idle":"2024-04-05T00:06:17.883004Z","shell.execute_reply.started":"2024-04-05T00:06:16.827385Z","shell.execute_reply":"2024-04-05T00:06:17.882173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import regularizers\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import models\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout\n\nmodel = Sequential([\n    conv_base,\n    Flatten(),\n    Dense(64, activation='relu'),\n    Dense(10, activation='softmax')\n])\n\n\nmodel.compile(loss='categorical_crossentropy',  # Use categorical cross-entropy for multi-class classification\n              optimizer=optimizers.Adam(0.0001),\n              metrics=['acc'])\n","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:30:53.000326Z","iopub.execute_input":"2024-04-05T00:30:53.001328Z","iopub.status.idle":"2024-04-05T00:30:53.016262Z","shell.execute_reply.started":"2024-04-05T00:30:53.001279Z","shell.execute_reply":"2024-04-05T00:30:53.015431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_history = model.fit(train_generator,\n                    epochs=10,\n                    steps_per_epoch=200,\n                    #validation_st n ceps=validation_steps\n                    )","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:30:54.288131Z","iopub.execute_input":"2024-04-05T00:30:54.289052Z","iopub.status.idle":"2024-04-05T00:44:22.660504Z","shell.execute_reply.started":"2024-04-05T00:30:54.289015Z","shell.execute_reply":"2024-04-05T00:44:22.659641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc = model_history.history['acc']\n# val_acc = model_history.history['val_acc']\nloss = model_history.history['loss']\n# val_loss = model_history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, label='Training acc')\n# plt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, label='Training loss')\n# plt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:49:30.855561Z","iopub.execute_input":"2024-04-05T00:49:30.855956Z","iopub.status.idle":"2024-04-05T00:49:31.255269Z","shell.execute_reply.started":"2024-04-05T00:49:30.855926Z","shell.execute_reply":"2024-04-05T00:49:31.254195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # Evaluate the model on the test data\n# test_loss, test_accuracy = model.evaluate(test_generator)\n\n# # Print the test accuracy\n# print(\"Test Accuracy:\", test_accuracy)\n\n# # Make predictions on the test data\n# predictions = model.predict(test_generator)\n\n# # Decode one-hot encoded predictions to get class labels\n# predicted_classes = np.argmax(predictions, axis=1)\n\n# # Get true labels from the test generator\n# true_classes = test_generator.classes\n\n# # Calculate accuracy manually\n# accuracy = np.mean(predicted_classes == true_classes)\n# print(\"Accuracy on test data (manually calculated):\", accuracy)\n\n#test_images2 = preprocess_input(test_images1)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-05T00:50:14.851724Z","iopub.execute_input":"2024-04-05T00:50:14.852114Z","iopub.status.idle":"2024-04-05T00:50:14.857105Z","shell.execute_reply.started":"2024-04-05T00:50:14.852083Z","shell.execute_reply":"2024-04-05T00:50:14.856072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}