{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":5048,"databundleVersionId":868335,"sourceType":"competition"}],"dockerImageVersionId":30746,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import csv\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.applications import DenseNet121\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D\nimport random","metadata":{"execution":{"iopub.status.busy":"2024-08-16T12:15:59.637281Z","iopub.execute_input":"2024-08-16T12:15:59.637689Z","iopub.status.idle":"2024-08-16T12:15:59.645491Z","shell.execute_reply.started":"2024-08-16T12:15:59.637641Z","shell.execute_reply":"2024-08-16T12:15:59.644479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Loading the dataset\ndata = {}\nwith open('/kaggle/input/state-farm-distracted-driver-detection/driver_imgs_list.csv') as f:\n    reader = csv.reader(f)\n    next(reader)\n    for row in reader:\n        key = row[1]\n        if key in data:\n            data[key].append(row[2])\n        else:\n            data[key] = [row[2]]\n\n        \n","metadata":{"execution":{"iopub.status.busy":"2024-08-16T11:33:14.865531Z","iopub.execute_input":"2024-08-16T11:33:14.865957Z","iopub.status.idle":"2024-08-16T11:33:14.900459Z","shell.execute_reply.started":"2024-08-16T11:33:14.865925Z","shell.execute_reply":"2024-08-16T11:33:14.899789Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Shuffling data\nfor key in data:\n    random.shuffle(data[key])","metadata":{"execution":{"iopub.status.busy":"2024-08-16T11:33:17.211690Z","iopub.execute_input":"2024-08-16T11:33:17.212258Z","iopub.status.idle":"2024-08-16T11:33:17.235838Z","shell.execute_reply.started":"2024-08-16T11:33:17.212229Z","shell.execute_reply":"2024-08-16T11:33:17.234826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Saving the labels in a list\nlabels = list(data.keys())\nlabels","metadata":{"execution":{"iopub.status.busy":"2024-08-16T11:33:18.919853Z","iopub.execute_input":"2024-08-16T11:33:18.920189Z","iopub.status.idle":"2024-08-16T11:33:18.927257Z","shell.execute_reply.started":"2024-08-16T11:33:18.920165Z","shell.execute_reply":"2024-08-16T11:33:18.926336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n\nos.mkdir('master_data')\nos.mkdir('master_data/training')\nos.mkdir('master_data/testing')","metadata":{"execution":{"iopub.status.busy":"2024-08-16T11:33:21.263101Z","iopub.execute_input":"2024-08-16T11:33:21.263470Z","iopub.status.idle":"2024-08-16T11:33:21.268238Z","shell.execute_reply.started":"2024-08-16T11:33:21.263440Z","shell.execute_reply":"2024-08-16T11:33:21.267446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for emotion in labels:\n  os.mkdir(os.path.join('master_data/training/', emotion))\n  os.mkdir(os.path.join('master_data/testing/', emotion))","metadata":{"execution":{"iopub.status.busy":"2024-08-16T11:33:24.157537Z","iopub.execute_input":"2024-08-16T11:33:24.157899Z","iopub.status.idle":"2024-08-16T11:33:24.163845Z","shell.execute_reply.started":"2024-08-16T11:33:24.157871Z","shell.execute_reply":"2024-08-16T11:33:24.162923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from shutil import copyfile\nsplit_size = 0.8\n\nfor emotion, images in data.items():\n  train_size = int(split_size*len(images))\n  train_images = images[:train_size]\n  test_images = images[train_size:]\n  for image in train_images:\n    source = os.path.join('/kaggle/input/state-farm-distracted-driver-detection/imgs/train',emotion, image)\n    dest = os.path.join('/kaggle/working/master_data/training', emotion,image)\n    copyfile(source, dest)\n  for image in test_images:\n    source = os.path.join('/kaggle/input/state-farm-distracted-driver-detection/imgs/train', emotion, image)\n    dest = os.path.join('/kaggle/working/master_data/testing', emotion,image)\n    copyfile(source, dest)","metadata":{"execution":{"iopub.status.busy":"2024-08-16T11:33:27.588551Z","iopub.execute_input":"2024-08-16T11:33:27.588895Z","iopub.status.idle":"2024-08-16T11:36:55.874976Z","shell.execute_reply.started":"2024-08-16T11:33:27.588869Z","shell.execute_reply":"2024-08-16T11:36:55.874101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating a base pre-trained model of ResNet50\nbase_model = DenseNet121(weights='imagenet', include_top=False, input_shape=(224, 224, 3))","metadata":{"execution":{"iopub.status.busy":"2024-08-16T12:16:06.337920Z","iopub.execute_input":"2024-08-16T12:16:06.338994Z","iopub.status.idle":"2024-08-16T12:16:09.072425Z","shell.execute_reply.started":"2024-08-16T12:16:06.338958Z","shell.execute_reply":"2024-08-16T12:16:09.071619Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Add global average pooling layer and a dense layer for classification\nx = base_model.output\nx = GlobalAveragePooling2D()(x)  # Convert features to a single vector\nx = Dense(1024, activation='relu')(x)  # Fully connected layer\nx = Dense(1024,activation = 'relu')(x)\npredictions = Dense(10, activation='softmax')(x)  # Output layer for classification\n\n# Create the final model\nmodel = tf.keras.models.Model(inputs=base_model.input, outputs=predictions)","metadata":{"execution":{"iopub.status.busy":"2024-08-16T12:16:12.987128Z","iopub.execute_input":"2024-08-16T12:16:12.987504Z","iopub.status.idle":"2024-08-16T12:16:13.048183Z","shell.execute_reply.started":"2024-08-16T12:16:12.987474Z","shell.execute_reply":"2024-08-16T12:16:13.047444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Freeze the layers of the base model\nfor layer in base_model.layers:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2024-08-16T12:16:15.443519Z","iopub.execute_input":"2024-08-16T12:16:15.443846Z","iopub.status.idle":"2024-08-16T12:16:15.458722Z","shell.execute_reply.started":"2024-08-16T12:16:15.443822Z","shell.execute_reply":"2024-08-16T12:16:15.457791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compiling the model\nmodel.compile(optimizer=Adam(learning_rate=0.001),\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-08-16T12:16:17.678824Z","iopub.execute_input":"2024-08-16T12:16:17.679252Z","iopub.status.idle":"2024-08-16T12:16:17.690378Z","shell.execute_reply.started":"2024-08-16T12:16:17.679223Z","shell.execute_reply":"2024-08-16T12:16:17.689457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = '/kaggle/working/master_data/training'\ntest_dir = '/kaggle/working/master_data/testing'\n\n# Create an instance of ImageDataGenerator for data augmentation\ntrain_datagen = ImageDataGenerator(rescale=1./255, rotation_range=20, zoom_range=0.2, horizontal_flip=True)\nvalid_datagen = ImageDataGenerator(rescale=1./255)\n\n# Load the training and validation data\ntrain_generator = train_datagen.flow_from_directory(train_dir, target_size=(224, 224), batch_size=32, class_mode='categorical')\nvalid_generator = valid_datagen.flow_from_directory(test_dir, target_size=(224, 224), batch_size=32, class_mode='categorical')\n","metadata":{"execution":{"iopub.status.busy":"2024-08-16T12:16:21.290997Z","iopub.execute_input":"2024-08-16T12:16:21.291948Z","iopub.status.idle":"2024-08-16T12:16:22.089281Z","shell.execute_reply.started":"2024-08-16T12:16:21.291912Z","shell.execute_reply":"2024-08-16T12:16:22.088358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train the model\nmodel.fit(train_generator, validation_data=valid_generator, epochs=10)","metadata":{"execution":{"iopub.status.busy":"2024-08-16T12:16:27.092786Z","iopub.execute_input":"2024-08-16T12:16:27.093326Z","iopub.status.idle":"2024-08-16T13:01:27.018611Z","shell.execute_reply.started":"2024-08-16T12:16:27.093292Z","shell.execute_reply":"2024-08-16T13:01:27.017691Z"},"trusted":true},"execution_count":null,"outputs":[]}]}