{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## tfrecファイルの作成＋datasetへの登録 概要\n- 前提\n  - /kaggle/working直下は20GBの制限があるため、ここには作成しない。(Save方法したいで永続化される\n  - /kaggle/tmp 等の自作したディレクトリは100GBまで作成できそうなので、そこに作成する。(この中のファイルはコードのセッションが終了すると削除される。)\n  - datasetへの登録はKaggle APIを使用\n  - トリミングの情報は拝借してきた  ","metadata":{}},{"cell_type":"markdown","source":"- 手順\n1. データセット一時保存用ディレクトリを作成\n   - /kaggle/tmp/happy-whale-and-dolphin-dataset\n\n2. データセット一時保存用ディレクトリに、以下のCSVファイルを作成\n   - train_label_box.csv  \n     訓練画像用CSV(train.csv)について、正解ラベルのエンコード、トリミング情報を付与したファイル\n   - test_label_box.csv  \n     評価画像について、トリミング情報を付与したファイル\n   - label_master.csv  \n     正解ラベル、エンコードした数値の対応マスタCSV  \n\n3. 訓練画像をtfrec化してデータセット一時保存用ディレクトリに作成\n   - tfrec内の1画像は以下の情報を保存\n     - image:画像の行列\n     - image_name:画像の名称　※学習には使わない\n     - target:正解ラベル(エンコード後)\n     - species:イルカ・クジラの種類(エンコード後) ※学習には使わない\n     - box:トリミングの枠\n   - ファイル名  \n     train-images-{SEQ3桁}.tfrec\n   - tfrecは10ファイル分作成(1ファイル約5104枚の画像)\n     \n4. テスト画像をtfrec化して、データセット一時保存用ディレクトリに作成\n   - ファイル名  \n     test-images.tfrec\n   - target,speciesは情報がいため-1固定で作成\n\n5. Kaggle APIを使用してデータセット一時保存用ディレクトリに作成したデータ一式のdatasetを作成\n   - Kaggle APIのドキュメント  \n     https://github.com/Kaggle/kaggle-api","metadata":{}},{"cell_type":"code","source":"from math import ceil\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\n\n%config Completer.use_jedi = False","metadata":{"execution":{"iopub.status.busy":"2022-03-27T01:25:46.371550Z","iopub.execute_input":"2022-03-27T01:25:46.371882Z","iopub.status.idle":"2022-03-27T01:25:51.295829Z","shell.execute_reply.started":"2022-03-27T01:25:46.371801Z","shell.execute_reply":"2022-03-27T01:25:51.295101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ライブラリのバージョンチェック\nprint(np.__version__)\nprint(pd.__version__)\nprint(tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T01:26:47.842216Z","iopub.execute_input":"2022-03-27T01:26:47.842490Z","iopub.status.idle":"2022-03-27T01:26:47.847739Z","shell.execute_reply.started":"2022-03-27T01:26:47.842463Z","shell.execute_reply":"2022-03-27T01:26:47.846997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 1. データセット一時保存用ディレクトリを作成\nimport os\nimport shutil\ndataset_path = '/kaggle/tmp/happy-whale-and-dolphin-dataset'\nif os.path.exists(dataset_path):\n    shutil.rmtree(dataset_path)\nos.makedirs('/kaggle/tmp/happy-whale-and-dolphin-dataset', exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T01:26:48.862317Z","iopub.execute_input":"2022-03-27T01:26:48.862792Z","iopub.status.idle":"2022-03-27T01:26:48.869858Z","shell.execute_reply.started":"2022-03-27T01:26:48.862756Z","shell.execute_reply":"2022-03-27T01:26:48.869093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# オリジナルデータセットの保存パスを定義\nINPUT_BASE = '../input/'\nINPUT_DATA_PATH = f'{INPUT_BASE}happy-whale-and-dolphin/'\nTRAIN_IMAGES_PATH = f'{INPUT_DATA_PATH}train_images/'\nTEST_IMAGES_PATH = f'{INPUT_DATA_PATH}test_images/'\n\n# トリミング用のboxが格納されたデータセットの保存パスを定義\nCROPPED_DATA_PATH = f'{INPUT_BASE}cropped-dataset/'\n\n# 出力用のデータセット\n#OUTPUT_DIR_PATH = '/kaggle/working/'\nOUTPUT_DIR_PATH = '/kaggle/tmp/happy-whale-and-dolphin-dataset/'\nOUTPUT_TRAIN_IMAGES_PATH = f'{OUTPUT_DIR_PATH}train_images/'\nOUTPUT_TEST_IMAGES_PATH = f'{OUTPUT_DIR_PATH}test_images/'\n\n# 出力用のファイル\n#COPY_SAMPLE_CSV = 'train_sample.csv'\nTRAIN_LABEL_CSV = 'train_label_box.csv'\nTEST_LABEL_CSV = 'test_label_box.csv'\nLABEL_MASTER_CSV = 'label_master.csv'\n\nTRAIN_IMAGES_TFREC = 'train-images-{}-{}.tfrec'\nTEST_IMAGES_TFREC = 'test-images-{}-{}.tfrec'\n\n# 作業に使用する画像数を定義\nIMAGE_COUNT = 10","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:15:14.932884Z","iopub.execute_input":"2022-03-27T02:15:14.933167Z","iopub.status.idle":"2022-03-27T02:15:14.939482Z","shell.execute_reply.started":"2022-03-27T02:15:14.933120Z","shell.execute_reply":"2022-03-27T02:15:14.938383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 2. train_label_box.csvの作成\n# 正解ラベルをエンコーディングしたデータが記載された訓練データCSVを出力\ndef write_label_encode_train_csv():\n    # 正解ラベルのエンコーディング(説明変数として利用するわけではないため、ラベルエンコーディングで実施)\n    df_train = pd.read_csv(f'{INPUT_DATA_PATH}train.csv')\n    le = LabelEncoder()\n\n    # individual_idのエンコード\n    encoded_individual_id = pd.Series(le.fit_transform(df_train['individual_id']))\n    df_train['encoded_individual_id'] = encoded_individual_id\n\n    # speciesのエンコード\n    encoded_species = pd.Series(le.fit_transform(df_train['species']))\n    df_train['encoded_species'] = encoded_species\n    \n    # トリミング用のbox情報をセットを読み込んで、訓練データCSVに追加\n    df_train_cropped_info = pd.read_csv(f'{CROPPED_DATA_PATH}train-cropped-dataset.csv')\n    df_train['box'] = df_train_cropped_info['box']\n    \n    # エンコードした正解ラベルが記載されたCSVファイルを出力\n    df_train.to_csv(f'{OUTPUT_DIR_PATH}{TRAIN_LABEL_CSV}')\n\nwrite_label_encode_train_csv()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T01:26:50.696475Z","iopub.execute_input":"2022-03-27T01:26:50.697382Z","iopub.status.idle":"2022-03-27T01:26:51.195495Z","shell.execute_reply.started":"2022-03-27T01:26:50.697331Z","shell.execute_reply":"2022-03-27T01:26:51.194723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 2. test_label_box.csv の作成\n# テストデータのトリミングしたbox情報を格納したcsvを出力\ndef write_test_box_csv():\n    # 提出用サンプルにテスト画像が登録されているため、これをベースとする。\n    df_test = pd.read_csv(f'{INPUT_DATA_PATH}sample_submission.csv')\n    # \"predictions\"項目を削除する。\n    df_test = df_test.drop('predictions', axis=1)\n\n    # トリミング用のbox情報をセットを読み込んで、訓練データCSVに追加\n    df_test_cropped_info = pd.read_csv(f'{CROPPED_DATA_PATH}test-cropped-dataset.csv')\n    df_test['box'] = df_test_cropped_info['box']\n    \n    print(df_test.head())\n    \n    # エンコードした正解ラベルが記載されたCSVファイルを出力\n    df_test.to_csv(f'{OUTPUT_DIR_PATH}{TEST_LABEL_CSV}')\n\nwrite_test_box_csv()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T01:26:51.421784Z","iopub.execute_input":"2022-03-27T01:26:51.422446Z","iopub.status.idle":"2022-03-27T01:26:51.650732Z","shell.execute_reply.started":"2022-03-27T01:26:51.422405Z","shell.execute_reply":"2022-03-27T01:26:51.649951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 2. label_master.csv の作成\n# (正解ラベルのマスタcsvを作成)\ndef create_label_master():\n    # 正解ラベルのエンコーディング(説明変数として利用するわけではないため、ラベルエンコーディングで実施)\n    df_train = pd.read_csv(f'{OUTPUT_DIR_PATH}{TRAIN_LABEL_CSV}')\n    df_train = df_train.groupby(['encoded_individual_id', 'individual_id'],as_index=False)\n    df_train = df_train.size()\n    \n    # \"size\"項目を削除する。\n    df_train = df_train.drop('size', axis=1)\n    df_train = df_train.rename(columns={'encoded_individual_id': 'index'})\n    df_train.to_csv(f'{OUTPUT_DIR_PATH}{LABEL_MASTER_CSV}', index=False)\n    \ncreate_label_master()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T01:26:52.182252Z","iopub.execute_input":"2022-03-27T01:26:52.182806Z","iopub.status.idle":"2022-03-27T01:26:52.340258Z","shell.execute_reply.started":"2022-03-27T01:26:52.182765Z","shell.execute_reply":"2022-03-27T01:26:52.339488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # https://www.kaggle.com/lextoumbourou/happywhale-tfrecords-with-bounding-boxes\n# def read_bbox(bbox):\n#     return np.array([int(i) for i in bbox.split()])\n\n# tfrecの作成関数類たち\ndef _bytes_feature(value):\n    \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n    if isinstance(value, type(tf.constant(0))):\n        # BytesList won't unpack a string from an EagerTensor.\n        value = value.numpy()\n    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n# def _float_feature(value):\n#   \"\"\"Returns a float_list from a float / double.\"\"\"\n#   return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\ndef _int64_feature(value):\n    \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\ndef _bb_feature(bb):\n    \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n    return tf.train.Feature(int64_list=tf.train.Int64List(value=bb))\n\n#def serialize_example(image,image_name,target,species,yolov5_bb,detic_bb):\n# 画像のシリアライズ(イメージ、正解ラベルを付与したデータセットを作成)\ndef serialize_image(image, image_name, target, species, box):\n    feature = {\n        'image': _bytes_feature(image),\n        'image_name': _bytes_feature(image_name),\n        'target': _int64_feature(target),\n        'species': _int64_feature(species),\n        'box': _bb_feature(box)\n        #'yolov5_box': _bb_feature(yolov5_bb),\n        #'detic_box': _bb_feature(detic_bb)\n    }\n    serialize_data = tf.train.Example(features=tf.train.Features(feature=feature))\n    return serialize_data.SerializeToString()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T01:26:53.167246Z","iopub.execute_input":"2022-03-27T01:26:53.167924Z","iopub.status.idle":"2022-03-27T01:26:53.176070Z","shell.execute_reply.started":"2022-03-27T01:26:53.167883Z","shell.execute_reply":"2022-03-27T01:26:53.175381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 訓練画像の総枚数\nIMAGE_TOTAL_COUNT = len(pd.read_csv(f'{OUTPUT_DIR_PATH}{TRAIN_LABEL_CSV}'))\n# 訓練画像の1TFRECに保存する画像数\nIMAGE_FOLD = ceil(IMAGE_TOTAL_COUNT / 10)\nprint(IMAGE_FOLD)\n\n# テスト画像の総枚数\nTEST_TOTAL_COUNT = len(pd.read_csv(f'{OUTPUT_DIR_PATH}{TEST_LABEL_CSV}'))\nTEST_IMAGE_FOLD = ceil(TEST_TOTAL_COUNT / 10)\nprint(TEST_IMAGE_FOLD)\nprint(TEST_TOTAL_COUNT)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:15:26.379321Z","iopub.execute_input":"2022-03-27T02:15:26.379690Z","iopub.status.idle":"2022-03-27T02:15:26.498170Z","shell.execute_reply.started":"2022-03-27T02:15:26.379655Z","shell.execute_reply":"2022-03-27T02:15:26.497230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 4. テスト画像をtfrec化して、データセット一時保存用ディレクトリに作成\nfrom math import ceil\n\n# 訓練画像をtfrecファイルに変換\ndef train_image_to_tfrec():\n    tfr_filename = f'{OUTPUT_DIR_PATH}{TRAIN_IMAGES_TFREC}'\n    train_df = pd.read_csv(f'{OUTPUT_DIR_PATH}{TRAIN_LABEL_CSV}')\n    \n    total_row_count = len(train_df)\n    print(total_row_count)\n\n    tfrec_index = 0\n    remaining_row_count = total_row_count\n\n    row_index = 0\n    while True:\n        # tfrecのindexを取得\n        tfrec_index = tfrec_index + 1\n        \n        if tfrec_index >= 3:\n            break\n\n        # tfrecの画像数を取得\n        if remaining_row_count >= IMAGE_FOLD:\n            tfrec_data_count = IMAGE_FOLD\n        else:\n            tfrec_data_count = remaining_row_count\n\n        # tfrec名称を取得\n        tfrec_filename = tfr_filename.format(str(tfrec_index).zfill(3), str(tfrec_data_count))\n\n        # 画像を作成\n        with tf.io.TFRecordWriter(tfrec_filename) as writer:\n            start = (tfrec_index - 1) * IMAGE_FOLD\n            end = start + tfrec_data_count\n\n            for row_index in range(start, end):\n                row = train_df.iloc[row_index]\n\n                # 画像ファイル名\n                image_id = row['image']\n                # 正解ラベル(エンコーディング済み)\n                target = row['encoded_individual_id']\n                # イルカ・クジラの分類(エンコーディング済み)\n                species = row['encoded_species']\n\n                # 画像の読み込み\n                image_path = f\"{TRAIN_IMAGES_PATH}{image_id}\"\n                image_encoded = tf.io.read_file(image_path)\n                image_name = str.encode(image_id)\n\n                # トリミング領域の取得\n                if type(row['box']) is float:\n                    box = [-1, -1, -1, -1]\n                else:\n                    #box = list(read_bbox(row['box']))\n                    box = [int(b) for b in row['box'].split()]\n\n                serialize_image_data = serialize_image(image_encoded, image_name, target, species, box)\n                writer.write(serialize_image_data)\n            \n            print(f'{tfrec_filename} 作成 ここまでの画像数：{row_index + 1}')\n\n        # 残りの画像件数を取得\n        remaining_row_count = remaining_row_count - IMAGE_FOLD\n        # 全ての画像を処理しきったらループを抜ける\n        if remaining_row_count <= 0:\n            break\n        \n    print(f'index:{str(tfrec_index)}')\n\ntrain_image_to_tfrec()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:03:15.239077Z","iopub.execute_input":"2022-03-27T02:03:15.239479Z","iopub.status.idle":"2022-03-27T02:05:25.716604Z","shell.execute_reply.started":"2022-03-27T02:03:15.239441Z","shell.execute_reply":"2022-03-27T02:05:25.715825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # 4. テスト画像をtfrec化して、データセット一時保存用ディレクトリに作成\n# from math import ceil\n\n# # 訓練画像をtfrecファイルに変換\n# def train_image_to_tfrec():\n#     tfr_filename = f'{OUTPUT_DIR_PATH}{TRAIN_IMAGES_TFREC}'\n#     train_df = pd.read_csv(f'{OUTPUT_DIR_PATH}{TRAIN_LABEL_CSV}')\n    \n#     total_row_count = len(train_df)\n#     print(total_row_count)\n#     tfrec_count = ceil(total_row_count / IMAGE_FOLD) \n    \n#     for i in range(1, tfrec_count + 1):\n#         tfrec_filename = tfr_filename.format(str(i).zfill(3))\n\n#         with tf.io.TFRecordWriter(tfrec_filename) as writer:\n#             for index in range(0, IMAGE_FOLD):\n#                 row_index = index + ((i - 1) * IMAGE_FOLD)\n#                 if row_index >= total_row_count:\n#                     break\n\n#                 row = train_df.iloc[row_index]\n\n#                 # 画像ファイル名\n#                 image_id = row['image']\n#                 # 正解ラベル(エンコーディング済み)\n#                 target = row['encoded_individual_id']\n#                 # イルカ・クジラの分類(エンコーディング済み)\n#                 species = row['encoded_species']\n\n#                 # 画像の読み込み\n#                 image_path = f\"{TRAIN_IMAGES_PATH}{image_id}\"\n#                 image_encoded = tf.io.read_file(image_path)\n#                 image_name = str.encode(image_id)\n\n#                 # トリミング領域の取得\n#                 if type(row['box']) is float:\n#                     box = [-1, -1, -1, -1]\n#                 else:\n#                     #box = list(read_bbox(row['box']))\n#                     box = [int(b) for b in row['box'].split()]\n\n#                 serialize_image_data = serialize_image(image_encoded, image_name, target, species, box)\n#                 writer.write(serialize_image_data)\n            \n#             print(f'{tfrec_filename} 作成 ここまでの画像数：{row_index}')\n\n#     print(f'画像数:{row_index}')\n\n# train_image_to_tfrec()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 4. テスト画像をtfrec化して、データセット一時保存用ディレクトリに作成\ndef test_image_to_tfrec():\n    tfr_filename = f'{OUTPUT_DIR_PATH}{TEST_IMAGES_TFREC}'\n    test_df = pd.read_csv(f'{OUTPUT_DIR_PATH}{TEST_LABEL_CSV}')\n\n    total_row_count = len(test_df)\n    print(total_row_count)\n\n    tfrec_index = 0\n    remaining_row_count = total_row_count\n    \n    row_index = 0\n    while True:\n        # tfrecのindexを取得\n        tfrec_index = tfrec_index + 1\n\n        if tfrec_index >= 3:\n            break\n        \n        # tfrecの画像数を取得\n        if remaining_row_count >= TEST_IMAGE_FOLD:\n            tfrec_data_count = TEST_IMAGE_FOLD\n        else:\n            tfrec_data_count = remaining_row_count\n\n        # tfrec名称を取得\n        tfrec_filename = tfr_filename.format(str(tfrec_index).zfill(3), str(tfrec_data_count))\n\n        # 画像を作成\n        with tf.io.TFRecordWriter(tfrec_filename) as writer:\n            start = (tfrec_index - 1) * TEST_IMAGE_FOLD\n            end = start + tfrec_data_count\n\n            for row_index in range(start, end):\n                row = test_df.iloc[row_index]\n\n                # 画像ファイル名\n                image_id = row['image']\n                # 正解ラベル(正解が分からないので固定値)\n                target = -1\n                # イルカ・クジラの分類(正解が分からないので固定値)\n                species = -1\n\n                # 画像の読み込み\n                image_path = f\"{TEST_IMAGES_PATH}{image_id}\"\n                image_encoded = tf.io.read_file(image_path)\n                image_name = str.encode(image_id)\n\n                if type(row['box']) is float:\n                    box = [-1, -1, -1, -1]\n                else:\n                    box = [int(b) for b in row['box'].split()]\n\n                serialize_image_data = serialize_image(image_encoded, image_name, target, species, box)\n                writer.write(serialize_image_data)\n            \n            print(f'{tfrec_filename} 作成 ここまでの画像数：{row_index + 1}')\n\n        # 残りの画像件数を取得\n        remaining_row_count = remaining_row_count - TEST_IMAGE_FOLD\n        # 全ての画像を処理しきったらループを抜ける\n        if remaining_row_count <= 0:\n            break\n        \n    print(f'index:{str(tfrec_index)}')\n\ntest_image_to_tfrec()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:20:21.423676Z","iopub.execute_input":"2022-03-27T02:20:21.423949Z","iopub.status.idle":"2022-03-27T02:21:42.972640Z","shell.execute_reply.started":"2022-03-27T02:20:21.423917Z","shell.execute_reply":"2022-03-27T02:21:42.971854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # 4. テスト画像をtfrec化して、データセット一時保存用ディレクトリに作成\n# def test_image_to_tfrec():\n#     tfr_filename = f'{OUTPUT_DIR_PATH}{TEST_IMAGES_TFREC}'\n#     test_df = pd.read_csv(f'{OUTPUT_DIR_PATH}{TEST_LABEL_CSV}')\n\n#     test_total_count = len(test_df)\n#     #tfrec_count = ceil(len(test_df) / IMAGE_FOLD)\n#     #print(tfrec_count)\n    \n#     with tf.io.TFRecordWriter(tfr_filename) as writer:\n#         for index, row in test_df.iterrows():\n#             image_id = row['image']\n#             # 正解ラベル(正解が分からないので固定値)\n#             target = -1\n#             # イルカ・クジラの分類(正解が分からないので固定値)\n#             species = -1\n            \n#             # 画像の読み込み\n#             image_path = f\"{TEST_IMAGES_PATH}{image_id}\"\n#             image_encoded = tf.io.read_file(image_path)\n#             image_name = str.encode(image_id)\n            \n#             if type(row['box']) is float:\n#                 box = [-1, -1, -1, -1]\n#             else:\n#                 #box = list(read_bbox(row['box']))\n#                 box = [int(b) for b in row['box'].split()]\n\n#             serialize_image_data = serialize_image(image_encoded, image_name, target, species, box)\n#             writer.write(serialize_image_data)\n            \n#             if index % 2000 == 0:\n#                 print(f'テスト画像:{index}枚 作成済')\n\n#     print(f'テスト画像tfrec作成済み')\n\n# test_image_to_tfrec()","metadata":{"execution":{"iopub.status.busy":"2022-03-22T16:30:22.005002Z","iopub.execute_input":"2022-03-22T16:30:22.005428Z","iopub.status.idle":"2022-03-22T16:37:40.517519Z","shell.execute_reply.started":"2022-03-22T16:30:22.005393Z","shell.execute_reply":"2022-03-22T16:37:40.51674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 5. Kaggle APIを使用してデータセット一時保存用ディレクトリに作成したデータ一式のdatasetを作成\n## kaggle.jsonを作成する。これがルートディレクトリにないとKaggle APIが使用できない。\n## このjsonはユーザアカウント画面のCreat New API Tokenから取得できる。\n## ただし、直接コードにアップロードする方法が分からなかったので、内容をLunuxコマンドで直接書き込んだ。(usernameやkeyは自分のkaggle.jsonのものに読み替えて下さい)\n!echo '{\"username\":\"npc0302\",\"key\":\"0de12965922b9485b11174c575648272\"}' > /root/.kaggle/kaggle.json\n## 600にするとkaggle.jsonを他ユーザに公開しない。\n!chmod 600 /root/.kaggle/kaggle.json","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:22:16.567695Z","iopub.execute_input":"2022-03-27T02:22:16.568327Z","iopub.status.idle":"2022-03-27T02:22:17.962963Z","shell.execute_reply.started":"2022-03-27T02:22:16.568280Z","shell.execute_reply":"2022-03-27T02:22:17.961932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 5. Kaggle APIを使用してデータセット一時保存用ディレクトリに作成したデータ一式のdatasetを作成\n## LinuxコマンドでKaggle APIをたたいてdatasetに登録するAPIを実行(データセットはここではnpx0302ユーザ配下のtest01　としている。)\n## 以下はdatasetを作成するために必要なmetadataのjsonファイルを作成するコマンド。\n## 詳細は以下を参照\n##   https://github.com/Kaggle/kaggle-api#datasets\n!kaggle datasets init -p /kaggle/tmp/happy-whale-and-dolphin-dataset\n!cat /kaggle/tmp/happy-whale-and-dolphin-dataset/dataset-metadata.json | jq '.title|=\"happy-whale-and-dolphin-tfrec\"' > /kaggle/tmp/happy-whale-and-dolphin-dataset/dataset-metadata-1.json\n!cat /kaggle/tmp/happy-whale-and-dolphin-dataset/dataset-metadata-1.json | jq '.id|=\"npc0302/happy-whale-and-dolphin-tfrec\"' > /kaggle/tmp/happy-whale-and-dolphin-dataset/dataset-metadata-2.json\n!mv -f /kaggle/tmp/happy-whale-and-dolphin-dataset/dataset-metadata-2.json /kaggle/tmp/happy-whale-and-dolphin-dataset/dataset-metadata.json\n!cat /kaggle/tmp/happy-whale-and-dolphin-dataset/dataset-metadata.json\n!rm /kaggle/tmp/happy-whale-and-dolphin-dataset/dataset-metadata-1.json\n\n## 一時作業フォルダ/kaggle/tmp/happy-whale-and-dolphin-datasetに存在するファイル一式をdatasetにアップロードする。\n## (--dir-mode zipは、この中にあるサブディレクトリをzip化してアップロードするコマンドだが、重くて途中で落ちたのでやめた。全ファイルを直下に配置する形式とした)\n## (--dir-mode zipがない場合、内部のサブディレクトリは無視されるっぽい)\n#!kaggle datasets create -p /kaggle/tmp/happy-whale-and-dolphin-dataset --dir-mode zip\n!kaggle datasets create -p /kaggle/tmp/happy-whale-and-dolphin-dataset","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:22:19.873698Z","iopub.execute_input":"2022-03-27T02:22:19.874020Z","iopub.status.idle":"2022-03-27T02:22:25.706240Z","shell.execute_reply.started":"2022-03-27T02:22:19.873979Z","shell.execute_reply":"2022-03-27T02:22:25.705321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}