캐글 데이터 다운로드 받기 (via Colab)

Page content

강의 홍보

I. 개요

  • 데이터 시각화와 변환에 대해 짧게 익혔다면 바로 실전 데이터를 활용한다.
  • 이론이 조금 부족하게 느껴질 수 있지만, 모든 것을 다 알려드릴 수는 없다.
    • 결국 공부는 스스로 해야 한다.
  • 이 강의의 목적이 Kaggle 데이터를 활용한 Python 포트폴리오 제작 강의임을 잊지 말자.
  • 이번 시간에는 Kaggle 데이터를 구글 드라이브로 다운로드 받는 방법에 대해 작성하였다.

II. Kaggle KPI 설치

  • Google Colab에서 Kaggle API를 불러오려면 다음 소스코드를 실행한다.
!pip install kaggle
Requirement already satisfied: kaggle in /usr/local/lib/python3.6/dist-packages (1.5.6)
Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from kaggle) (2.23.0)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from kaggle) (1.24.3)
Requirement already satisfied: python-slugify in /usr/local/lib/python3.6/dist-packages (from kaggle) (4.0.0)
Requirement already satisfied: python-dateutil in /usr/local/lib/python3.6/dist-packages (from kaggle) (2.8.1)
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from kaggle) (4.41.1)
Requirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from kaggle) (2020.4.5.1)
Requirement already satisfied: six>=1.10 in /usr/local/lib/python3.6/dist-packages (from kaggle) (1.12.0)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->kaggle) (2.9)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->kaggle) (3.0.4)
Requirement already satisfied: text-unidecode>=1.3 in /usr/local/lib/python3.6/dist-packages (from python-slugify->kaggle) (1.3)

III. Kaggle Token 다운로드

  • Kaggle에서 API Token을 다운로드 받는다.
  • [Kaggle]-[My Account]-[API]-[Create New API Token]을 누르면 kaggle.json 파일이 다운로드 된다.
  • 이 파일을 바탕화면에 옮긴 뒤, 아래 코드를 실행 시킨다.
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
  print('uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))
  
# kaggle.json을 아래 폴더로 옮긴 뒤, file을 사용할 수 있도록 권한을 부여한다. 
!mkdir -p ~/.kaggle/ && mv kaggle.json ~/.kaggle/ && chmod 600 ~/.kaggle/kaggle.json
Upload widget is only available when the cell has been executed in the current browser session. Please rerun this cell to enable.
Saving kaggle.json to kaggle.json
uploaded file "kaggle.json" with length 64 bytes
ls -1ha ~/.kaggle/kaggle.json
ls: cannot access '/root/.kaggle/kaggle.json': No such file or directory
  • 에러 메시지가 없으면 성공적으로 json 파일이 업로드 되었다는 뜻이다.

IV. 구글 드라이브 연동

  • 데이터를 불러오기 전에 구글 드라이브와 연동하는 작업을 우선 진행한다.
  • 매우 쉽다. 그러니 천천히 따라와주시기를 바란다.

(1) 구글 드라이브 마운트

  • 다음 소스코드를 통해서 구글 드라이브와 마운트를 진행한다.
    • 쉽게 표현하면 구글 코랩에서 드라이브로 접근을 하겠다는 뜻이다.
    • 아래 소스 코드를 실행 하면 본인 인증 절차를 진행하면 된다.
from google.colab import drive # 패키지 불러오기 

ROOT = "/content/drive"     # 드라이브 기본 경로
print(ROOT)                 # print content of ROOT (Optional)
drive.mount(ROOT)           # 드라이브 기본 경로 Mount
/content/drive
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).

(2) 프로젝트 파일 생성 및 다운받을 경로 이동

  • 구글 코랩을 실행하면 Drive에 Colab Notebooks 폴더가 생성이 된다.
  • 일종의 Colab Project 폴더로 생각하자.
  • 이 때 본인만의 프로젝트 폴더를 만들자. (주의: 폴더 이름은 반드시 영어명과 공백없이 만든다)
    • 예: 내프로젝트 또는 my project와 같이 만들지 않는다.
    • 강사는 inflearn_kaggle이라고 만들었다.
  • 프로젝트 폴더를 생성했으면 이제 아래코드를 실행시킨다.
from os.path import join  

MY_GOOGLE_DRIVE_PATH = 'My Drive/Colab Notebooks/inflearn_kaggle/data'
PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH)
print(PROJECT_PATH)
/content/drive/My Drive/Colab Notebooks/inflearn_kaggle/data
  • 위 소스코드는 PROJECT_PATH를 만드는 코드다.
  • 만들어진 PROJECT_PATH를 아래와 같이 적용하면 구글 드라이브 내 해당 폴더로 이동하게 된다.
%cd "{PROJECT_PATH}"
/content/drive/My Drive/Colab Notebooks/inflearn_kaggle/data

V. Kaggle 데이터 불러오기

  • 먼저 kaggle competition list를 불러온다.
!kaggle competitions list
Warning: Looks like you're using an outdated API Version, please consider updating (server 1.5.6 / client 1.5.4)
ref                                               deadline             category            reward  teamCount  userHasEntered  
------------------------------------------------  -------------------  ---------------  ---------  ---------  --------------  
digit-recognizer                                  2030-01-01 00:00:00  Getting Started  Knowledge       3152           False  
titanic                                           2030-01-01 00:00:00  Getting Started  Knowledge      23304            True  
house-prices-advanced-regression-techniques       2030-01-01 00:00:00  Getting Started  Knowledge       5364            True  
connectx                                          2030-01-01 00:00:00  Getting Started  Knowledge        389           False  
nlp-getting-started                               2030-01-01 00:00:00  Getting Started      Kudos       1704            True  
competitive-data-science-predict-future-sales     2020-12-31 23:59:00  Playground           Kudos       7210           False  
siim-isic-melanoma-classification                 2020-08-17 23:59:00  Featured           $30,000        637           False  
global-wheat-detection                            2020-08-04 23:59:00  Research           $15,000        714           False  
open-images-object-detection-rvc-2020             2020-07-31 16:00:00  Playground       Knowledge         22           False  
open-images-instance-segmentation-rvc-2020        2020-07-31 16:00:00  Playground       Knowledge          5           False  
hashcode-photo-slideshow                          2020-07-27 23:59:00  Playground       Knowledge         33           False  
prostate-cancer-grade-assessment                  2020-07-22 23:59:00  Featured           $25,000        531           False  
alaska2-image-steganalysis                        2020-07-20 23:59:00  Research           $25,000        471           False  
halite                                            2020-06-30 23:59:00  Featured             Kudos          0           False  
m5-forecasting-accuracy                           2020-06-30 23:59:00  Featured           $50,000       4749            True  
m5-forecasting-uncertainty                        2020-06-30 23:59:00  Featured           $50,000        572           False  
trends-assessment-prediction                      2020-06-29 23:59:00  Research           $25,000        597           False  
jigsaw-multilingual-toxic-comment-classification  2020-06-22 23:59:00  Featured           $50,000       1277           False  
tweet-sentiment-extraction                        2020-06-16 23:59:00  Featured           $15,000       1869           False  
trec-covid-information-retrieval                  2020-06-03 11:00:00  Research             Kudos         19           False  
  • 여기에서 참여하기 원하는 대회의 데이터셋을 불러오면 된다.
  • 이번 basic강의에서는 house-prices-advanced-regression-techniques 데이터를 활용한 데이터 가공과 시각화를 연습할 것이기 때문에 아래와 같이 코드를 실행하여 데이터를 불러온다.
!kaggle competitions download -c house-prices-advanced-regression-techniques
Warning: Looks like you're using an outdated API Version, please consider updating (server 1.5.6 / client 1.5.4)
Downloading sample_submission.csv to /content/drive/My Drive/Colab Notebooks/inflearn_kaggle/data
  0% 0.00/31.2k [00:00<?, ?B/s]
100% 31.2k/31.2k [00:00<00:00, 4.73MB/s]
Downloading train.csv to /content/drive/My Drive/Colab Notebooks/inflearn_kaggle/data
  0% 0.00/450k [00:00<?, ?B/s]
100% 450k/450k [00:00<00:00, 30.0MB/s]
Downloading test.csv to /content/drive/My Drive/Colab Notebooks/inflearn_kaggle/data
  0% 0.00/441k [00:00<?, ?B/s]
100% 441k/441k [00:00<00:00, 29.0MB/s]
Downloading data_description.txt to /content/drive/My Drive/Colab Notebooks/inflearn_kaggle/data
  0% 0.00/13.1k [00:00<?, ?B/s]
100% 13.1k/13.1k [00:00<00:00, 1.83MB/s]
!ls
data_description.txt  sample_submission.csv  test.csv  train.csv
  • 현재 총 4개의 데이터를 다운로드 받았다.
    • data_description.txt
    • sample_submission.csv
    • test.csv
    • train.csv

VI. What’s Next

  • Google Colab에서 Kaggle API를 활용하여 데이터를 불러오는 것을 실습하였다.
  • Kaggle에서 받은 데이터를 구글 드라이브에 바로 저장하는 방법을 배웠다.
  • 다음 시간에는 데이터를 불러온 뒤 이제 본격적인 EDA를 단계별로 진행한다. (Stay with Me)

VII. 옵션

  • 구글 코랩은 참고로 한글폰트를 지원하지 않는다. 따라서, 한글 폰트를 꼭 실무에서 사용하고 싶은 분들은 아래 Reference에 관련 내용을 같이 첨부한 것이 있으니 확인하시기를 바란다.
  • 본 튜토리얼에서 Kaggle 데이터는 모두 영어이기에 한글폰트는 따로 사용하지 않는다.

Reference

출처: https://chloevan.github.io/settings/kakao_arena_3_eda/