{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"### this notebook is based on https://www.kaggle.com/ismailchaida/cnn-to-detect-driver-actions (CNN to detect driver actions)</br>\n### train data classes column</br>\n``c0: safe driving\nc1: texting - right\nc2: talking on the phone - right\nc3: texting - left\nc4: talking on the phone - left\nc5: operating the radio\nc6: drinking\nc7: reaching behind\nc8: hair and makeup\nc9: talking to passenger``","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"markdown","source":"# 1. import the Libraroes","metadata":{}},{"cell_type":"code","source":"import os\nfrom glob import glob\nimport random\nimport time\nimport tensorflow\nimport datetime\n\nos.environ['KERAS_BACKEND'] = 'tensorflow'\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\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","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:37:12.006462Z","iopub.execute_input":"2021-11-05T15:37:12.007243Z","iopub.status.idle":"2021-11-05T15:37:18.688098Z","shell.execute_reply.started":"2021-11-05T15:37:12.007207Z","shell.execute_reply":"2021-11-05T15:37:18.687407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2. import datasets","metadata":{}},{"cell_type":"code","source":"ls","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:37:18.689714Z","iopub.execute_input":"2021-11-05T15:37:18.690569Z","iopub.status.idle":"2021-11-05T15:37:19.49639Z","shell.execute_reply.started":"2021-11-05T15:37:18.690517Z","shell.execute_reply":"2021-11-05T15:37:19.495603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = pd.read_csv('../input/state-farm-distracted-driver-detection/driver_imgs_list.csv')\ndataset.head(10)","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:37:19.498592Z","iopub.execute_input":"2021-11-05T15:37:19.499274Z","iopub.status.idle":"2021-11-05T15:37:19.55459Z","shell.execute_reply.started":"2021-11-05T15:37:19.499221Z","shell.execute_reply":"2021-11-05T15:37:19.553652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 운전자 id를 분리함\nby_drivers = dataset.groupby('subject')\nunique_drivers = by_drivers.groups.keys()\nprint(unique_drivers)","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:37:19.555857Z","iopub.execute_input":"2021-11-05T15:37:19.55608Z","iopub.status.idle":"2021-11-05T15:37:19.573996Z","shell.execute_reply.started":"2021-11-05T15:37:19.556054Z","shell.execute_reply":"2021-11-05T15:37:19.573343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the dataset previously downloaded from Kaggle\nNUMBER_CLASSES = 10 # 분류 종류가 c0~c9 총 10개\n# Color type: 1 - grey, 3 - rgb\n\n# openCV 모듈의 imread()함수.\n# 이미지를 읽어오는 함수로 절대, 상대 경로 모두 가능. 두번째 인자인 option은 이미지를 grayscale로 읽을것인지 color로 읽을것인지 결정.\ndef get_cv2_image(path, img_rows, img_cols, color_type=3): # color_type이 안들어오면 default로 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    return img\n\n# Training\ndef load_train(img_rows, img_cols, color_type=3):\n    start_time = time.time()\n    train_images = [] \n    train_labels = []\n    # Loop over the training folder \n    for classed in tqdm(range(NUMBER_CLASSES)):\n        print('Loading directory c{}'.format(classed))\n        files = glob(os.path.join('..', 'input', 'state-farm-distracted-driver-detection', 'imgs', 'train', 'c' + str(classed), '*.jpg')) # 행동 분류별 train img 주소를 가져옴\n        for file in files:\n            img = get_cv2_image(file, img_rows, img_cols, color_type) # 각각의 이미지를 읽어옴.\n            train_images.append(img)\n            train_labels.append(classed)\n    print(\"Data Loaded in {} second\".format(time.time() - start_time))\n    return train_images, train_labels \n\ndef read_and_normalize_train_data(img_rows, img_cols, color_type):\n    X, labels = load_train(img_rows, img_cols, color_type)  # 전체 이미지를 모두 읽어옴\n    y = np_utils.to_categorical(labels, 10) # labels (c0 ~ c9)을 one-hot encoding\n    x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)  # train_test_split으로 적절한 테스트 범위를 나눠줌.\n    \n    x_train = np.array(x_train, dtype=np.uint8).reshape(-1,img_rows,img_cols,color_type)  # 기본적으로 CNN은 4차원 벡터를 사용한다. 따라서 reshape으로 데이터 형테를 4차원으로 조정한다.\n    x_test = np.array(x_test, dtype=np.uint8).reshape(-1,img_rows,img_cols,color_type)\n    \n    return x_train, x_test, y_train, y_test\n\n# Validation\ndef load_test(size=200000, img_rows=64, img_cols=64, color_type=3):\n    path = os.path.join('..', 'input', 'state-farm-distracted-driver-detection', 'imgs', 'test', '*.jpg')\n    files = sorted(glob(path))\n    X_test, 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 = get_cv2_image(file, img_rows, img_cols, color_type)\n        X_test.append(img)\n        X_test_id.append(file_base)\n        total += 1\n    return X_test, X_test_id\n\ndef read_and_normalize_sampled_test_data(size, img_rows, img_cols, color_type=3):\n    test_data, test_ids = load_test(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","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:37:19.576428Z","iopub.execute_input":"2021-11-05T15:37:19.576802Z","iopub.status.idle":"2021-11-05T15:37:19.593012Z","shell.execute_reply.started":"2021-11-05T15:37:19.576767Z","shell.execute_reply":"2021-11-05T15:37:19.592067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_rows = 64\nimg_cols = 64\ncolor_type = 1 # 회색조로 변경하기 위함.","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:37:19.594529Z","iopub.execute_input":"2021-11-05T15:37:19.594984Z","iopub.status.idle":"2021-11-05T15:37:19.611106Z","shell.execute_reply.started":"2021-11-05T15:37:19.594933Z","shell.execute_reply":"2021-11-05T15:37:19.610055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train, x_test, y_train, y_test = read_and_normalize_train_data(img_rows, img_cols, color_type)\nprint('Train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:37:19.612281Z","iopub.execute_input":"2021-11-05T15:37:19.612822Z","iopub.status.idle":"2021-11-05T15:40:16.389505Z","shell.execute_reply.started":"2021-11-05T15:37:19.61278Z","shell.execute_reply":"2021-11-05T15:40:16.387003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test data 중에 200개만 뽑아서 돌려봄\nnb_test_samples = 200\ntest_files, test_targets = read_and_normalize_sampled_test_data(nb_test_samples, img_rows, img_cols, color_type)\nprint('Test shape:', test_files.shape)\nprint(test_files.shape[0], 'Test samples')","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:16.391953Z","iopub.execute_input":"2021-11-05T15:40:16.393008Z","iopub.status.idle":"2021-11-05T15:40:20.006982Z","shell.execute_reply.started":"2021-11-05T15:40:16.392962Z","shell.execute_reply":"2021-11-05T15:40:20.006004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Statistics\n# Load the list of names\nnames = [item[17:19] for item in sorted(glob(\"../input/state-farm-distracted-driver-detection/imgs/train/*/\"))]  # 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)","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:20.008513Z","iopub.execute_input":"2021-11-05T15:40:20.00961Z","iopub.status.idle":"2021-11-05T15:40:20.246326Z","shell.execute_reply.started":"2021-11-05T15:40:20.009562Z","shell.execute_reply":"2021-11-05T15:40:20.245387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## visualization","metadata":{}},{"cell_type":"code","source":"# classes 분류는 전반적으로 골고루 분포되어있음\n# Plot figure size\nplt.figure(figsize = (10,10))\n# Count the number of images per category\nsns.countplot(x = 'classname', data = dataset)\n# Change the Axis names\nplt.ylabel('Count')\nplt.title('Categories Distribution')\n# Show plot\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:20.247824Z","iopub.execute_input":"2021-11-05T15:40:20.24813Z","iopub.status.idle":"2021-11-05T15:40:20.544482Z","shell.execute_reply.started":"2021-11-05T15:40:20.248088Z","shell.execute_reply":"2021-11-05T15:40:20.543636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Find the frequency of images per driver\ndrivers_id = pd.DataFrame((dataset['subject'].value_counts()).reset_index())\ndrivers_id.columns = ['driver_id', 'Counts']\ndrivers_id","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:20.545833Z","iopub.execute_input":"2021-11-05T15:40:20.546069Z","iopub.status.idle":"2021-11-05T15:40:20.563005Z","shell.execute_reply.started":"2021-11-05T15:40:20.546042Z","shell.execute_reply":"2021-11-05T15:40:20.562248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plotting class distribution\ndataset['class_type'] = dataset['classname'].str.extract('(\\d)',expand=False).astype(np.float) # dataset에 class_tyoe column을 만드는데 classname column의 숫자만 가져와 만든다\nplt.figure(figsize = (20,20))\ndataset.hist('class_type', alpha=0.5, layout=(1,1), bins=10)\nplt.title('Class distribution')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:20.564218Z","iopub.execute_input":"2021-11-05T15:40:20.564785Z","iopub.status.idle":"2021-11-05T15:40:20.807864Z","shell.execute_reply.started":"2021-11-05T15:40:20.564751Z","shell.execute_reply":"2021-11-05T15:40:20.806799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### images overview","metadata":{}},{"cell_type":"code","source":"activity_map = {'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":{"execution":{"iopub.status.busy":"2021-11-05T15:40:20.809239Z","iopub.execute_input":"2021-11-05T15:40:20.809526Z","iopub.status.idle":"2021-11-05T15:40:20.8146Z","shell.execute_reply.started":"2021-11-05T15:40:20.809486Z","shell.execute_reply":"2021-11-05T15:40:20.813578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 각 헹동별 첫번째 이미지를 출력해봄.\nplt.figure(figsize = (12, 20))\nimage_count = 1\nBASE_URL = '../input/state-farm-distracted-driver-detection/imgs/train/'\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(activity_map[directory])","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:20.818271Z","iopub.execute_input":"2021-11-05T15:40:20.818785Z","iopub.status.idle":"2021-11-05T15:40:22.971156Z","shell.execute_reply.started":"2021-11-05T15:40:20.81875Z","shell.execute_reply":"2021-11-05T15:40:22.970447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_submission(predictions, test_id, info):\n    result = pd.DataFrame(predictions, columns=['c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9'])\n    result.loc[:, 'img'] = pd.Series(test_id, index=result.index)\n    \n    now = datetime.datetime.now()\n    \n    if not os.path.isdir('kaggle_submissions'):\n        os.mkdir('kaggle_submissions')\n\n    suffix = \"{}_{}\".format(info,str(now.strftime(\"%Y-%m-%d-%H-%M\")))\n    sub_file = os.path.join('kaggle_submissions', 'submission_' + suffix + '.csv')\n    \n    result.to_csv(sub_file, index=False)\n    \n    return sub_file","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:22.972504Z","iopub.execute_input":"2021-11-05T15:40:22.972899Z","iopub.status.idle":"2021-11-05T15:40:22.978471Z","shell.execute_reply.started":"2021-11-05T15:40:22.972868Z","shell.execute_reply":"2021-11-05T15:40:22.977856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Create a vanilla CNN model</br>\n### Buliding the model</br>\ni'll develope the model with total 4 Convolutional layers, then a Faltten layer and then 2 Dense layers. i'll use the optimizer as rmsprop. and loss as categorical_crossentropy\n</br>.</br>\nhttps://bcho.tistory.com/1149 </br>\nhttps://davinci-ai.tistory.com/29 </br>\nhttps://bskyvision.com/427\n","metadata":{}},{"cell_type":"code","source":"batch_size = 40\nnb_epoch = 10","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:22.979634Z","iopub.execute_input":"2021-11-05T15:40:22.98014Z","iopub.status.idle":"2021-11-05T15:40:22.990907Z","shell.execute_reply.started":"2021-11-05T15:40:22.980108Z","shell.execute_reply":"2021-11-05T15:40:22.989856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!rm -f saved_models/weights_best_vanilla.hdf5","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:22.992802Z","iopub.execute_input":"2021-11-05T15:40:22.993568Z","iopub.status.idle":"2021-11-05T15:40:23.842095Z","shell.execute_reply.started":"2021-11-05T15:40:22.993515Z","shell.execute_reply":"2021-11-05T15:40:23.840673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 추후 모델 재사용을 위해 저장시켜둠\nmodels_dir = \"saved_models\"\nif not os.path.exists(models_dir):\n    os.makedirs(models_dir)\n\n# https://deep-deep-deep.tistory.com/53\n# performance measurment가 최소여야 하기 때문에 monitor를 val_loss, mode를 min으로 맞춰주었다.\n# save_best_only 옵션을 True로 줘서 무조건 해당 모델이 best 일때만 저장시켰다.\ncheckpointer = ModelCheckpoint(filepath='saved_models/weights_best_vanilla.hdf5', \n                               monitor='val_loss', mode='min',\n                               verbose=1, save_best_only=True)\n\n# EarlyStopping은 최적의 epoch를 찾기위한 함수로 monitor와 mode는 모델과 동일하게 맞춰 사용한다.\n# patience는 성능이 증가하지 않는 epoch 허용 횟수로 데이터마다 다르게 적용해야 한다.\n\nes = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=1)\n# patience를 1,2 둘다 돌려봤는데 1이면 epoch3까지 밖에 못가고 2면 9까지 간다.\ncallbacks = [checkpointer, es]","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:23.844118Z","iopub.execute_input":"2021-11-05T15:40:23.844418Z","iopub.status.idle":"2021-11-05T15:40:23.850715Z","shell.execute_reply.started":"2021-11-05T15:40:23.84438Z","shell.execute_reply":"2021-11-05T15:40:23.849833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### model version1","metadata":{}},{"cell_type":"code","source":"def create_model_v1():\n    # Vanilla CNN model\n    # sequential 모델은 모델을 선형으로 연결하여 구성. => 두번째 입력 데이터부터는 첫번째 형태를 그대로 받아드려 저장됨.\n    model = Sequential()\n\n    # filter가 64개이다. 따라서 출력의 depth도 64가 된다.\n    # activation function으로는 relu사용.\n    model.add(Conv2D(filters = 64, kernel_size = 3, padding='same', activation = 'relu', input_shape=(img_rows, img_cols, color_type)))\n    model.add(MaxPooling2D(pool_size = 2))\n\n    model.add(Conv2D(filters = 128, padding='same', kernel_size = 3, activation = 'relu'))\n    model.add(MaxPooling2D(pool_size = 2))\n\n    model.add(Conv2D(filters = 256, padding='same', kernel_size = 3, activation = 'relu'))\n    model.add(MaxPooling2D(pool_size = 2))\n\n    model.add(Conv2D(filters = 512, padding='same', kernel_size = 3, activation = 'relu'))\n    model.add(MaxPooling2D(pool_size = 2))\n\n    # dropout은 overfitting을 막기위한 방법\n    # 임의로 뉴런을 꺼서 학습을 방해 -> 학습이 학습용 데이터에 치우치지 않도록 조정하는 것.\n    model.add(Dropout(0.5))\n\n    # Dense와 같은 분류 함수를 실행시키기 위해선 데이터를 1차원으로 변경해야 함. 따라서 Flatten 수행.\n    model.add(Flatten())\n\n    model.add(Dense(500, activation = 'relu'))\n    model.add(Dropout(0.5))\n    \n    # softmax는 어떤 집단인지 분류하기 위해 큰값은 크게, 작은값은 작게 만들어 평균을 구하는 것.\n    model.add(Dense(10, activation = 'softmax'))\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:23.852044Z","iopub.execute_input":"2021-11-05T15:40:23.85234Z","iopub.status.idle":"2021-11-05T15:40:23.868334Z","shell.execute_reply.started":"2021-11-05T15:40:23.852284Z","shell.execute_reply":"2021-11-05T15:40:23.867629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_v1 = create_model_v1() # model version1 생성\n\n# More details about the layers\nmodel_v1.summary()\n\n# Compiling the model\nmodel_v1.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:23.870478Z","iopub.execute_input":"2021-11-05T15:40:23.871324Z","iopub.status.idle":"2021-11-05T15:40:24.186011Z","shell.execute_reply.started":"2021-11-05T15:40:23.871263Z","shell.execute_reply":"2021-11-05T15:40:24.185055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Training the Vanilla Model version 1\nhistory_v1 = model_v1.fit(x_train, y_train, \n          validation_data=(x_test, y_test),\n          callbacks=callbacks,\n          epochs=nb_epoch, batch_size=batch_size, verbose=1)\n\n# 특정 단계마다 callback을 불러와서 비교하게 된다.\n# 아래의 결과를 보면 매 epoch마다 fitting한 결과값과 callback으로 적용시킨 결과값을 비교해 더 나은 결과를 저장하고 있다.","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:40:24.187226Z","iopub.execute_input":"2021-11-05T15:40:24.187666Z","iopub.status.idle":"2021-11-05T15:52:30.899202Z","shell.execute_reply.started":"2021-11-05T15:40:24.187629Z","shell.execute_reply":"2021-11-05T15:52:30.898159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 가중치만 불러옴.\nmodel_v1.load_weights('saved_models/weights_best_vanilla.hdf5')","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:52:30.900776Z","iopub.execute_input":"2021-11-05T15:52:30.901054Z","iopub.status.idle":"2021-11-05T15:52:30.937511Z","shell.execute_reply.started":"2021-11-05T15:52:30.901022Z","shell.execute_reply":"2021-11-05T15:52:30.936884Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 이거랑 아래꺼는 안됨.\ndef plot_train_history(history):\n    # Summarize history for accuracy\n    plt.plot(history.history['acc'])\n    plt.plot(history.history['val_acc'])\n    plt.title('Model accuracy')\n    plt.ylabel('accuracy')\n    plt.xlabel('epoch')\n    plt.legend(['train', 'test'], loc='upper left')\n    plt.show()\n\n    # Summarize history for loss\n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.title('Model loss')\n    plt.ylabel('loss')\n    plt.xlabel('epoch')\n    plt.legend(['train', 'test'], loc='upper left')\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:52:30.938496Z","iopub.execute_input":"2021-11-05T15:52:30.939237Z","iopub.status.idle":"2021-11-05T15:52:30.947011Z","shell.execute_reply.started":"2021-11-05T15:52:30.939202Z","shell.execute_reply":"2021-11-05T15:52:30.946142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_train_history(history_v1)","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:52:30.948339Z","iopub.execute_input":"2021-11-05T15:52:30.948863Z","iopub.status.idle":"2021-11-05T15:52:31.205338Z","shell.execute_reply.started":"2021-11-05T15:52:30.948819Z","shell.execute_reply":"2021-11-05T15:52:31.204598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_test_class(model, test_files, image_number, color_type=1):\n    # 실제 이미지를 불러옴\n    img_brute = test_files[image_number]\n    img_brute = cv2.resize(img_brute,(img_rows,img_cols))\n    plt.imshow(img_brute, cmap='gray')\n\n    # 예측시킬 이미지를 생성함\n    new_img = img_brute.reshape(-1,img_rows,img_cols,color_type)\n\n    # 예측시킴\n    # classes를 categorical하게 one-hot encoding 처리 했으니까 그 값이 예측됨.\n    y_prediction = model.predict(new_img, batch_size=batch_size, verbose=1)\n    print('Y prediction: {}'.format(y_prediction))\n    print('Predicted: {}'.format(activity_map.get('c{}'.format(np.argmax(y_prediction)))))\n    \n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:53:46.53527Z","iopub.execute_input":"2021-11-05T15:53:46.535621Z","iopub.status.idle":"2021-11-05T15:53:46.543067Z","shell.execute_reply.started":"2021-11-05T15:53:46.535588Z","shell.execute_reply":"2021-11-05T15:53:46.542076Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score = model_v1.evaluate(x_test, y_test, verbose=1)\nprint('Score: ', score)","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:53:52.462434Z","iopub.execute_input":"2021-11-05T15:53:52.46306Z","iopub.status.idle":"2021-11-05T15:54:09.622386Z","shell.execute_reply.started":"2021-11-05T15:53:52.463023Z","shell.execute_reply":"2021-11-05T15:54:09.620046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_test_class(model_v1, test_files, 20)","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:54:25.060439Z","iopub.execute_input":"2021-11-05T15:54:25.060706Z","iopub.status.idle":"2021-11-05T15:54:25.438339Z","shell.execute_reply.started":"2021-11-05T15:54:25.060677Z","shell.execute_reply":"2021-11-05T15:54:25.437455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_test(img_rows, img_cols, color_type=3):\n    test_images = [] \n    files = glob(os.path.join('..', 'input', 'state-farm-distracted-driver-detection', 'imgs', 'test', '*.jpg')) # 전체 test data를 가져옴\n    for file in files:\n        img = get_cv2_image(file, img_rows, img_cols, color_type) # 각각의 이미지를 읽어옴.\n        test_images.append(img)\n    return test_images","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:54:30.781696Z","iopub.execute_input":"2021-11-05T15:54:30.782274Z","iopub.status.idle":"2021-11-05T15:54:30.787604Z","shell.execute_reply.started":"2021-11-05T15:54:30.782231Z","shell.execute_reply":"2021-11-05T15:54:30.786753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_images = load_test(img_rows, img_cols, 1)","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:54:33.581064Z","iopub.execute_input":"2021-11-05T15:54:33.581408Z","iopub.status.idle":"2021-11-05T16:09:52.909161Z","shell.execute_reply.started":"2021-11-05T15:54:33.581371Z","shell.execute_reply":"2021-11-05T16:09:52.908222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" y_prediction = model_v1.predict(test_images, batch_size=batch_size, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2021-11-05T16:10:52.682185Z","iopub.execute_input":"2021-11-05T16:10:52.682543Z","iopub.status.idle":"2021-11-05T16:31:34.664206Z","shell.execute_reply.started":"2021-11-05T16:10:52.682507Z","shell.execute_reply":"2021-11-05T16:31:34.552352Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output = pd.DataFrame(y_prediction, columns=['c0','c1','c2','c3','c4','c5','c6','c7','c8','c9'])\noutput.loc[: , 'img'] = pd.Series(test_images, index=output.index)\noutput.to_csv('submission.csv', index=False)\nprint(\"Your submission was successfully saved!\")","metadata":{"execution":{"iopub.status.busy":"2021-11-05T15:52:31.215085Z","iopub.status.idle":"2021-11-05T15:52:31.215735Z","shell.execute_reply.started":"2021-11-05T15:52:31.215436Z","shell.execute_reply":"2021-11-05T15:52:31.215465Z"},"trusted":true},"execution_count":null,"outputs":[]}]}