{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"collapsed":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\n# import numpy as np # linear algebra\n# import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n# import cv2\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\n# import os\n# for 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 20GB 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":{"trusted":true},"cell_type":"code","source":"%config Completer.use_jedi = False\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\n\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D\nfrom tensorflow.keras import Model\nimport pandas as pd\nimport cv2\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras import datasets, layers, models\nimport matplotlib.pyplot as plt\nimport numpy as np\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = pd.read_csv('/kaggle/input/state-farm-distracted-driver-detection/driver_imgs_list.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = cv2.imread('/kaggle/input/state-farm-distracted-driver-detection/imgs/train/c0/img_25094.jpg')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_im_cv2(path, img_rows, img_cols, color_type=3):\n    # Load as grayscale\n#     if color_type == 1:\n    img = cv2.imread(path,0)\n#     elif color_type == 3:\n#         img = cv2.imread(path)\n    #Reduce size\n    resized = cv2.resize(img, (img_cols, img_rows))\n    return resized","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = data[['img']]\ny = data[['classname']]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)\nprint(X_train.shape)\nprint(X_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)\nprint(X_train.columns,y_train.columns)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nplt.figure(figsize=(30,30))\nfor i in range(5):\n    plt.subplot(5,5,i+1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(True)\n    path = \"/kaggle/input/state-farm-distracted-driver-detection/imgs/train/{}/{}\".format(y.loc[i+3,'classname'],X.loc[i+3,'img'])\n    train_image= get_im_cv2(path,200,200)\n    print(train_image.shape)\n#     print(train_image)\n#     print(type(train_image))\n\n    plt.imshow(train_image)\n    # The CIFAR labels happen to be arrays, \n    # which is why you need the extra index\n    plt.xlabel(\"_{}\".format(train_image.shape))\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = models.Sequential()\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 1)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":" model.summary()\n\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_train_arr = []\nfor i in range(len(X_train)):\n#     print((X_train.loc[i,'']))\n#     print(y_train.iloc[i,0],X_train.iloc[i,0])\n#     break\n\n    path = \"/kaggle/input/state-farm-distracted-driver-detection/imgs/train/{}/{}\".format(y_train.iloc[i,0],X_train.iloc[i,0])\n    resized = get_im_cv2(path,32,32)\n    image_train_arr.append(resized)\n#     print(data.loc[i,'images'])\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_test_arr = []\nfor i in range(len(X_test)):\n#     print((X_train.loc[i,'']))\n#     print(y_train.iloc[i,0],X_train.iloc[i,0])\n#     break\n\n    path = \"/kaggle/input/state-farm-distracted-driver-detection/imgs/train/{}/{}\".format(y_test.iloc[i,0],X_test.iloc[i,0])\n    resized = get_im_cv2(path,32,32)\n    image_test_arr.append(resized)\n#     print(data.loc[i,'images'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_train_arr = np.array(image_train_arr)\nimage_test_arr = np.array(image_test_arr)\nprint(image_train_arr.shape,image_test_arr.shape)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_train_arr,image_test_arr = image_train_arr/255.0, image_test_arr/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.add(layers.Flatten())\nmodel.add(layers.Dense(64, activation='relu'))\nmodel.add(layers.Dense(10))\nmodel.add(Dense(10, activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"type(image_test_arr),type(y_test)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_test_arr.shape,y_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_train_arr = image_train_arr.reshape(15024,32,32,1)\nimage_test_arr = image_test_arr.reshape(7400,32,32,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nlabelencoder = LabelEncoder()\ny_train['new-col'] = labelencoder.fit_transform(y_train)\ny_test['new-col'] = labelencoder.fit_transform(y_test)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_test['new-col']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam',\n              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n              metrics=['accuracy'])\n\nhistory = model.fit(image_train_arr, y_train['new-col'], epochs=30,validation_data=(image_test_arr, y_test['new-col']))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"With 10 Epoch we got 0.9723 accuracy\nWith 30 Epoch we got 0.9723 accuracy\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['val_accuracy'], label = 'val_accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.ylim([0.5, 1.1])\nplt.legend(loc='lower right')\n\ntest_loss, test_acc = model.evaluate(image_test_arr, y_test['new-col'], verbose=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data = pd.read_csv('/kaggle/input/state-farm-distracted-driver-detection/sample_submission.csv')\ntest_data.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_arr = []\nfor i in range(len(test_data)):\n#     print((X_train.loc[i,'']))\n#     print(y_train.iloc[i,0],X_train.iloc[i,0])\n#     break\n\n    path = \"/kaggle/input/state-farm-distracted-driver-detection/imgs/test/{}\".format(test_data.iloc[i,0])\n    resized = get_im_cv2(path,32,32)\n    test_arr.append(resized)\n#     print(data.loc[i,'images'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_arr=np.array(test_arr)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_arr.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_arr_norm =test_arr/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_arr_norm= test_arr_norm.reshape(79726,32,32,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_output_arr = model.predict(test_arr_norm)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_output_arr","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_output_arr.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_output_prob = pd.DataFrame(test_output_arr)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"type(test_output_prob)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range (len(test_output_prob.columns)):\n    test_output_prob[\"c{}\".format(i)] = test_output_prob.iloc[:,i]\nprint(test_output_prob.columns)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_output_prob.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test=test_output_prob.drop([0,1,2,3,4,5,6,7,8,9], axis = 1) \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.columns\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result = pd.concat([test_data.iloc[:,0], test], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result.shape,result.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result.isnull().values.any()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result.to_csv(r'result.csv',index=False)","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}