{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":false},"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    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":"image_csv = pd.read_csv('../input/state-farm-distracted-driver-detection/driver_imgs_list.csv')\nimage_csv\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_csv['file_path'] = image_csv['classname'].astype(str) + '/' + image_csv['img'].astype(str)\nimage_csv","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntraining, validation = train_test_split(image_csv, random_state = 1, test_size = 0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Image size is (480, 640, 3), We will use the same size for data as well to avoid distortion\ntrain_datagen = ImageDataGenerator(rescale = 1.0/255)\ntrain_generator = train_datagen.flow_from_dataframe(training,\n                                                directory = '../input/state-farm-distracted-driver-detection/imgs/train',\n                                                x_col = 'file_path',\n                                                y_col = 'classname',\n                                                target_size = (480, 640),\n                                               # Keeping batch size default as 32\n                                                class_mode='categorical')\n\nvalid_datagen = ImageDataGenerator(rescale = 1.0/255)\nvalid_generator = valid_datagen.flow_from_dataframe(validation,\n                                                directory = '../input/state-farm-distracted-driver-detection/imgs/train',\n                                                x_col = 'file_path',\n                                                y_col = 'classname',\n                                                target_size = (480, 640),\n                                               # Keeping batch size default as 32\n                                                class_mode='categorical')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.optimizers import Adam","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    Conv2D(32, kernel_size = (2, 2), padding = 'same', activation = 'relu', use_bias = True, input_shape = (480, 640, 3)),\n    MaxPooling2D(pool_size=(2, 2)),\n    Conv2D(64, kernel_size = (2, 2), padding = 'same', activation = 'relu', use_bias = True),\n    MaxPooling2D(pool_size=(2, 2)),\n    Conv2D(128, kernel_size = (2, 2), padding = 'same', activation = 'relu', use_bias = True),\n    MaxPooling2D(pool_size=(2, 2)),\n#   Dense Layer after the Convo Layers, we will flatten the image data and pass to dense layer\n    Flatten(),\n    Dense(1024, activation='relu'),\n    Dense(10, activation='softmax')\n])\n\nmodel.compile(optimizer = Adam(lr = 0.0015), loss = 'categorical_crossentropy', metrics = ['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"es = EarlyStopping(monitor='val_acc', patience=2, min_delta = 0.01)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit_generator(train_generator,\n          epochs = 10,\n          verbose = 2,\n          validation_data = valid_generator,\n          callbacks = [es])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.predict(img_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from matplotlib import image\nfrom matplotlib import pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = image.imread('../input/state-farm-distracted-driver-detection/imgs/test/img_1.jpg')\nimg1 = image.imread('../input/state-farm-distracted-driver-detection/imgs/train/c5/img_100136.jpg')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_data = np.array(img)\nimg_data = img_data.reshape(-1, 480, 640, 3)\nplt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(img1)","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}