{"cells":[{"metadata":{"trusted":true,"_uuid":"fe1245f770c3182929676e1176e320494ef6c7ac"},"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport cv2\nimport random\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom keras.utils import np_utils\n%matplotlib inline\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.regularizers import L1L2\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.callbacks import EarlyStopping\nimport tensorflow as tf\nfrom keras.models import load_model\nfrom tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a2b06e90ee800a04d6b73f01825da060f28f4daa"},"cell_type":"code","source":"# defining the path and classes.\ndirectory = '../input/train'\ntest_directory = '../input/test/'\nclasses = ['c0','c1','c2','c3','c4','c5','c6','c7','c8','c9']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"652fd4391d5bb0ba89315c5371de8a0013678d85"},"cell_type":"code","source":"def generate_path(*args,**kwargs):\n    import os\n    path_conv = \"\"\n    for i in range(len(args)):\n        \n        if len(args) == 1 :\n            path_conv = os.path.join(path_conv,args[i])     \n            return path_conv\n        elif i == (len(args) - 1):\n            return path_conv\n        \n        path_conv = os.path.join(path_conv,args[i],args[i+1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6f8ead59d10105d09b879a4b6ea369996e3d1c4d"},"cell_type":"code","source":"# provide the path and number of images to be displayed.\n# function plots those images.\ndef display_images(path,no_of_images):\n    count = 1\n    for img in os.listdir(path):\n        img_array = cv2.imread(os.path.join(path,img),cv2.IMREAD_GRAYSCALE)\n        plt.imshow(img_array, cmap='gray')\n        plt.show()\n        count += 1\n        if(no_of_images < count):\n            break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6c4a3db73373a1e06785f25411b4093d28389e9e"},"cell_type":"code","source":"# defining a shape to be used for our models.\nimg_size1 = 240\nimg_size2 = 240","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"87e7092123747702cfdd690b1ead058b7dd9835b"},"cell_type":"code","source":"class train_and_test:\n    def __init__(self,*args,**kwargs):\n        self.train_and_test = args\n        \n    # creating a training dataset.\n    def create_training_data(self,path,classes,img_size1,img_size2):\n            training_data = []\n            for img in tqdm(os.listdir(path)):\n                img_array = cv2.imread(os.path.join(path,img),cv2.IMREAD_GRAYSCALE)\n                new_img = cv2.resize(img_array,(img_size2,img_size1))\n                if classes == 'c0':\n                    training_data.append([new_img,0])\n                elif classes == 'c1' :               \n                    training_data.append([new_img,1])\n                elif classes == 'c2' :               \n                    training_data.append([new_img,1])\n                elif classes == 'c3' :               \n                    training_data.append([new_img,1])\n                elif classes == 'c4' :               \n                    training_data.append([new_img,1])\n                elif classes == 'c5' :               \n                    training_data.append([new_img,1])\n                elif classes == 'c6' :               \n                    training_data.append([new_img,1])\n                elif classes == 'c7' :               \n                    training_data.append([new_img,1])\n                elif classes == 'c8' :               \n                    training_data.append([new_img,1])\n                elif classes == 'c9' :               \n                    training_data.append([new_img,1])\n            return training_data\n        \n    # Creating a test dataset.    \n    def create_testing_data(self,path,img_size1,img_size2):\n        testing_data = []       \n        for img in tqdm(os.listdir(path)):\n            img_array = cv2.imread(os.path.join(path,img),cv2.IMREAD_GRAYSCALE)\n            new_img = cv2.resize(img_array,(img_size2,img_size1))\n            testing_data.append([img,new_img])\n        return testing_data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"46a3181f31646481bfa4c981eaae130badc781c4"},"cell_type":"code","source":"# Initializing the train and test classes for training and validation.\n_train_ = train_and_test()\n_test_ = train_and_test()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"394111aeffeec5d4e25c134be9ea83ff0b65b23b"},"cell_type":"code","source":"training_data_c0 = _train_.create_training_data(generate_path(directory,classes[0]),classes[0],img_size1,img_size2)\ntraining_data_c1 = _train_.create_training_data(generate_path(directory,classes[1]),classes[1],img_size1,img_size2)\ntraining_data_c2 = _train_.create_training_data(generate_path(directory,classes[2]),classes[2],img_size1,img_size2)\ntraining_data_c3 = _train_.create_training_data(generate_path(directory,classes[3]),classes[3],img_size1,img_size2)\ntraining_data_c4 = _train_.create_training_data(generate_path(directory,classes[4]),classes[4],img_size1,img_size2)\ntraining_data_c5 = _train_.create_training_data(generate_path(directory,classes[5]),classes[5],img_size1,img_size2)\ntraining_data_c6 = _train_.create_training_data(generate_path(directory,classes[6]),classes[6],img_size1,img_size2)\ntraining_data_c7 = _train_.create_training_data(generate_path(directory,classes[7]),classes[7],img_size1,img_size2)\ntraining_data_c8 = _train_.create_training_data(generate_path(directory,classes[8]),classes[8],img_size1,img_size2)\ntraining_data_c9 = _train_.create_training_data(generate_path(directory,classes[9]),classes[9],img_size1,img_size2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"19cb55e14f48ca7070f780b15d108b4cba850dda","scrolled":false},"cell_type":"code","source":"test_data = _test_.create_testing_data(generate_path(test_directory),img_size1,img_size2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"66ba680a6d0116041b2903abe66c8496d8db11cc"},"cell_type":"code","source":"# create train and test data for our model.\nclass features_and_labels:\n    # get all the arguments dynmically.\n    def __init__(self,*args,**kwargs):\n        self.features_and_labels = args\n        \n    # generate your features and labels.\n    def generate_features_and_label(self,_class1_,_class2_):\n        x = []\n        y = []\n        \n        for features, label in tqdm(_class1_):\n            x.append(features)\n            y.append(label)\n            \n        for features, label in tqdm(_class2_):\n            x.append(features)\n            y.append(label)\n            \n        return x,y\n    \n    # generate np_arrays for test.\n    def generate_npArray(self,_class1_,_class2_,img_size2,img_size1) :\n        x,y = self.generate_features_and_label(_class1_,_class2_)\n        np_array = np.array(x).reshape(-1,img_size2*img_size1)\n        return np_array, y\n    \n    # train and split your data.\n    def train_and_split(self,features,labels,test_size,random_state,num_class):\n        x_train,x_test,y_train,y_test = train_test_split(features,labels,test_size=test_size,random_state=random_state)\n        Y_train = np_utils.to_categorical(y_train,num_classes=num_class)\n        Y_test = np_utils.to_categorical(y_test,num_classes=num_class)\n        \n        return x_train,x_test,Y_train,Y_test\n    ","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ad9d5b8c07c79b670222a643d03b76c4aed486b6"},"cell_type":"markdown","source":"## Different Distraction type\n    c0: safe driving\n    c1: texting - right\n    c2: talking on the phone - right\n    c3: texting - left\n    c4: talking on the phone - left\n    c5: operating the radio\n    c6: drinking\n    c7: reaching behind\n    c8: hair and makeup\n    c9: talking to passenger\n"},{"metadata":{"_uuid":"1d40b4449e380e5cef46a5920125fb6d06ec82c5"},"cell_type":"markdown","source":"## Creating training data for Safe vs texting_right"},{"metadata":{"trusted":true,"_uuid":"64267b69619301f43159deebbd16f24ccb846691"},"cell_type":"code","source":"feature_label = features_and_labels()\n\nnp_array_c0c1,y_c0c1 = feature_label.generate_npArray(training_data_c0,training_data_c1,img_size2,img_size1)\nx_train_c0c1,x_test_c0c1,y_train_c0c1,y_test_c0c1 = feature_label.train_and_split(np_array_c0c1,y_c0c1,0.3,100,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ba3b419c5d358e129bfb97b35154aab219c71ee7"},"cell_type":"code","source":"# initializing the logistic regression classifier.\noutput_dim = nb_classes = 2\nbatch_size = 128 \nnb_epoch = 100\nmodel_c0c1 = Sequential() \nmodel_c0c1.add(BatchNormalization())\nmodel_c0c1.add(Dense(output_dim, input_dim=240*240, activation='softmax')) \nmodel_c0c1.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')\ncallbacks = [EarlyStopping(monitor='val_acc',patience=5,mode='max')]\nhistory_c0c1 = model_c0c1.fit(x_train_c0c1, y_train_c0c1, batch_size=batch_size, epochs=nb_epoch,verbose=1, validation_data=(x_test_c0c1, y_test_c0c1),callbacks=callbacks) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"11047c56dfd4b95194075275707c8d936f1490b4"},"cell_type":"code","source":"model_c0c1.save_weights('./driverdistraction_Safe_vs_texting_right_weights.h5', overwrite=True)\nmodel_c0c1.save('./driverdistraction_lr_Safe_vs_texting_right.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"eef3f50978fbb0448ad46a04acc12846920398ac"},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history_c0c1.history['acc'])\nplt.plot(history_c0c1.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history_c0c1.history['loss'])\nplt.plot(history_c0c1.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"4b886a68fbdd27bea14c4a14374ca84a623b68ea"},"cell_type":"markdown","source":"## Creating training data for Safe vs talking_on_the_phone_right"},{"metadata":{"trusted":true,"_uuid":"c81bb284841be2771f7b8aae048b576a6f701865"},"cell_type":"code","source":"np_array_c0c2, y_c0c2 = feature_label.generate_npArray(training_data_c0,training_data_c2,img_size2,img_size1)\nx_train_c0c2,x_test_c0c2,y_train_c0c2,y_test_c0c2 = feature_label.train_and_split(np_array_c0c2,y_c0c2,0.3,100,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5a5dbc0c175516fabb274e92b99aac0e56411ed9"},"cell_type":"code","source":"# initializing the logistic regression classifier.\noutput_dim = nb_classes = 2\nbatch_size = 128 \nnb_epoch = 25\nmodel_c0c2 = Sequential() \nmodel_c0c2.add(BatchNormalization())\nmodel_c0c2.add(Dense(output_dim, input_dim=240*240, activation='softmax')) \nmodel_c0c2.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')\ncallbacks = [EarlyStopping(monitor='val_acc',patience=5,mode='max')]\nhistory_c0c2 = model_c0c2.fit(x_train_c0c2, y_train_c0c2, batch_size=batch_size, epochs=nb_epoch,verbose=1, validation_data=(x_test_c0c2, y_test_c0c2),callbacks=callbacks) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5de9c39cf5e892bbe90f4476184e68424f5a1f93"},"cell_type":"code","source":"model_c0c2.save_weights('./driverdistraction_talking_on_the_phone_right_weights.h5', overwrite=True)\nmodel_c0c2.save('./driverdistraction_lr_talking_on_the_phone_right.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"760ba3b6682ed9088ad1bb7a5c1f9b6b32320cea"},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history_c0c2.history['acc'])\nplt.plot(history_c0c2.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history_c0c2.history['loss'])\nplt.plot(history_c0c2.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8361da36a0f0b750fdba503ee1c06177d7757794"},"cell_type":"markdown","source":"## Creating training data for Safe vs texting_left"},{"metadata":{"trusted":true,"_uuid":"12b5ece42e86d0f331f00b407359b0bb2ecea9eb"},"cell_type":"code","source":"np_array_c0c3, y_c0c3 = feature_label.generate_npArray(training_data_c0,training_data_c3,img_size2,img_size1)\nx_train_c0c3,x_test_c0c3,y_train_c0c3,y_test_c0c3 = feature_label.train_and_split(np_array_c0c3,y_c0c3,0.3,100,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4fe99dbf1a9450c0b944db9aa88a078e3bd7492d"},"cell_type":"code","source":"# initializing the logistic regression classifier.\noutput_dim = nb_classes = 2\nbatch_size = 128 \nnb_epoch = 25\nmodel_c0c3 = Sequential() \nmodel_c0c3.add(BatchNormalization())\nmodel_c0c3.add(Dense(output_dim, input_dim=240*240, activation='softmax')) \nmodel_c0c3.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')\ncallbacks = [EarlyStopping(monitor='val_acc',patience=5,mode='max')]\nhistory_c0c3 = model_c0c3.fit(x_train_c0c3, y_train_c0c3, batch_size=batch_size, epochs=nb_epoch,verbose=1, validation_data=(x_test_c0c3, y_test_c0c3),callbacks=callbacks) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"220b6bc0a6c7492d03fc2da0e9a82f51806e2d98"},"cell_type":"code","source":"model_c0c3.save_weights('./driverdistraction_Safe_texting_left_weights.h5', overwrite=True)\nmodel_c0c3.save('./driverdistraction_lr_Safe_texting_left.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5154e84b5aab424bef6d603c8ed379e24279d208"},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history_c0c3.history['acc'])\nplt.plot(history_c0c3.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history_c0c3.history['loss'])\nplt.plot(history_c0c3.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ec27d0f4eeca930bad5dc2c8849121092c62603e"},"cell_type":"markdown","source":"## Creating training data for Safe vs talking_on_the_phone_left"},{"metadata":{"trusted":true,"_uuid":"43e059daaff58a849cabd3a0dc585fdded948c66"},"cell_type":"code","source":"np_array_c0c4, y_c0c4 = feature_label.generate_npArray(training_data_c0,training_data_c4,img_size2,img_size1)\nx_train_c0c4,x_test_c0c4,y_train_c0c4,y_test_c0c4 = feature_label.train_and_split(np_array_c0c4,y_c0c4,0.3,100,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dc60dd7f2956298bc74349c4cd18f03aaa1db27e"},"cell_type":"code","source":"# initializing the logistic regression classifier.\noutput_dim = nb_classes = 2\nbatch_size = 128 \nnb_epoch = 25\nmodel_c0c4 = Sequential() \nmodel_c0c4.add(BatchNormalization())\nmodel_c0c4.add(Dense(output_dim, input_dim=240*240, activation='softmax')) \nmodel_c0c4.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')\ncallbacks = [EarlyStopping(monitor='val_acc',patience=5,mode='max')]\nhistory_c0c4 = model_c0c4.fit(x_train_c0c4, y_train_c0c4, batch_size=batch_size, epochs=nb_epoch,verbose=1, validation_data=(x_test_c0c4, y_test_c0c4),callbacks=callbacks) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b866bf996a7695d998be4d1f666f52390de86240"},"cell_type":"code","source":"model_c0c4.save_weights('./driverdistraction_talking_on_the_phone_left_weights.h5', overwrite=True)\nmodel_c0c4.save('./driverdistraction_lr_talking_on_the_phone_left.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"96706e70efb2c041de23b10ce465e80b8b9ab655"},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history_c0c4.history['acc'])\nplt.plot(history_c0c4.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history_c0c4.history['loss'])\nplt.plot(history_c0c4.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"f05eb751be88cfa5fdd0d28aafeb35ca2ec07aa0"},"cell_type":"markdown","source":"## Creating training data for Safe vs operating_the_radio"},{"metadata":{"trusted":true,"_uuid":"545b1cbbc475777c9e2dc1565ee9c84b8e2c3412"},"cell_type":"code","source":"np_array_c0c5, y_c0c5 = feature_label.generate_npArray(training_data_c0,training_data_c5,img_size2,img_size1)\nx_train_c0c5,x_test_c0c5,y_train_c0c5,y_test_c0c5 = feature_label.train_and_split(np_array_c0c5,y_c0c5,0.3,100,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4d4d079c0bd37424c88747ca7723f47a3d2a6bf4"},"cell_type":"code","source":"# initializing the logistic regression classifier.\noutput_dim = nb_classes = 2\nbatch_size = 128 \nnb_epoch = 25\nmodel_c0c5 = Sequential() \nmodel_c0c5.add(BatchNormalization())\nmodel_c0c5.add(Dense(output_dim, input_dim=240*240, activation='softmax')) \nmodel_c0c5.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')\ncallbacks = [EarlyStopping(monitor='val_acc',patience=5,mode='max')]\nhistory_c0c5 = model_c0c5.fit(x_train_c0c5, y_train_c0c5, batch_size=batch_size, epochs=nb_epoch,verbose=1, validation_data=(x_test_c0c5, y_test_c0c5),callbacks=callbacks) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6bdc882d21678c35c59d26dc5a428c35f42ad57d"},"cell_type":"code","source":"model_c0c5.save_weights('./driverdistraction_operating_the_radio_weights.h5', overwrite=True)\nmodel_c0c5.save('./driverdistraction_lr_operating_the_radio.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1ac1ce0a90704c91803ec030901a32e3d4160b59"},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history_c0c5.history['acc'])\nplt.plot(history_c0c5.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history_c0c5.history['loss'])\nplt.plot(history_c0c5.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d56f0057c34aec38788f240a7c103287d20f6d20"},"cell_type":"markdown","source":"## Creating training data for Safe vs drinking"},{"metadata":{"trusted":true,"_uuid":"3f9a3504b378cab1f50a12c84e9c5da0cbfdfe31"},"cell_type":"code","source":"np_array_c0c6, y_c0c6 = feature_label.generate_npArray(training_data_c0,training_data_c6,img_size2,img_size1)\nx_train_c0c6,x_test_c0c6,y_train_c0c6,y_test_c0c6 = feature_label.train_and_split(np_array_c0c6,y_c0c6,0.3,100,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b6c88db3271670a7fba95b72d14487b32f5b3fa2"},"cell_type":"code","source":"# initializing the logistic regression classifier.\noutput_dim = nb_classes = 2\nbatch_size = 128 \nnb_epoch = 30\nmodel_c0c6 = Sequential() \nmodel_c0c6.add(BatchNormalization())\nmodel_c0c6.add(Dense(output_dim, input_dim=240*240, activation='softmax')) \nmodel_c0c6.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')\ncallbacks = [EarlyStopping(monitor='val_acc',patience=5,mode='max')]\nhistory_c0c6 = model_c0c6.fit(x_train_c0c6, y_train_c0c6, batch_size=batch_size, epochs=nb_epoch,verbose=1, validation_data=(x_test_c0c6, y_test_c0c6),callbacks=callbacks) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"368b696cf608dc46a6ba67ddb84367271ca90164"},"cell_type":"code","source":"model_c0c6.save_weights('./driverdistraction_drinking_weights.h5', overwrite=True)\nmodel_c0c6.save('./driverdistraction_lr_drinking.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cbccc2f8b45f2aba58a1579ef15f92f935837dfa"},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history_c0c6.history['acc'])\nplt.plot(history_c0c6.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history_c0c6.history['loss'])\nplt.plot(history_c0c6.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e1506b551b531725ee4a3926518f2d7dfbafc0eb"},"cell_type":"markdown","source":"## Creating training data for Safe vs reach_behind"},{"metadata":{"trusted":true,"_uuid":"596cbe730d3ce7114b4db41aa8d85b0e0de887df"},"cell_type":"code","source":"np_array_c0c7, y_c0c7 = feature_label.generate_npArray(training_data_c0,training_data_c7,img_size2,img_size1)\nx_train_c0c7,x_test_c0c7,y_train_c0c7,y_test_c0c7 = feature_label.train_and_split(np_array_c0c7,y_c0c7,0.3,100,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"580a835da3d0608e73b03ccceb47ef4d5a603f89"},"cell_type":"code","source":"# initializing the logistic regression classifier.\noutput_dim = nb_classes = 2\nbatch_size = 128 \nnb_epoch = 30\nmodel_c0c7 = Sequential() \nmodel_c0c7.add(BatchNormalization())\nmodel_c0c7.add(Dense(output_dim, input_dim=240*240, activation='softmax')) \nmodel_c0c7.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')\ncallbacks = [EarlyStopping(monitor='val_acc',patience=5,mode='max')]\nhistory_c0c7 = model_c0c7.fit(x_train_c0c7, y_train_c0c7, batch_size=batch_size, epochs=nb_epoch,verbose=1, validation_data=(x_test_c0c7, y_test_c0c7),callbacks=callbacks) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4f5129f6afa22c6184b1fa08cb2d840f1a5b203c"},"cell_type":"code","source":"model_c0c7.save_weights('./driverdistraction_reach_behind_weights.h5', overwrite=True)\nmodel_c0c7.save('./driverdistraction_lr_reach_behind.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3ad4ea4648e6dbdd41519e34ac6b87f67ee493f8"},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history_c0c7.history['acc'])\nplt.plot(history_c0c7.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history_c0c7.history['loss'])\nplt.plot(history_c0c7.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c49c97513ea50148ab8bc19390e6937b0af5785c"},"cell_type":"markdown","source":"## Creating training data for Safe vs hair_and_makeup"},{"metadata":{"trusted":true,"_uuid":"14b76538dd2c41629cdf4344bdba661d52e1b9fd"},"cell_type":"code","source":"np_array_c0c8, y_c0c8 = feature_label.generate_npArray(training_data_c0,training_data_c8,img_size2,img_size1)\nx_train_c0c8,x_test_c0c8,y_train_c0c8,y_test_c0c8 = feature_label.train_and_split(np_array_c0c8,y_c0c8,0.3,100,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cba4d3777e474c24ac54e8f01a9130148c9903bf"},"cell_type":"code","source":"# initializing the logistic regression classifier.\noutput_dim = nb_classes = 2\nbatch_size = 128 \nnb_epoch = 30\nmodel_c0c8 = Sequential() \nmodel_c0c8.add(BatchNormalization())\nmodel_c0c8.add(Dense(output_dim, input_dim=240*240, activation='softmax')) \nmodel_c0c8.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')\ncallbacks = [EarlyStopping(monitor='val_acc',patience=5,mode='max')]\nhistory_c0c8 = model_c0c8.fit(x_train_c0c8, y_train_c0c8, batch_size=batch_size, epochs=nb_epoch,verbose=1, validation_data=(x_test_c0c8, y_test_c0c8),callbacks=callbacks) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b3cd67feb8464742263658ad73dc11098d28edb6"},"cell_type":"code","source":"model_c0c8.save_weights('./driverdistraction_hair_and_makeup_weights.h5', overwrite=True)\nmodel_c0c8.save('./driverdistraction_lr_hair_and_makeup.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3d72492b15afdeaa5ad5494b634cf1d30a631636"},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history_c0c8.history['acc'])\nplt.plot(history_c0c8.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history_c0c8.history['loss'])\nplt.plot(history_c0c8.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"09393d7d8c337f516291732bc10d4d460605979e"},"cell_type":"markdown","source":"## Creating training data for Safe vs talking_to_the_passenger"},{"metadata":{"trusted":true,"_uuid":"b37305c435284d40aeab1f4744be58427380941c"},"cell_type":"code","source":"np_array_c0c9, y_c0c9 = feature_label.generate_npArray(training_data_c0,training_data_c9,img_size2,img_size1)\nx_train_c0c9,x_test_c0c9,y_train_c0c9,y_test_c0c9 = feature_label.train_and_split(np_array_c0c9,y_c0c9,0.3,100,2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1a711aed0a7102dde8c33534d1a36372257c03a1"},"cell_type":"code","source":"# initializing the logistic regression classifier.\noutput_dim = nb_classes = 2\nbatch_size = 128 \nnb_epoch = 25\nmodel_c0c9 = Sequential() \nmodel_c0c9.add(BatchNormalization())\nmodel_c0c9.add(Dense(output_dim, input_dim=240*240, activation='softmax')) \nmodel_c0c9.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')\ncallbacks = [EarlyStopping(monitor='val_acc',patience=5,mode='max')]\nhistory_c0c9 = model_c0c9.fit(x_train_c0c9, y_train_c0c9, batch_size=batch_size, epochs=nb_epoch,verbose=1, validation_data=(x_test_c0c9, y_test_c0c9),callbacks=callbacks) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f2bdf839cd945b295749dba826c66d08e81b8e2b"},"cell_type":"code","source":"model_c0c9.save_weights('./driverdistraction_talking_to_the_passenger_weights.h5', overwrite=True)\nmodel_c0c9.save('./driverdistraction_lr_talking_to_the_passenger.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"70d3609147617db43b71e4ed3fcdf7c5c3065ce5"},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history_c0c9.history['acc'])\nplt.plot(history_c0c9.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history_c0c9.history['loss'])\nplt.plot(history_c0c9.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a325ebfcdec377b3c9c507ba552644565e603988"},"cell_type":"code","source":"from sklearn.metrics import r2_score\ntest_data_ = np.array(test_data[3000][1]).reshape(-1,img_size2*img_size1)\nnew_img = cv2.resize(test_data[3000][1],(img_size2,img_size1))\nplt.imshow(new_img,cmap='gray')\nplt.show()\npred = model_c0c3.predict(test_data_)\n#r2_score(y_test, pred)\nprint(np.argmax(pred))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d6dfe0720090b5eaad739891c99532a9e3523def"},"cell_type":"code","source":"pred","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6180c71a17ebe1a53b907b24a87ce747e532df00"},"cell_type":"markdown","source":"    c0: safe driving\n    c1: texting - right\n    c2: talking on the phone - right\n    c3: texting - left\n    c4: talking on the phone - left\n    c5: operating the radio\n    c6: drinking\n    c7: reaching behind\n    c8: hair and makeup\n    c9: talking to passenger"},{"metadata":{"trusted":true,"_uuid":"097c65cac14961149c4e7dc5d48bba307aff623e"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}