LoginSignup
105
107

More than 5 years have passed since last update.

Google Colaboratory で始める Kaggler 生活(データ入手と提出編)

Last updated at Posted at 2018-03-26

Google Colaboratory で Kaggle コンペに参加したいときの
データの入手方法や提出方法についてまとめました。

実際の学習を行う部分は省略していますのでご注意ください。

記事よりも下記の成果物とリンク見たほうが早いと思います。

リンク

必要なもの

  • Google アカウント
  • Google Chrome

各手順

お好きなノートブック上で以下のコマンドを打ってください。

1. kaggle コマンド(api) のインストール

!pip install kaggle
Collecting kaggle
  Downloading kaggle-1.1.0.tar.gz
Requirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from kaggle)
Requirement already satisfied: python-dateutil in /usr/local/lib/python3.6/dist-packages (from kaggle)
Requirement already satisfied: six>=1.10 in /usr/local/lib/python3.6/dist-packages (from kaggle)
Requirement already satisfied: urllib3>=1.15 in /usr/local/lib/python3.6/dist-packages (from kaggle)
Building wheels for collected packages: kaggle
  Running setup.py bdist_wheel for kaggle ... - done
  Stored in directory: /content/.cache/pip/wheels/2a/cc/c6/e4c872c053261660031b4a3e35ac958725b284c6fde9ff05c8
Successfully built kaggle
Installing collected packages: kaggle
Successfully installed kaggle-1.1.0

ただしこれだけではまだ API は使えません。

!kaggle datasets list
## => Unauthorized: you must download an API key from https://www.kaggle.com/<username>/account
## => Then put kaggle.json in the folder /content/.kaggle

次に API key を入手します。

2. Kaggle API Key の入手

  • https://www.kaggle.com/<UserName>/account で自分のアカウントページを開いてください
  • 上記ページ内の Create New API Token をクリックして kaggle.json をダウンロードしてください
    • API Key が載ってるので、扱いには注意

3. Google ドライブに kaggle.json をアップロード

  • https://drive.google.com/drive/my-drive を開いてください
  • ドライブ上の好きな場所に kaggle.json をアップロードしてください
    • ドラッグ & ドロップで OK です

4. Google ドライブから Colaboratory 上に kaggle.json をダウンロード

# download API key from google drive
## Original: https://colab.research.google.com/drive/1eufc8aNCdjHbrBhuy7M7X6BGyzAyRbrF#scrollTo=y5_288BYp6H1
## When you run for the first time, you will see a link to authenticate.

from googleapiclient.discovery import build
import io, os
from googleapiclient.http import MediaIoBaseDownload
from google.colab import auth

auth.authenticate_user()

drive_service = build('drive', 'v3')
results = drive_service.files().list(
        q="name = 'kaggle.json'", fields="files(id)").execute()
kaggle_api_key = results.get('files', [])

filename = "/content/.kaggle/kaggle.json"
os.makedirs(os.path.dirname(filename), exist_ok=True)

request = drive_service.files().get_media(fileId=kaggle_api_key[0]['id'])
fh = io.FileIO(filename, 'wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%." % int(status.progress() * 100))
os.chmod(filename, 600)
  • 初回実行時は Google アカウント認証ページが表示されます
    • 別タブで認証ページ開いてください
  • 認証したらコードが表示されるので、コードをコピーしてセルの下にある入力欄に入力してください
  • 上手く認証できればダウンロードされて Download 100%. と表示されます。

これで API が使えるようになります。 !kaggle competitions list などを打ち込んでみてください。
詳細は ここ で確認してください。

5. コンペに必要なデータのダウンロード

ここでは 3月26日現在開催中のコンペ "TalkingData AdTracking Fraud Detection Challenge" に必要なデータをダウンロードします。

5.1 コンペ一覧から該当コンペがあるか確認

# I want to search 'TalkingData AdTracking Fraud Detection Challenge'
!kaggle competitions list -s talkingdata
ref                                     deadline             category   reward  teamCount  userHasEntered  
--------------------------------------  -------------------  --------  -------  ---------  --------------  
talkingdata-mobile-user-demographics    2016-09-05 23:59:00  Featured  $25,000       1689           False  
talkingdata-adtracking-fraud-detection  2018-05-07 23:59:00  Featured  $25,000       1581            True 

5.2 必要なデータのダウンロード

次に必要なデータのダウンロードを行います。

【注意】予めコンペへの参加 (コンペルールへの同意) は済ませてください

まずダウンロードする前のストレージ使用状況を確認します。

!df -h
Filesystem      Size  Used Avail Use% Mounted on
overlay          40G  4.9G   33G  14% /
tmpfs           6.4G     0  6.4G   0% /dev
tmpfs           6.4G     0  6.4G   0% /sys/fs/cgroup
/dev/sda1        46G  5.6G   40G  13% /etc/hosts
shm              64M     0   64M   0% /dev/shm
tmpfs           6.4G     0  6.4G   0% /sys/firmware

あと 33GB 使えます。
次にダウンロードを行います。

# download data for competition
## Before download data, you should accept competition rules at https://www.kaggle.com/c/<competition-name>/rules.
## Reference: https://github.com/Kaggle/kaggle-api
## When I ran it ended within 1 minute
!kaggle competitions download -c talkingdata-adtracking-fraud-detection

私が実行した時は 1分かからないくらいでダウンロードが終わりました。

train.csv.zip: Downloaded 1GB of 1GB
train_sample.csv.zip: Downloaded 1MB of 1MB
test.csv.zip: Downloaded 162MB of 162MB
sample_submission.csv.zip: Downloaded 40MB of 40MB
test_supplement.csv.zip: Downloaded 494MB of 494MB

ダウンロードした後のストレージ使用状況を確認します。

!df -h
Filesystem      Size  Used Avail Use% Mounted on
overlay          40G  6.8G   31G  19% /
tmpfs           6.4G     0  6.4G   0% /dev
tmpfs           6.4G     0  6.4G   0% /sys/fs/cgroup
/dev/sda1        46G  7.5G   38G  17% /etc/hosts
shm              64M     0   64M   0% /dev/shm
tmpfs           6.4G     0  6.4G   0% /sys/firmware

残り 31GB になりました。

またダウンロードしたファイルは /content/.kaggle/competitions/ の下に配置されます。

# file path
!ls /content/.kaggle/competitions/talkingdata-adtracking-fraud-detection/ -a
.   sample_submission.csv.zip  test_supplement.csv.zip  train_sample.csv.zip
..  test.csv.zip           train.csv.zip

6. コンペに提出

上記のファイルを使ってモデルを構築して予測を行ったとします(本稿では触れません)。

予測結果は以下のようにして提出することができます。
コマンドだけで完結できるので楽です。

# submit
!kaggle competitions submit -c <competition-name> -f <submit.csv> -m "My submission message"

さいごに

  • コンペむずかちいけどたのちいです
  • 一緒に参加してくれる方募集中です
    • twitter@fam_taro まで
105
107
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
105
107