{"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 in \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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nprint(tf.__version__)\n\nimport os\nfrom glob import glob\nimport random\nimport time\nimport datetime\nfrom tqdm import tqdm\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, preprocess_input\n\n!pip install split_folders\nimport split_folders","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"split_folders.ratio('../input/state-farm-distracted-driver-detection/imgs/train', output='val', ratio=(.9, .1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls val","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model = VGG16(weights='imagenet',include_top=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = base_model.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(1024, activation='relu')(x)\nx = Dense(1024, activation='relu')(x)\nx = Dense(512, activation='relu')(x)\npreds = Dense(10, activation='softmax')(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Model(inputs=base_model.input, outputs=preds)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for layer in model.layers[:20]:\n  layer.trainable = False\n\nfor layer in model.layers[20:]:\n  layer.trainable = True","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\n\ntrain_generator=train_datagen.flow_from_directory('/kaggle/working/val/train/', # this is where you specify the path to the main data folder\n                                                 target_size=(224,224),\n                                                 color_mode='rgb',\n                                                 batch_size=32,\n                                                 class_mode='categorical',\n                                                 shuffle=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_generator=train_datagen.flow_from_directory('/kaggle/working/val/val/', # this is where you specify the path to the main data folder\n                                                 target_size=(224,224),\n                                                 color_mode='rgb',\n                                                 batch_size=32,\n                                                 class_mode='categorical',\n                                                 shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plotImages(images_arr):\n    fig, axes = plt.subplots(1, 5, figsize=(20,20))\n    axes = axes.flatten()\n    for img, ax in zip(images_arr, axes):\n        ax.imshow(img)\n    plt.tight_layout()\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"augmented_images = [val_generator[0][0][0] for i in range(5)]\nplotImages(augmented_images)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"es = EarlyStopping(monitor='val_loss', mode=\"min\", verbose=1, patience=3)\nmc = ModelCheckpoint('TL_model_vgg16.h5', monitor='val_acc', mode='max', save_best_only=True, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"step_size_train=train_generator.n//train_generator.batch_size\nstep_size_val=val_generator.n//val_generator.batch_size\nhistory = model.fit_generator(generator=train_generator,\n                   steps_per_epoch=step_size_train,\n                    validation_data=val_generator,\n                    validation_steps=step_size_val,\n                   epochs=10,\n                    callbacks=[es, mc])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(10)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame(history.history).plot(figsize=(8, 5))\nplt.grid(True)\nplt.gca().set_ylim(0, 1.5)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"model.save(\"vgg16.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class_names = ['Safe driving', 'texting right', 'talking on the phone - right', 'texting left', \n              'talking on the phone - left', 'operating the radio', 'drinking', 'reaching behind', \n              'hair and makeup', 'talking to passenger']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"my_model = tf.keras.models.load_model(\"../input/models/my_VGG16.h5\")\nmy_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image\nfrom tensorflow.keras.applications import imagenet_utils\npath = \"../input/state-farm-distracted-driver-detection/imgs/test/img_80059.jpg\"\nimg=image.load_img(path, target_size=(224, 224))\nx=image.img_to_array(img)\nx=np.expand_dims(x, axis=0)\nimage = imagenet_utils.preprocess_input(x)\npreds = my_model.predict(image)\ni = np.argmax(preds[0])\n# print(preds)\nprint(\"Predicted class:\", class_names[i])\nimg","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":1}