{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    \n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from glob import glob\nimport random\nimport os\nimport time\nimport tensorflow\nimport datetime\nos.environ['KERAS_BACKEND'] = 'tensorflow'\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # 3 = INFO, WARNING, and ERROR messages are not printed\n\nfrom tqdm import tqdm\n\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import FileLink\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings('ignore')\nimport seaborn as sns \n%matplotlib inline\nfrom IPython.display import display, Image\nimport matplotlib.image as mpimg\nimport cv2\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_files       \nfrom keras.utils import np_utils\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import log_loss\n\nfrom keras.models import Sequential, Model\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization, GlobalAveragePooling2D\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing import image\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom keras.applications.vgg16 import VGG16","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset = pd.read_csv('../input/state-farm-distracted-driver-detection/driver_imgs_list.csv')\ndataset.head(5)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"drivers = dataset.groupby('subject')\nunique_drivers = drivers.groups.keys()\nprint(unique_drivers)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_image(path, img_rows, img_cols, channels=3):\n    # Loading as Grayscale image\n    if color_type == 1:\n        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n    elif color_type == 3:\n        img = cv2.imread(path, cv2.IMREAD_COLOR)\n    # Reduce size\n    img = cv2.resize(img, (img_rows, img_cols)) \n\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes=10\ndef load_train_images(img_rows,img_clos,channels):\n    start_time=time.time()\n    train_imgs=[]\n    train_labels=[]\n    for classes in tqdm(range(num_classes)):\n        print(\"loading directory:c{}\".format(classes))\n        files = glob(os.path.join('..', 'input','state-farm-distracted-driver-detection','imgs','train', 'c' + str(classes), '*.jpg'))\n        for file in files:\n            img=load_image(file,img_rows,img_cols,channels)\n            train_imgs.append(img)\n            train_labels.append(classes)\n        print(\"data loaded in {} seconds\".format(time.time()-start_time))\n    return train_imgs,train_labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def modified_data(img_rows, img_cols, channels):\n    x,labels=load_train_images(img_rows,img_cols,channels=3)\n    y=np_utils.to_categorical(labels,10)\n    x_train,x_test,y_train,y_test=train_test_split(x, y, test_size=0.2, random_state=42)\n    x_train = np.array(x_train, dtype=np.uint8).reshape(-1,img_rows,img_cols,channels)\n    x_test = np.array(x_test, dtype=np.uint8).reshape(-1,img_rows,img_cols,channels)\n    \n    return x_train, x_test, y_train, y_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"../input/state-farm-distracted-driver-detection/imgs/test/img_100000.jpg","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_test_images(size=200000, img_rows=64, img_cols=64, channels=3):\n    path = os.path.join('..', 'input','state-farm-distracted-driver-detection','imgs','test', '*.jpg')\n    files = sorted(glob(path))\n    X_test_images=[]\n    X_test_id = []\n    total = 0\n    files_size = len(files)\n    for file in tqdm(files):\n        if total >= size or total >= files_size:\n            break\n        file_base = os.path.basename(file)\n        img = load_image(file, img_rows, img_cols, channels)\n        X_test_images.append(img)\n        X_test_id.append(file_base)\n        total += 1\n    return X_test_images, X_test_id","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def modified_test_images(size, img_rows, img_cols, channels=3):\n    test_data, test_ids = load_test_images(size, img_rows, img_cols, color_type)\n    \n    test_data = np.array(test_data, dtype=np.uint8)\n    test_data = test_data.reshape(-1,img_rows,img_cols,color_type)\n    \n    return test_data, test_ids","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_rows = 64\nimg_cols = 64\nchannels = 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, x_test, y_train, y_test = modified_data(img_rows, img_cols, channels)\nprint('Train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nb_test_samples = 200\ntest_files, test_targets = modified_test_images(nb_test_samples, img_rows, img_cols, channels)\nprint('Test shape:', test_files.shape)\nprint(test_files.shape[0], 'Test samples')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"names = [item[17:19] for item in sorted(glob(\"../input/state-farm-distracted-driver-detection/imgs/train/*/\"))]\ntest_files_size = len(np.array(glob(os.path.join('..', 'input','state-farm-distracted-driver-detection','imgs','test', '*.jpg'))))\nx_train_size = len(x_train)\ncategories_size = len(names)\nx_test_size = len(x_test)\nprint('There are %s total images.\\n' % (test_files_size + x_train_size + x_test_size))\nprint('There are %d training images.' % x_train_size)\nprint('There are %d total training categories.' % categories_size)\nprint('There are %d validation images.' % x_test_size)\nprint('There are %d test images.'% test_files_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (10,10))\nsns.countplot(x = 'classname', data = dataset)\nplt.ylabel('Count')\nplt.title('Categories Distribution')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"drivers_id = pd.DataFrame((dataset['subject'].value_counts()).reset_index())\ndrivers_id.columns = ['driver_id', 'Counts']\ndrivers_id","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"driver_activity = {'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'}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12,20))\nimage_count = 1\nBASE_URL = '../input/train/state-farm-distracted-driver-detection/imgs/'\nfor directory in os.listdir(BASE_URL):\n    if directory[0] != '.':\n        for i, file in enumerate(os.listdir(BASE_URL + directory)):\n            if i == 1:\n                break\n            else:\n                fig = plt.subplot(5, 2, image_count)\n                image_count += 1\n                image = mpimg.imread(BASE_URL + directory + '/' + file)\n                plt.imshow(image)\n                plt.title(driver_activity[directory])\n","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}