# Google Colaboratory からSignateを使うメモ

By [Shogaku](https://paragraph.com/@shogaku) · 2023-01-21

---

Google Colaboratory から、Signate使ったことがなかったので備忘録として残す

元記事　→　

[https://hide.ac/articles/V573gMOwM](https://hide.ac/articles/V573gMOwM)

*   手順SIGNATE CLI
    
    [https://pypi.org/project/signate/](https://pypi.org/project/signate/)
    

そして、こちらがとてもためになった

*   Google ColabでSIGNATE APIを使う[https://qiita.com/insilicomab/items/d757339d97b44feaff01](https://qiita.com/insilicomab/items/d757339d97b44feaff01)
    

* * *

APIトークン作成
---------

[https://signate.jp/account\_settings](https://signate.jp/account_settings)

ここで作成。グーグルドライブへ保管

* * *

[Google ColabでSIGNATE APIを使う](https://pypi.org/project/signate/) で導入を丸コピー
-------------------------------------------------------------------------

    !pip install signate
    
    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 = 'signate.json'", fields="files(id)").execute()
    signate_api_key = results.get('files', [])
    
    filename = "/root/.signate/signate.json"
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    
    request = drive_service.files().get_media(fileId=signate_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 Colab上でSignate APIキーを使用するためのPythonコードです。

このコードは、Google Driveから名前が'signate.json'のファイルを検索し、それをダウンロードし、それを使用してSignate APIに接続するために必要な準備をします。

*   pip install signate：
    
    これは、Signate Pythonクライアントライブラリをインストールするためのコマンドです。
    
*   auth.authenticate\_user():
    
    Google Driveにアクセスするための認証を行う。
    
*   drive\_service = build('drive', 'v3') :
    
    Google Drive APIのサービスを構築する。
    
*   results = drive\_service.files().list(q="name = 'signate.json'", fields="files(id)").execute() :
    
    指定された名前のファイルを検索する。
    
*   request = drive\_service.files().get\_media(fileId=signate\_api\_key\[0\]\['id'\]) :
    
    検索したファイルを取得する。
    
*   fh = io.FileIO(filename, 'wb') :
    
    ダウンロードしたファイルを保存するためのFileIOオブジェクトを作成する。
    
*   downloader = MediaIoBaseDownload(fh, request) :
    
    ダウンロードを開始する。
    
*   os.chmod(filename, 600) :
    
    ダウンロードしたファイルに適切なアクセス権を設定する。
    

* * *

使える機能チェック
---------

    !signate --help
    

    Usage: signate [OPTIONS] COMMAND [ARGS]...
    
    Options:
      --help  Show this message and exit.
    
    Commands:
      download  Download the file of competition
      files     List file of competition
      list      List competition
      submit    Submit a result file to the competition
      token     Download the API Token
    

* * *

コマンドを確認していく

list
----

    !signate list
    

      competitionId  title                                                                             closing     prize             submitters
    ---------------  --------------------------------------------------------------------------------  ----------  --------------  ------------
                  1  【練習問題】銀行の顧客ターゲティング                                              -                                   6443
                 24  【練習問題】お弁当の需要予測                                                      -                                   7823
                 27  【練習問題】Jリーグの観客動員数予測                                               -                                   1863
                100  【練習問題】手書き文字認識                                                        -           Knowledge                283
                102  【練習問題】タイタニックの生存予測                                                -           Knowledge               1942
                103  【練習問題】音楽ラベリング                                                        -           Knowledge                115
                104  【練習問題】スパムメール分類                                                      -           Knowledge                174
                105  【練習問題】毒キノコの分類                                                        -           Knowledge                319
                106  【練習問題】アワビの年齢予測                                                      -           Knowledge                418
                107  【練習問題】国勢調査からの収入予測                                                -           Knowledge                658
                108  【練習問題】画像ラベリング（20種類）                                              -           Knowledge                289
                112  【練習問題】ワインの品種の予測                                                    -           Knowledge                370
                113  【練習問題】山火事の消失面積予測                                                  -           Knowledge                262
                114  【練習問題】レンタル自転車の利用者数予測                                          -           Knowledge                564
                115  【練習問題】アヤメの分類                                                          -           Knowledge                462
                116  【練習問題】活動センサーログからの動作予測                                        -           Knowledge                 69
                118  【練習問題】テニスの試合結果の予測                                                -           Knowledge                185
                121  【練習問題】自動車の走行距離予測                                                  -           Knowledge               1754
                122  【練習問題】自動車の評価                                                          -           Knowledge                363
                123  【練習問題】オゾンレベルの分類                                                    -           Knowledge                 85
                124  【練習問題】ボットの判別                                                          -           Knowledge                361
                125  【練習問題】ガラスの分類                                                          -           Knowledge                269
                126  【練習問題】林型の分類                                                            -           Knowledge                 73
                127  【練習問題】ゲーム選手のリーグ分類                                                -           Knowledge                 98
                128  【練習問題】ステンレス板の欠陥分類                                                -           Knowledge                133
                129  【練習問題】都市サイクルの燃料消費量予測                                          -           Knowledge                306
                130  【練習問題】天秤のバランス分類                                                    -           Knowledge                253
                132  【練習問題】ネット広告のクリック予測                                              -           Knowledge                161
                133  【練習問題】画像ラベリング（10種類）                                              -                                    405
                135  【練習問題】ネット画像の分類                                                      -                                     82
                262  国立国会図書館の画像データレイアウト認識                                          2100-12-31  -                        100
                263  産業技術総合研究所 衛星画像分析コンテスト                                         2100-12-31  -                         70
                264  マイナビ × SIGNATE Student Cup 2019: 賃貸物件の家賃予測                           2100-12-31  -                        516
                265  【練習問題】健診データによる肝疾患判定                                            -                                    668
                266  【練習問題】民泊サービスの宿泊価格予測                                            -                                    713
                267  海洋研究開発機構 熱帯低気圧（台風等）検出アルゴリズム作成                         2100-12-31  -                         32
                268  オプト レコメンドエンジン作成                                                     2100-12-31                            62
                269  アップル 引越し需要予測                                                           2100-12-31  -                        534
                270  Weather Challenge：雲画像予測                                                     2100-12-31  -                         14
                271  JR西日本 走行中の北陸新幹線車両台車部の着雪量予測                                 2100-12-31  -                         33
                288  Sansan 名刺の項目予測                                                             2100-12-31  -                         48
                294  【練習問題】債務不履行リスクの低減                                                -                                    337
                358  【練習問題】機械稼働音の異常検知                                                  -                                     98
                404  【練習問題】モノクロ顔画像の感情分類                                              -                                    138
                406  【練習問題】鋳造製品の欠陥検出                                                    -                                    279
                409  【練習問題】株価の推移予測                                                        -                                    245
                565  SIGNATE Student Cup 2021春：楽曲のジャンル推定チャレンジ！！                      2100-12-31  -                        172
                567  SIGNATE Student Cup 2021秋：オペレーション最適化に向けたシェアサイクルの利用予測  2100-12-31  -                        121
                595  医学論文の自動仕分けチャレンジ                                                    2100-12-31                            59
                657  SUBARU 画像認識チャレンジ                                                         2100-12-31                             9
                841  第１回 金融データ活用チャレンジ                                                   2023-03-05  総額¥1,000,000            66
                936  ブルーカーボン・ダイナミクスを可視化せよ！                                        2023-04-30  総額¥1,000,000            16
    

* * *

file
----

ID = 1 にするとき

    !signate files --competition-id=1 
    

      fileId  name               title              size  updated_at
    --------  -----------------  --------------  -------  -------------------
           1  train.csv          学習用データ    2345067  2016-05-31 20:19:48
           2  test.csv           評価用データ    1523536  2021-11-02 12:16:31
           3  submit_sample.csv  応募用サンプル   205890  2016-05-31 20:20:59
    

* * *

downoad
-------

ID = 1 にするとき

    !signate download --competition-id=1 
    

    submit_sample.csv
    
    test.csv
    
    train.csv
    
    
    Download completed.
    

* * *

データの中身を確認する
-----------

head()メソッドを使用して、最初の5行のデータを表示
----------------------------

    import pandas as pd
    
    submit_sample = pd.read_csv('submit_sample.csv')
    test = pd.read_csv('test.csv')
    train = pd.read_csv('train.csv')
    
    print(submit_sample.head())
    print(test.head())
    print(train.head())
    

       1  0.236
    0  2  0.128
    1  3  0.903
    2  4  0.782
    3  5  0.597
    4  6  0.555
       id  age            job  marital  education default  balance housing loan  \
    0   1   30     management   single   tertiary      no     1028      no   no   
    1   2   39  self-employed   single   tertiary      no      426      no   no   
    2   3   38     technician   single   tertiary      no     -572     yes  yes   
    3   4   34     technician   single  secondary      no     -476     yes   no   
    4   5   37   entrepreneur  married    primary      no       62      no   no   
    
        contact  day month  duration  campaign  pdays  previous poutcome  
    0  cellular    4   feb      1294         2     -1         0  unknown  
    1   unknown   18   jun      1029         1     -1         0  unknown  
    2   unknown    5   jun        26        24     -1         0  unknown  
    3   unknown   27   may        92         4     -1         0  unknown  
    4  cellular   31   jul       404         2     -1         0  unknown  
       id  age           job  marital  education default  balance housing loan  \
    0   1   39   blue-collar  married  secondary      no     1756     yes   no   
    1   2   51  entrepreneur  married    primary      no     1443      no   no   
    2   3   36    management   single   tertiary      no      436      no   no   
    3   4   63       retired  married  secondary      no      474      no   no   
    4   5   31    management   single   tertiary      no      354      no   no   
    
        contact  day month  duration  campaign  pdays  previous poutcome  y  
    0  cellular    3   apr       939         1     -1         0  unknown  1  
    1  cellular   18   feb       172        10     -1         0  unknown  1  
    2  cellular   13   apr       567         1    595         2  failure  1  
    3  cellular   25   jan       423         1     -1         0  unknown  1  
    4  cellular   30   apr       502         1      9         2  success  1  
    

* * *

shape属性を使用して、データの行数と列数を確認
-------------------------

    print(submit_sample.shape)
    print(test.shape)
    print(train.shape)
    

    (18082, 2)
    (18083, 17)
    (27128, 18)
    

* * *

info()メソッドやdescribe()メソッド
-------------------------

    print(submit_sample.info())
    print(test.describe())
    print(train.describe())
    

    <class 'pandas.core.frame.dataframe'="">
    RangeIndex: 18082 entries, 0 to 18081
    Data columns (total 2 columns):
     #   Column  Non-Null Count  Dtype  
    ---  ------  --------------  -----  
     0   1       18082 non-null  int64  
     1   0.236   18082 non-null  float64
    dtypes: float64(1), int64(1)
    memory usage: 282.7 KB
    None
                     id           age       balance           day      duration  \
    count  18083.000000  18083.000000  18083.000000  18083.000000  18083.000000   
    mean    9042.000000     40.914008   1371.980092     15.806725    254.340264   
    std     5220.256794     10.634331   3105.985293      8.299509    253.591981   
    min        1.000000     18.000000  -8019.000000      1.000000      0.000000   
    25%     4521.500000     33.000000     72.000000      8.000000    102.000000   
    50%     9042.000000     39.000000    447.000000     16.000000    178.000000   
    75%    13562.500000     48.000000   1427.000000     21.000000    314.000000   
    max    18083.000000     95.000000  98417.000000     31.000000   3881.000000   
    
               campaign         pdays      previous  
    count  18083.000000  18083.000000  18083.000000  
    mean       2.781950     39.702428      0.581209  
    std        3.054651     99.747634      1.965265  
    min        1.000000     -1.000000      0.000000  
    25%        1.000000     -1.000000      0.000000  
    50%        2.000000     -1.000000      0.000000  
    75%        3.000000     -1.000000      0.000000  
    max       50.000000    854.000000     58.000000  
                     id           age        balance           day      duration  \
    count  27128.000000  27128.000000   27128.000000  27128.000000  27128.000000   
    mean   13564.500000     40.951010    1355.800870     15.806215    260.711295   
    std     7831.323388     10.608542    3003.305272      8.337904    260.091727   
    min        1.000000     18.000000   -6847.000000      1.000000      0.000000   
    25%     6782.750000     33.000000      72.000000      8.000000    104.000000   
    50%    13564.500000     39.000000     449.000000     16.000000    182.000000   
    75%    20346.250000     48.000000    1428.000000     21.000000    323.000000   
    max    27128.000000     95.000000  102127.000000     31.000000   4918.000000   
    
               campaign         pdays      previous             y  
    count  27128.000000  27128.000000  27128.000000  27128.000000  
    mean       2.751769     40.528052      0.579733      0.117001  
    std        3.126594    100.382462      2.503653      0.321427  
    min        1.000000     -1.000000      0.000000      0.000000  
    25%        1.000000     -1.000000      0.000000      0.000000  
    50%        2.000000     -1.000000      0.000000      0.000000  
    75%        3.000000     -1.000000      0.000000      0.000000  
    max       63.000000    871.000000    275.000000      1.000000  
    </class>
    

* * *

データを提出する段階に来たら、また備忘録を残したいと思う

---

*Originally published on [Shogaku](https://paragraph.com/@shogaku/google-colaboratory-signate)*
