{"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":"code","source":"import os, json, random, cv2\nimport numpy as np, pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf, re, math\nfrom tqdm import tqdm\n\nfrom PIL import Image","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-02-20T00:44:15.207048Z","iopub.execute_input":"2022-02-20T00:44:15.207360Z","iopub.status.idle":"2022-02-20T00:44:21.505971Z","shell.execute_reply.started":"2022-02-20T00:44:15.207323Z","shell.execute_reply":"2022-02-20T00:44:21.504586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Intro\n\nThis notebook extends the work done by [ks2019](https://www.kaggle.com/ks2019) in the notebook [HappyWhale TFRecords](https://www.kaggle.com/ks2019/happywhale-tfrecords), to include:\n\n* the [Yolov5 bounding box predictions](https://www.kaggle.com/awsaf49/happywhale-cropped-dataset-yolov5) created by [awsaf49](https://www.kaggle.com/awsaf49)\n* the [Detic bounding box predictions](https://www.kaggle.com/c/happy-whale-and-dolphin/discussion/305503) created by [phalanx](https://www.kaggle.com/phalanx).","metadata":{}},{"cell_type":"code","source":"train_df = pd.read_csv('../input/happywhale-splits/skf_species_10folds.csv')\ntest_df = pd.read_csv('../input/happy-whale-and-dolphin/sample_submission.csv')\ntest_df['split'] = test_df.index%10","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:21.507615Z","iopub.execute_input":"2022-02-20T00:44:21.507985Z","iopub.status.idle":"2022-02-20T00:44:21.666368Z","shell.execute_reply.started":"2022-02-20T00:44:21.507947Z","shell.execute_reply":"2022-02-20T00:44:21.665609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Yolov5\n\nLoad the [Yolov5 bounding box predictions](https://www.kaggle.com/awsaf49/happywhale-cropped-dataset-yolov5) created by [awsaf49](https://www.kaggle.com/awsaf49).","metadata":{}},{"cell_type":"code","source":"yolo5_train_df = pd.read_csv('../input/happywhale-cropped-dataset-yolov5/train.csv')\nyolo5_test_df = pd.read_csv('../input/happywhale-cropped-dataset-yolov5/test.csv')","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:30.084941Z","iopub.execute_input":"2022-02-20T00:44:30.085243Z","iopub.status.idle":"2022-02-20T00:44:30.962173Z","shell.execute_reply.started":"2022-02-20T00:44:30.085212Z","shell.execute_reply":"2022-02-20T00:44:30.961200Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"yolo5_train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:30.966008Z","iopub.execute_input":"2022-02-20T00:44:30.966274Z","iopub.status.idle":"2022-02-20T00:44:30.992502Z","shell.execute_reply.started":"2022-02-20T00:44:30.966243Z","shell.execute_reply":"2022-02-20T00:44:30.991523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['yolo5_bbox'] = yolo5_train_df.bbox.str[2:-2].str.replace(',', '')\ntest_df['yolo5_bbox'] = yolo5_test_df.bbox.str[2:-2].str.replace(',', '')","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:30.994164Z","iopub.execute_input":"2022-02-20T00:44:30.994490Z","iopub.status.idle":"2022-02-20T00:44:31.115366Z","shell.execute_reply.started":"2022-02-20T00:44:30.994448Z","shell.execute_reply":"2022-02-20T00:44:31.114353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:32.856252Z","iopub.execute_input":"2022-02-20T00:44:32.856540Z","iopub.status.idle":"2022-02-20T00:44:32.869140Z","shell.execute_reply.started":"2022-02-20T00:44:32.856506Z","shell.execute_reply":"2022-02-20T00:44:32.867978Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_bbox(bbox):\n    return np.array([int(i) for i in bbox.split()])","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:33.204924Z","iopub.execute_input":"2022-02-20T00:44:33.205199Z","iopub.status.idle":"2022-02-20T00:44:33.210015Z","shell.execute_reply.started":"2022-02-20T00:44:33.205171Z","shell.execute_reply":"2022-02-20T00:44:33.209113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def show_crop(row, crops=None, dataset='train'):\n    crops = crops or {'yolov5', 'detic'}\n    f, axarr = plt.subplots(1, len(crops) + 1, figsize=(18, 6))\n    img = Image.open(f'../input/happy-whale-and-dolphin/{dataset}_images/{row.image}')\n    \n    arr_num = 0\n    axarr[arr_num].imshow(img)\n\n    if 'detic' in crops:\n        detic_crop = img.crop(read_bbox(row.detic_bbox))\n        arr_num += 1\n        axarr[arr_num].set_title('Detic')\n        axarr[arr_num].imshow(detic_crop)\n\n    if 'yolov5' in crops:\n        yolo5_crop = img.crop(read_bbox(row.yolo5_bbox))\n        arr_num += 1\n        axarr[arr_num].set_title('Yolov5')\n        axarr[arr_num].imshow(yolo5_crop)\n\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:33.893924Z","iopub.execute_input":"2022-02-20T00:44:33.894204Z","iopub.status.idle":"2022-02-20T00:44:33.907348Z","shell.execute_reply.started":"2022-02-20T00:44:33.894175Z","shell.execute_reply":"2022-02-20T00:44:33.906289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"row = train_df.iloc[1610]\nrow","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:34.626650Z","iopub.execute_input":"2022-02-20T00:44:34.627245Z","iopub.status.idle":"2022-02-20T00:44:34.636313Z","shell.execute_reply.started":"2022-02-20T00:44:34.627198Z","shell.execute_reply":"2022-02-20T00:44:34.635217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_crop(row, {'yolov5'})","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:34.781849Z","iopub.execute_input":"2022-02-20T00:44:34.782525Z","iopub.status.idle":"2022-02-20T00:44:36.689617Z","shell.execute_reply.started":"2022-02-20T00:44:34.782485Z","shell.execute_reply":"2022-02-20T00:44:36.688850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Detic\n\nLoad the [Detic bounding box predictions] created by [phalanx](https://www.kaggle.com/phalanx).","metadata":{}},{"cell_type":"code","source":"detic_train_df = pd.read_csv('../input/whale2-cropped-dataset/train2.csv')\ndetic_test_df = pd.read_csv('../input/whale2-cropped-dataset/test2.csv')","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:36.691288Z","iopub.execute_input":"2022-02-20T00:44:36.691783Z","iopub.status.idle":"2022-02-20T00:44:36.913215Z","shell.execute_reply.started":"2022-02-20T00:44:36.691719Z","shell.execute_reply":"2022-02-20T00:44:36.912121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"detic_train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:36.917123Z","iopub.execute_input":"2022-02-20T00:44:36.917899Z","iopub.status.idle":"2022-02-20T00:44:36.928790Z","shell.execute_reply.started":"2022-02-20T00:44:36.917791Z","shell.execute_reply":"2022-02-20T00:44:36.928001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"detic_train_df.loc[detic_train_df.box.isna(), 'box'] = ''\ndetic_test_df.loc[detic_test_df.box.isna(), 'box'] = ''","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:36.931106Z","iopub.execute_input":"2022-02-20T00:44:36.931471Z","iopub.status.idle":"2022-02-20T00:44:36.954053Z","shell.execute_reply.started":"2022-02-20T00:44:36.931433Z","shell.execute_reply":"2022-02-20T00:44:36.953091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['detic_bbox'] = detic_train_df.box\ntest_df['detic_bbox'] = detic_test_df.box","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:36.957579Z","iopub.execute_input":"2022-02-20T00:44:36.957885Z","iopub.status.idle":"2022-02-20T00:44:36.964611Z","shell.execute_reply.started":"2022-02-20T00:44:36.957849Z","shell.execute_reply":"2022-02-20T00:44:36.963686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"row = train_df.iloc[1610]\nrow","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:36.965953Z","iopub.execute_input":"2022-02-20T00:44:36.966622Z","iopub.status.idle":"2022-02-20T00:44:36.982160Z","shell.execute_reply.started":"2022-02-20T00:44:36.966573Z","shell.execute_reply":"2022-02-20T00:44:36.981146Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_crop(row, {'detic'})","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:36.983308Z","iopub.execute_input":"2022-02-20T00:44:36.983611Z","iopub.status.idle":"2022-02-20T00:44:38.578013Z","shell.execute_reply.started":"2022-02-20T00:44:36.983580Z","shell.execute_reply":"2022-02-20T00:44:38.576850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Any row missing bounding boxes, will use values -1, -1, -1, -1 as null value.","metadata":{}},{"cell_type":"code","source":"train_df.loc[train_df.yolo5_bbox == '', 'yolo5_bbox'] = '-1 -1 -1 -1'\ntrain_df.loc[train_df.detic_bbox == '', 'detic_bbox'] = '-1 -1 -1 -1'\n\ntest_df.loc[test_df.yolo5_bbox == '', 'yolo5_bbox'] = '-1 -1 -1 -1'\ntest_df.loc[test_df.detic_bbox == '', 'detic_bbox'] = '-1 -1 -1 -1'","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:38.579326Z","iopub.execute_input":"2022-02-20T00:44:38.579561Z","iopub.status.idle":"2022-02-20T00:44:38.621100Z","shell.execute_reply.started":"2022-02-20T00:44:38.579533Z","shell.execute_reply":"2022-02-20T00:44:38.620108Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Setup Dataset","metadata":{}},{"cell_type":"code","source":"%%time\n\n### Create Kaggle Dataset if not exists \nDATASET_NAME = f'happywhale-tfrecords-bb'\n\n!rm -rf /tmp/{DATASET_NAME}\n\nos.makedirs(f'/tmp/{DATASET_NAME}', exist_ok=True)\n\nwith open('../input/kaggleapi/kaggle.json') as f:\n    kaggle_creds = json.load(f)\n    \nos.environ['KAGGLE_USERNAME'] = kaggle_creds['username']\nos.environ['KAGGLE_KEY'] = kaggle_creds['key']\n\n!kaggle datasets init -p /tmp/{DATASET_NAME}\n\nwith open(f'/tmp/{DATASET_NAME}/dataset-metadata.json') as f:\n    dataset_meta = json.load(f)\n\ndataset_meta['id'] = f'lextoumbourou/{DATASET_NAME}'\ndataset_meta['title'] = DATASET_NAME\nwith open(f'/tmp/{DATASET_NAME}/dataset-metadata.json', \"w\") as outfile:\n    json.dump(dataset_meta, outfile)\nprint(dataset_meta)\n\n!cp /tmp/{DATASET_NAME}/dataset-metadata.json /tmp/{DATASET_NAME}/meta.json\n!ls /tmp/{DATASET_NAME}\n\n#!kaggle datasets create -u -p /tmp/{DATASET_NAME} ","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:44:53.345449Z","iopub.execute_input":"2022-02-20T00:44:53.346004Z","iopub.status.idle":"2022-02-20T00:44:56.945651Z","shell.execute_reply.started":"2022-02-20T00:44:53.345964Z","shell.execute_reply":"2022-02-20T00:44:56.944359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create TFRecords","metadata":{}},{"cell_type":"code","source":"def get_fold(fold):\n    val_df = train_df[train_df.fold==fold].reset_index(drop=True)\n    val_df['order'] = val_df.index\n    val_df['order'] = val_df.groupby('individual_id').order.rank()\n    val_total_counts = val_df.individual_id.value_counts().to_dict()\n    val_df['total_counts'] = val_df.individual_id.map(val_total_counts)\n    val_df['order'] = val_df['order']/val_df['total_counts']\n    val_df = val_df.sort_values('order',ascending=False).reset_index(drop=True)\n    val_df = val_df[['image','species','individual_id','yolo5_bbox', 'detic_bbox']]\n    return val_df","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:45:11.098541Z","iopub.execute_input":"2022-02-20T00:45:11.099025Z","iopub.status.idle":"2022-02-20T00:45:11.107620Z","shell.execute_reply.started":"2022-02-20T00:45:11.098985Z","shell.execute_reply":"2022-02-20T00:45:11.106251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def _bytes_feature(value):\n  \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n  if isinstance(value, type(tf.constant(0))):\n    value = value.numpy() # BytesList won't unpack a string from an EagerTensor.\n  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef _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\ndef serialize_example(image,image_name,target,species,yolov5_bb,detic_bb):\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        'yolov5_box': _bb_feature(yolov5_bb),\n        'detic_box': _bb_feature(detic_bb)\n    }\n    example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n    return example_proto.SerializeToString()","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:45:11.736058Z","iopub.execute_input":"2022-02-20T00:45:11.736533Z","iopub.status.idle":"2022-02-20T00:45:11.748020Z","shell.execute_reply.started":"2022-02-20T00:45:11.736501Z","shell.execute_reply":"2022-02-20T00:45:11.746937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"def create_tf_records(fold  = 0, progress=False):\n    df = get_fold(fold)\n    tfr_filename = f'/tmp/{DATASET_NAME}/happywhale-2022-train-{fold}-{df.shape[0]}.tfrec'\n    with tf.io.TFRecordWriter(tfr_filename) as writer:\n        it = df.iterrows()\n        if progress:\n            it = tqdm(it, total=len(df))\n        for i,row in it:\n            image_id = row.image\n            target = row.individual_id\n            species = row.species\n            image_path = f\"../input/happy-whale-and-dolphin/train_images/{image_id}\"\n            image_encoded = tf.io.read_file(image_path)\n            image_name = str.encode(image_id)\n            yolov5_bb = list(read_bbox(row.yolo5_bbox))\n            detic_bb = list(read_bbox(row.detic_bbox))\n            example = serialize_example(image_encoded,image_name,target,species,yolov5_bb,detic_bb)\n            writer.write(example)","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:45:13.418460Z","iopub.execute_input":"2022-02-20T00:45:13.418787Z","iopub.status.idle":"2022-02-20T00:45:13.427553Z","shell.execute_reply.started":"2022-02-20T00:45:13.418732Z","shell.execute_reply":"2022-02-20T00:45:13.426864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create_tf_records(0, progress=True)","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:45:23.435216Z","iopub.execute_input":"2022-02-20T00:45:23.435654Z","iopub.status.idle":"2022-02-20T00:46:38.483833Z","shell.execute_reply.started":"2022-02-20T00:45:23.435621Z","shell.execute_reply":"2022-02-20T00:46:38.482779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"import joblib\n_ = joblib.Parallel(n_jobs=8)(\n        joblib.delayed(create_tf_records)(fold) for fold in tqdm(range(10), total=10)\n    )","metadata":{"execution":{"iopub.status.busy":"2022-02-19T06:42:28.969687Z","iopub.execute_input":"2022-02-19T06:42:28.970979Z","iopub.status.idle":"2022-02-19T06:49:57.493302Z","shell.execute_reply.started":"2022-02-19T06:42:28.970927Z","shell.execute_reply":"2022-02-19T06:49:57.492067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_test_tf_records(fold  = 0, progress=False):\n    df = test_df[test_df.split==fold]\n    tfr_filename = f'/tmp/{DATASET_NAME}/happywhale-2022-test-{fold}-{df.shape[0]}.tfrec'\n    with tf.io.TFRecordWriter(tfr_filename) as writer:\n        it = df.iterrows()\n        if progress:\n            it = tqdm(it, total=len(df))\n        for i,row in it:\n            image_id = row.image\n            target = -1\n            species = -1\n            image_path = f\"../input/happy-whale-and-dolphin/test_images/{image_id}\"\n            image_encoded = tf.io.read_file(image_path)\n            image_name = str.encode(image_id)\n            yolov5_bb = list(read_bbox(row.yolo5_bbox))\n            detic_bb = list(read_bbox(row.detic_bbox))\n            example = serialize_example(image_encoded,image_name,target,species,yolov5_bb,detic_bb)\n            writer.write(example)","metadata":{"execution":{"iopub.status.busy":"2022-02-19T06:53:59.423008Z","iopub.execute_input":"2022-02-19T06:53:59.423613Z","iopub.status.idle":"2022-02-19T06:53:59.43291Z","shell.execute_reply.started":"2022-02-19T06:53:59.42357Z","shell.execute_reply":"2022-02-19T06:53:59.431946Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import joblib\n_ = joblib.Parallel(n_jobs=8)(\n        joblib.delayed(create_test_tf_records)(fold) for fold in tqdm(range(10))\n    )","metadata":{"execution":{"iopub.status.busy":"2022-02-19T06:54:01.78001Z","iopub.execute_input":"2022-02-19T06:54:01.780469Z","iopub.status.idle":"2022-02-19T06:56:44.046774Z","shell.execute_reply.started":"2022-02-19T06:54:01.780417Z","shell.execute_reply":"2022-02-19T06:56:44.045356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from datetime import datetime\nversion_name = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\nprint(version_name)","metadata":{"execution":{"iopub.status.busy":"2022-02-19T06:57:36.363088Z","iopub.execute_input":"2022-02-19T06:57:36.363443Z","iopub.status.idle":"2022-02-19T06:57:36.370473Z","shell.execute_reply.started":"2022-02-19T06:57:36.363408Z","shell.execute_reply":"2022-02-19T06:57:36.36972Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /tmp/{DATASET_NAME}","metadata":{"execution":{"iopub.status.busy":"2022-02-19T06:57:36.759935Z","iopub.execute_input":"2022-02-19T06:57:36.760263Z","iopub.status.idle":"2022-02-19T06:57:37.646121Z","shell.execute_reply.started":"2022-02-19T06:57:36.76023Z","shell.execute_reply":"2022-02-19T06:57:37.644707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Verify TFRecords","metadata":{}},{"cell_type":"markdown","source":"In this example I load some images from TFRecords and plot with the 2 bounding boxes.","metadata":{}},{"cell_type":"code","source":"from functools import partial","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:51:20.530106Z","iopub.execute_input":"2022-02-20T00:51:20.532050Z","iopub.status.idle":"2022-02-20T00:51:20.538920Z","shell.execute_reply.started":"2022-02-20T00:51:20.531986Z","shell.execute_reply":"2022-02-20T00:51:20.537720Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def decode_image(image_data, bb):\n    if bb is not None and bb[0] != -1:\n        left, top, right, bottom = bb[0], bb[1], bb[2], bb[3]\n        bbs = tf.convert_to_tensor([top, left, bottom - top, right - left])\n        image = tf.io.decode_and_crop_jpeg(image_data, bbs, channels=3)\n    else:\n        image = tf.image.decode_jpeg(image_data, channels = 3)\n\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.image.resize(image,IMAGE_SIZE_)\n    return image\n\ndef read_labeled_tfrecord(example, crop_method):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"image_name\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        'target': tf.io.FixedLenFeature([], tf.int64),\n        'species': tf.io.FixedLenFeature([], tf.int64),\n        'yolov5_box': tf.io.FixedLenFeature([4], tf.int64),\n        'detic_box': tf.io.FixedLenFeature([4], tf.int64),\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    \n    bb = None\n    if crop_method == 'detic':\n        bb = tf.cast(example['detic_box'], tf.int32)\n    elif crop_method == 'yolov5':\n        bb = tf.cast(example['yolov5_box'], tf.int32)\n\n    image = decode_image(example['image'], bb)\n    label = example['target']\n    return image, label, example['species']\n\ndef load_dataset(filenames, crop_method, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(partial(read_labeled_tfrecord, crop_method=crop_method))\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset(crop_method):\n    dataset = load_dataset(TRAINING_FILENAMES, crop_method, labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:55:23.477439Z","iopub.execute_input":"2022-02-20T00:55:23.477724Z","iopub.status.idle":"2022-02-20T00:55:23.496543Z","shell.execute_reply.started":"2022-02-20T00:55:23.477692Z","shell.execute_reply":"2022-02-20T00:55:23.495222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# numpy and matplotlib defaults\nnp.set_printoptions(threshold=15, linewidth=80)\nCLASSES = [0,1]\n\nfrom matplotlib import patches\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels, species = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    species_labels = species.numpy()\n    #if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n    #    numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images, numpy_labels, species_labels\n\ndef display_single_sample(image, label, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n\n    plt.imshow(image)\n\n    title = str(label)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n    \ndef display_batch_of_images(databatch):\n    \"\"\"\n    Display single batch Of images \n    \"\"\"\n    # data\n    images, labels, species = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n    # auto-squaring: this will drop data that does not fit into square or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)//rows\n        \n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))\n    \n    # display\n    for i, (image, label) in enumerate(zip(\n        images[:rows*cols],\n        labels[:rows*cols]\n    )):\n        correct = True\n        dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n        subplot = display_single_sample(image, label, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    #layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:54:29.315436Z","iopub.execute_input":"2022-02-20T00:54:29.316206Z","iopub.status.idle":"2022-02-20T00:54:29.335803Z","shell.execute_reply.started":"2022-02-20T00:54:29.316088Z","shell.execute_reply":"2022-02-20T00:54:29.334748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = 256\nBATCH_SIZE = 32","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:54:29.814573Z","iopub.execute_input":"2022-02-20T00:54:29.814903Z","iopub.status.idle":"2022-02-20T00:54:29.820492Z","shell.execute_reply.started":"2022-02-20T00:54:29.814870Z","shell.execute_reply":"2022-02-20T00:54:29.819347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE_ = [IMAGE_SIZE,IMAGE_SIZE]\nAUTO = tf.data.experimental.AUTOTUNE\nTRAINING_FILENAMES = tf.io.gfile.glob(f'/tmp/{DATASET_NAME}/happywhale-2022-train*.tfrec')\nprint(len(TRAINING_FILENAMES))\ndataset = load_dataset(TRAINING_FILENAMES, crop_method='detic', labeled=True)\ndataset = dataset.repeat()\ndataset = dataset.shuffle(2048)\ndataset = dataset.batch(BATCH_SIZE)\ndataset = dataset.prefetch(AUTO) #This dataset can directly be passed to keras.fit method\nprint(count_data_items(TRAINING_FILENAMES))\n\n# Displaying single batch of TFRecord\ntrain_batch = iter(dataset)\ndisplay_batch_of_images(next(train_batch))","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:54:30.117219Z","iopub.execute_input":"2022-02-20T00:54:30.117665Z","iopub.status.idle":"2022-02-20T00:55:04.000591Z","shell.execute_reply.started":"2022-02-20T00:54:30.117633Z","shell.execute_reply":"2022-02-20T00:55:03.998923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE_ = [IMAGE_SIZE,IMAGE_SIZE]\nAUTO = tf.data.experimental.AUTOTUNE\nTRAINING_FILENAMES = tf.io.gfile.glob(f'/tmp/{DATASET_NAME}/happywhale-2022-train*.tfrec')\nprint(len(TRAINING_FILENAMES))\ndataset = load_dataset(TRAINING_FILENAMES, crop_method='yolov5', labeled=True)\ndataset = dataset.repeat()\ndataset = dataset.shuffle(2048)\ndataset = dataset.batch(BATCH_SIZE)\ndataset = dataset.prefetch(AUTO) #This dataset can directly be passed to keras.fit method\nprint(count_data_items(TRAINING_FILENAMES))\n\n# Displaying single batch of TFRecord\ntrain_batch = iter(dataset)\ndisplay_batch_of_images(next(train_batch))","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:55:26.020105Z","iopub.execute_input":"2022-02-20T00:55:26.020646Z","iopub.status.idle":"2022-02-20T00:56:21.984811Z","shell.execute_reply.started":"2022-02-20T00:55:26.020609Z","shell.execute_reply":"2022-02-20T00:56:21.983113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE_ = [IMAGE_SIZE,IMAGE_SIZE]\nAUTO = tf.data.experimental.AUTOTUNE\nTRAINING_FILENAMES = tf.io.gfile.glob(f'/tmp/{DATASET_NAME}/happywhale-2022-test*.tfrec')\nprint(len(TRAINING_FILENAMES))\ndataset = load_dataset(TRAINING_FILENAMES, crop_method='detic', labeled=True)\ndataset = dataset.repeat()\ndataset = dataset.shuffle(2048)\ndataset = dataset.batch(BATCH_SIZE)\ndataset = dataset.prefetch(AUTO) #This dataset can directly be passed to keras.fit method\nprint(count_data_items(TRAINING_FILENAMES))\n\n# Displaying single batch of TFRecord\ntrain_batch = iter(dataset)\ndisplay_batch_of_images(next(train_batch))","metadata":{"execution":{"iopub.status.busy":"2022-02-20T00:56:21.986628Z","iopub.execute_input":"2022-02-20T00:56:21.986979Z","iopub.status.idle":"2022-02-20T00:56:22.178319Z","shell.execute_reply.started":"2022-02-20T00:56:21.986945Z","shell.execute_reply":"2022-02-20T00:56:22.177072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Upload Dataset","metadata":{}},{"cell_type":"code","source":"# !kaggle datasets version -m {version_name} -p /tmp/{DATASET_NAME} -r zip -q","metadata":{"execution":{"iopub.status.busy":"2022-02-19T06:58:45.893791Z","iopub.execute_input":"2022-02-19T06:58:45.894166Z","iopub.status.idle":"2022-02-19T07:41:51.046311Z","shell.execute_reply.started":"2022-02-19T06:58:45.894127Z","shell.execute_reply":"2022-02-19T07:41:51.043883Z"},"trusted":true},"execution_count":null,"outputs":[]}]}