{"cells":[{"metadata":{},"cell_type":"markdown","source":"<h1><center><font size=\"6\">자동차 이미지 데이터셋을 이용한 자동차 차종 분류</font></center></h1>\n\n\n<h2><center><font size=\"4\">2019 3rd ML month with KaKR - EDA version</font></center></h2>\n\n<br>\n\n# **<a id='0'>Content</a>**\n\n- <a href='#1'>Introduction</a>  \n- <a href='#2'>Load Package and Data Check</a>\n- <a href='#3'>Data Exploration</a>"},{"metadata":{},"cell_type":"markdown","source":"<h2><font size=\"4\">다음 커널을 바탕으로 작성하였습니다.</font></h2>\n\n - Hyeonho Lee 님의 \"[3rd ML Month] Car Model Classification Baseline\" : https://www.kaggle.com/hyeonho/2019-3rd-ml-month-with-kakr-eda\n \n **감사합니다.**"},{"metadata":{},"cell_type":"markdown","source":"# **<a id='1'>Introduction</a>**\n\n\n#### **Competition background**\n우리가 살면서 갖고 싶은게 여러 가지가 있지만, 집 다음으로 보통 자동차 일 것입니다. 우리 주위에서 흔히 볼 수 있고, 편리한 교통 수단 중에 하나입니다. 전 세계적으로 그 수는 무려 10억대가 넘고, 그 종류는 수백, 수천 가지 이상 된다고 합니다.\n\n하지만, 이렇게 많은 차종을 구별하는 것은 사람일지라도 쉽지가 않은데요. 만약, 그림만 보고 자동차의 모델(Class)을 쉽게 예측할 수 있다면 CCTV나 블랙박스 속의 차량을 자동으로 분류, 감지해서 범죄예방에 도움을 줄 수 있는 등 다양한 곳에 유익하게 사용될 수 있습니다.\n\n이번 컴페티션에서는, 자동차 이미지 데이터셋을 활용하여 이미지에 해당하는 차종(Class)이 과연 무엇인지 예측해보겠습니다.\n\n#### **Evaluation**\n이번 컴페티션의 평가지표(Metric)은 F1 score 입니다.\n\n#### **Timeline**\n'19.06.14 ~ '19.08.17\n\n#### **Data**\n- train.csv - Train 셋의 이미지 파일명, 바운딩박스 좌표, 차종정보\n- test.csv - Test 셋의 이미지 파일명, 바운딩박스 좌표, 차종정보\n- submission.csv - Test셋과 대응되는 제출 파일\n- class.csv - 데이터 셋의 class 컬럼과 대응되는 차종의 레이블\n- train.zip - Train 이미지 파일\n- test.zip - Test 이미지 파일"},{"metadata":{},"cell_type":"markdown","source":"# **<a id='2'>Load Package and Data Check</a>**\n\n## Load Package"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\n\nimport cv2\nimport json\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n\nfrom PIL import Image\n\nfrom wordcloud import WordCloud\n\nimport warnings\nwarnings.filterwarnings(action='ignore')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"path = '../input/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(path+'train.csv')\ntest = pd.read_csv(path+'test.csv')\nclass_ = pd.read_csv(path+'class.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data Check - Text"},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class_.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class_.info()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data Check - Image"},{"metadata":{"trusted":true},"cell_type":"code","source":"def image_show(path, row=0, train_data=True):\n    if train_data:\n        img_name = train.iloc[row, 0]\n        img = np.asarray(Image.open(path + \"train/\" + img_name))\n    else:\n        img_name = test.iloc[row, 0]\n        img = np.asarray(Image.open(path + \"test/\" + img_name))\n    plt.imshow(img)        \n    plt.show()\n    \ndef image_object_show(path, row, train_data=True):\n    if train_data:\n        img_name, x, y, w, h = train.iloc[row, 0], train.iloc[row, 1], train.iloc[row, 2], train.iloc[row, 3], train.iloc[row, 4]\n        img = np.asarray(Image.open(path + \"train/\" + img_name))\n        cv2.rectangle(img,(x,y),(w,h),(0,255,0),4)\n    else:\n        img_name, x, y, w, h = test.iloc[row, 0], test.iloc[row, 1], test.iloc[row, 2], test.iloc[row, 3], test.iloc[row, 4]\n        img = np.asarray(Image.open(path + \"test/\" + img_name))\n        cv2.rectangle(img,(x,y),(w,h),(0,255,0),4)\n    plt.imshow(img)        \n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_show(path, 130)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_object_show(path, 130)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_show(path, 251)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_object_show(path, 251)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":" - 한가지 눈여겨볼 점은 여러가지 이미지를 보았을 때, 바운딩박스가 차에 완전히 딱 맞춰져 있지 않습니다."},{"metadata":{},"cell_type":"markdown","source":"# **<a id='3'>Data Exploration</a>**\n\n## Text"},{"metadata":{},"cell_type":"markdown","source":" - Class data의 Name을 보면 Name -> 자동차 회사 / 자동차 모델명 / 자동차 타입 / 년도로 구성이 되어 있는걸 확인 할 수 있습니다.\n - 위 기준을 바탕을로 Nmae 항목을 나눠서 새로운 항목을 생성합니다."},{"metadata":{"trusted":true},"cell_type":"code","source":"train['image_index'] = train.index\n\n# train data + class data \n# name -> company / car_model_name / car_body_type / year\ntrain = pd.merge(train, class_, how='left', left_on='class', right_on='id')\ntrain['company'] = train['name'].apply(lambda x: x.split(' ')[0])\n\ntrain['car_model_name'] = train['name'].apply(lambda x: x.split(' ')[1:-2])\ntrain['car_model_name'] = train.car_model_name.apply(', '.join)\ntrain['car_model_name'] = train['car_model_name'].str.replace(',','')\n\ntrain['car_body_type'] = train['name'].apply(lambda x: x.split(' ')[-2])\n\ntrain['year'] = train['name'].apply(lambda x: x.split(' ')[-1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['image_count'] = train['class'] / train['id']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"text = ''\nfor name in train['company']:\n    text += ' ' + name\n\nCompany = WordCloud(max_font_size=50, width=600, height=300, background_color='white').generate(text)\nplt.figure(figsize=(15,8))\nplt.imshow(Company)\nplt.title(\"- Company -\", fontsize=40, color='red')\nplt.axis(\"off\")\nplt.show() ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(70, 8))\nsns.countplot(x = train['company'], order = train['company'].value_counts().index)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Chevrolet, Dodge, Audi, BMW, Ford, Hyundai 회사 차들이 많은 수를 차지하고 있습니다."},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.crosstab(train['company'], train['car_body_type'], margins=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(70, 8))\nsns.countplot(x = train['company'], hue = 'car_body_type', data = train, order = train['company'].value_counts().index)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train.groupby(\"company\")['car_model_name'].value_counts()\n# train.groupby(\"company\")['car_body_type'].value_counts()\n# train.groupby(\"car_body_type\")['car_model_name'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.pivot_table(train,index=[\"company\",\"car_model_name\",\"car_body_type\"], values=[\"image_count\"],aggfunc=[np.sum])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.pivot_table(train,index=[\"company\",\"car_body_type\",\"car_model_name\"],values=[\"image_count\"],aggfunc=[np.sum])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.pivot_table(train,index=[\"company\",\"car_body_type\"],values=[\"image_count\"],aggfunc=[np.sum])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.pivot_table(train,index=[\"car_body_type\",\"car_model_name\"],values=[\"image_count\"],aggfunc=[np.sum])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(300, 8))\nsns.countplot(x = train['car_model_name'], order = train['car_model_name'].value_counts().index)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Golf**(Volkswagen) 등 15가지 자동차 모델이 100개 이상의 이미지 개수 차지하고 있습니다."},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(70, 8))\nsns.countplot(x = train['car_body_type'], order = train['car_body_type'].value_counts().index)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Sedan, SUV, Coupe, Convertible, Cab, Hatchback 차종이 대다수를 차지하고 있습니다."},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(20, 8))\nsns.countplot(x = train['year'], order = train['year'].value_counts().index)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"2012년식이 가장 많은 것을 알 수 있습니다."},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(len(train)):\n    img = Image.open(path + \"train/\" + train.iloc[i, 0])\n    img_size = list(img.size)\n    train.loc[i, 'width'] = img_size[0]\n    train.loc[i, 'height'] = img_size[1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(len(test)):\n    img = Image.open(path + \"test/\" + test.iloc[i, 0])\n    img_size = list(img.size)\n    test.loc[i, 'width'] = img_size[0]\n    test.loc[i, 'height'] = img_size[1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['cropped_width'] = abs(train['bbox_x1'] - train['bbox_x2'])\ntrain['cropped_height'] = abs(train['bbox_y1'] - train['bbox_y2'])\ntest['cropped_width'] = abs(test['bbox_x1'] - test['bbox_x2'])\ntest['cropped_height'] = abs(test['bbox_y1'] - test['bbox_y2'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"height = []\nwidth = []\ncropped_height = []\ncropped_width = []\nfor i in range(len(train)):\n    img = np.asarray(Image.open(path + \"train/\" + train.iloc[i, 0]))\n    height.append(img.shape[0])\n    width.append(img.shape[1])\n    cropped_height = train['cropped_height']\n    cropped_width = train['cropped_width']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.subplots(2, 2, figsize=(20, 6))\n\nplt.subplot(2, 2, 1)\nsns.distplot(height)\nplt.title('Height Distribution')\n\nplt.subplot(2, 2, 2)\nsns.distplot(width)\nplt.title('Widht Distribution')\n\nplt.subplot(2, 2, 3)\nsns.distplot(cropped_height)\nplt.title('cropped_Height Distribution')\n\nplt.subplot(2, 2, 4)\nsns.distplot(cropped_width)\nplt.title('cropped_Widht Distribution')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"(정확한 분석인지 모르겠지만...)\n원본 이미지에서 CROPPED 이미지로 변화를 보면, 넓이는 비슷한 분폴를 보이고 높이는 약간 달라지는 것을 확인 할 수 있습니다."},{"metadata":{},"cell_type":"markdown","source":"## Image"},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}