カレーちゃんブログ

Kaggleや競技プログラミングなどのこと

Kaggleのノートブックカーネルにscriptをimportする

これまで、Kaggleのカーネルから他のカーネルのscript(コード)をimportすることはできませんでした。
今回のアップデートで、ノートブックカーネルであれば、scriptをimportすることができるようになりました。

これまでは同じコードを繰り返し書いていましたが、共通の処理はscriptで書いておいて、カーネルに書くコードを減らすという使い方ができそうです。

使い方

使い方は、次のツイートで書いた通り。

公式からは次のように説明がありました。

  1. Create a script kernel with the code you’d like to import. For some ideas on how to organize this, check out this documentation on Python modules or this guide to writing code for R packages.
  2. In the settings panel on the right hand side, select “Utility Script On” from the Utility drop down. This will let you import this script to notebook kernels.
  3. Commit your script. When you import a script, you’re importing the most recent committed version. If you haven’t committed a version yet, you won’t see it in the list of scripts you can import.
  4. Open the notebook where you’d like to import the script.
  5. Add the script. Under “File”, click “Add utility script”. Search for the script you want and click to add it. You should see it listed under “usr/lib” in the panel on the right hand side.
  6. Import your script. In Python you can do this using import nameof_script. In R, you can do this using source(“path/to/script”). The path will be like ../usr/lib/[your_script_name_here]/[your_script_name_here.R]. You can use the TAB button as you type the path to automatically fill out the file path.
  7. Use the functions or objects you’ve imported!

実際に使ってみる

Kernelの実行終了時にLineに通知を送るコードをscriptにしてみました。
コピペで使える。Kaggleでの実験を効率化する小技まとめのLINEに通知を送るで紹介されているやつですね。

line_tokenが色々なところに散らばるのを防ぐためにも、scriptにしてimportして使うというのは良い気がします。

import requests

def send_line_notification(message):
    line_token = 'YOUR_LINE_TOKEN'  # 終わったら無効化する
    endpoint = 'https://notify-api.line.me/api/notify'
    message = "\n{}".format(message)
    payload = {'message': message}
    headers = {'Authorization': 'Bearer {}'.format(line_token)}
    requests.post(endpoint, data=payload, headers=headers)

scriptでは、上記ブログの通りにパーソナルアクセストークンをを発行して'YOUR_LINE_TOKEN'を発行されたトークンに置き換えます。
そして、他のカーネルからimportできるようにするために、settingsのUtility Scriptをonにしておきます。

次にノートブックのカーネルを開き、FileにあるAdd utility scriptから、先ほど作ったscriptを選択します。
また、通知はinternetアクセスが必要なため、Settingsにあるinternetをonにします。 あとは次のようにimportして、'send_line_notification()'すると、Lineに通知が行きます。

from line_notify import send_line_notification

send_line_notification('test_notify')

f:id:currypurin:20190502211453j:plain
とても簡単です。素晴らしい。

この情報を知った経緯など

次のツイートでできるようになったことを知りました。

Kaggleのカーネル実行終了時に通知できないのかなーとつぶやいていたら、higeponさんにインターネットアクセスをonにしないといけないと教えてもらいました。

No internet access enabledとされている、Kernelコンペでは、インターネットアクセスをonにしていると、Kernelからサブミットできないようです。