{"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-03-24T14:09:22.056871Z","iopub.execute_input":"2022-03-24T14:09:22.057527Z","iopub.status.idle":"2022-03-24T14:09:24.077875Z","shell.execute_reply.started":"2022-03-24T14:09:22.057402Z","shell.execute_reply":"2022-03-24T14:09:24.076907Z"},"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-03-24T14:09:26.304033Z","iopub.execute_input":"2022-03-24T14:09:26.305282Z","iopub.status.idle":"2022-03-24T14:09:26.404365Z","shell.execute_reply.started":"2022-03-24T14:09:26.305221Z","shell.execute_reply":"2022-03-24T14:09:26.403482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:09:26.831045Z","iopub.execute_input":"2022-03-24T14:09:26.831367Z","iopub.status.idle":"2022-03-24T14:09:26.84935Z","shell.execute_reply.started":"2022-03-24T14:09:26.831316Z","shell.execute_reply":"2022-03-24T14:09:26.848369Z"},"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/self-crop-yolov5/train_1.csv')\nyolo5_test_df = pd.read_csv('../input/self-crop-yolov5/test_1.csv')","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:09:28.04834Z","iopub.execute_input":"2022-03-24T14:09:28.04907Z","iopub.status.idle":"2022-03-24T14:09:28.204844Z","shell.execute_reply.started":"2022-03-24T14:09:28.049031Z","shell.execute_reply":"2022-03-24T14:09:28.203679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"yolo5_train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:09:28.665741Z","iopub.execute_input":"2022-03-24T14:09:28.666092Z","iopub.status.idle":"2022-03-24T14:09:28.680785Z","shell.execute_reply.started":"2022-03-24T14:09:28.666055Z","shell.execute_reply":"2022-03-24T14:09:28.679671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['yolo5_bbox'] = yolo5_train_df.yolo5_bbox\ntest_df['yolo5_bbox'] = yolo5_test_df.yolo5_bbox","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:09:29.415655Z","iopub.execute_input":"2022-03-24T14:09:29.416631Z","iopub.status.idle":"2022-03-24T14:09:29.425158Z","shell.execute_reply.started":"2022-03-24T14:09:29.416585Z","shell.execute_reply":"2022-03-24T14:09:29.423854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"type(train_df.iloc[33].yolo5_bbox)","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:21:18.599041Z","iopub.execute_input":"2022-03-24T14:21:18.599506Z","iopub.status.idle":"2022-03-24T14:21:18.606618Z","shell.execute_reply.started":"2022-03-24T14:21:18.599472Z","shell.execute_reply":"2022-03-24T14:21:18.605814Z"},"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-03-24T14:09:30.829256Z","iopub.execute_input":"2022-03-24T14:09:30.830296Z","iopub.status.idle":"2022-03-24T14:09:30.835879Z","shell.execute_reply.started":"2022-03-24T14:09:30.830251Z","shell.execute_reply":"2022-03-24T14:09:30.834853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def change_boundary(bbox_str):\n    np_bbox = read_bbox(bbox_str)\n    new_bbox = [] #left, top, right, bottom\n    left = int(np_bbox[0]-np_bbox[2]/2)\n    right = int(np_bbox[0]+np_bbox[2]/2)\n    top = int(np_bbox[1]-np_bbox[3]/2)\n    bottom = int(np_bbox[1]+np_bbox[3]/2)\n    new_bbox.append(str(left))\n    new_bbox.append(str(top))\n    new_bbox.append(str(right))\n    new_bbox.append(str(bottom))\n    new_bbox_str = ' '.join(new_bbox)\n    return new_bbox_str","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:29:34.978052Z","iopub.execute_input":"2022-03-24T14:29:34.978558Z","iopub.status.idle":"2022-03-24T14:29:34.987254Z","shell.execute_reply.started":"2022-03-24T14:29:34.978524Z","shell.execute_reply":"2022-03-24T14:29:34.986362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(change_boundary(train_df.iloc[0].yolo5_bbox))","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:29:35.32036Z","iopub.execute_input":"2022-03-24T14:29:35.320726Z","iopub.status.idle":"2022-03-24T14:29:35.328025Z","shell.execute_reply.started":"2022-03-24T14:29:35.32069Z","shell.execute_reply":"2022-03-24T14:29:35.326643Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['yolo5_bbox'] = train_df['yolo5_bbox'].astype('str')\ntrain_df['yolo5_bbox'] = train_df['yolo5_bbox'].apply(change_boundary)","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:35:00.075283Z","iopub.execute_input":"2022-03-24T14:35:00.076423Z","iopub.status.idle":"2022-03-24T14:35:00.171221Z","shell.execute_reply.started":"2022-03-24T14:35:00.076356Z","shell.execute_reply":"2022-03-24T14:35:00.169719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:32:48.38469Z","iopub.execute_input":"2022-03-24T14:32:48.385058Z","iopub.status.idle":"2022-03-24T14:32:48.39916Z","shell.execute_reply.started":"2022-03-24T14:32:48.385021Z","shell.execute_reply":"2022-03-24T14:32:48.398241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(read_bbox(train_df.iloc[1631].yolo5_bbox)))","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:11:37.359218Z","iopub.execute_input":"2022-03-24T14:11:37.360445Z","iopub.status.idle":"2022-03-24T14:11:37.367646Z","shell.execute_reply.started":"2022-03-24T14:11:37.360386Z","shell.execute_reply":"2022-03-24T14:11:37.366843Z"},"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-03-24T14:09:31.498317Z","iopub.execute_input":"2022-03-24T14:09:31.498702Z","iopub.status.idle":"2022-03-24T14:09:31.510047Z","shell.execute_reply.started":"2022-03-24T14:09:31.498664Z","shell.execute_reply":"2022-03-24T14:09:31.508847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"row = train_df.iloc[0]\nrow","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:12:53.560281Z","iopub.execute_input":"2022-03-24T14:12:53.561614Z","iopub.status.idle":"2022-03-24T14:12:53.57058Z","shell.execute_reply.started":"2022-03-24T14:12:53.56155Z","shell.execute_reply":"2022-03-24T14:12:53.569786Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_crop(row, {'yolov5'})","metadata":{"execution":{"iopub.status.busy":"2022-03-24T14:12:53.921338Z","iopub.execute_input":"2022-03-24T14:12:53.921718Z","iopub.status.idle":"2022-03-24T14:12:54.594351Z","shell.execute_reply.started":"2022-03-24T14:12:53.921681Z","shell.execute_reply":"2022-03-24T14:12:54.593546Z"},"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"detic_train_df.head()","metadata":{"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":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"row = train_df.iloc[1610]\nrow","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_crop(row, {'detic'})","metadata":{"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":{"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-25val'\n\n!rm -rf /tmp/{DATASET_NAME}\n\nos.makedirs(f'/tmp/{DATASET_NAME}', exist_ok=True)\n\nwith open('../input/api-cred/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\nprint(kaggle_creds['username'])\nprint(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'runjiali/{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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!rm -rf ~/.kaggle/kaggle.json","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_id_count = pd.DataFrame(train_df.individual_id.value_counts()).reset_index()\ntrain_id_count.columns = ['individual_id', 'count']\ntrain_id_count.iloc[6400]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.utils import shuffle\nid_nums = len(train_id_count)\n\ntrain_all_df_copy = train_df.copy(deep=False)\ntrain_id_count = shuffle(train_id_count, random_state=0)\ntrain_id_count","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm import tqdm\n#take out all pictures to the validation set for certain ids\nval_all_df = pd.DataFrame()\nfor i in tqdm(range(int(id_nums/4))):\n    individual_id = train_id_count.iloc[i].individual_id\n    val_all_df = val_all_df.append((train_all_df_copy[train_all_df_copy.individual_id==individual_id]))\n    train_all_df_copy.drop(train_all_df_copy[train_all_df_copy.individual_id==individual_id].index, axis=0, inplace=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(val_all_df), len(train_all_df_copy))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#take out half pictures to the validation set for certain ids\ntrain_half_df_copy = train_all_df_copy.copy(deep=False)\nval_half_df = pd.DataFrame()\nfor i in tqdm(range(int(id_nums/4), 2*int(id_nums/4))):\n    individual_id = train_id_count.iloc[i].individual_id\n    if train_id_count.iloc[i]['count']>=2:\n        half_count = int(train_id_count.iloc[i]['count']/2)\n        for index, row in train_half_df_copy.iterrows():\n            if half_count==0:\n                break\n            if row.individual_id==individual_id:\n                val_half_df = val_half_df.append(row)\n                train_half_df_copy.drop(index, axis=0, inplace=True)\n                half_count -= 1\n    else:\n        val_half_df = val_half_df.append((train_all_df_copy[train_all_df_copy.individual_id==individual_id]))\n        train_half_df_copy.drop(train_half_df_copy[train_half_df_copy.individual_id==individual_id].index, axis=0, inplace=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(val_half_df), len(train_half_df_copy))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create TFRecords","metadata":{}},{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_tf_records(df, name='train', progress=False):\n    tfr_filename = f'/tmp/{DATASET_NAME}/happywhale-2022-{name}-{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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_half_df['individual_id'] = val_half_df['individual_id'].astype('int') \ntrain_half_df_copy['individual_id'] = train_half_df_copy['individual_id'].astype('int') \nval_half_df['species'] = val_half_df['species'].astype('int') \ntrain_half_df_copy['species'] = train_half_df_copy['species'].astype('int') ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"create_tf_records(val_all_df, 'val_all', progress=False)\ncreate_tf_records(val_half_df, 'val_half', progress=False)\ncreate_tf_records(train_half_df_copy, 'train', progress=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_all_df.columns","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"def create_test_tf_records(df, progress=False):\n    tfr_filename = f'/tmp/{DATASET_NAME}/happywhale-2022-test-{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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"create_test_tf_records(test_df)","metadata":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /tmp/{DATASET_NAME}","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!rm -rf /tmp/{DATASET_NAME}/happywhale-2022-val_all-12433.tfrec\n!rm -rf /tmp/{DATASET_NAME}/happywhale-2022-val_half-7020.tfrec","metadata":{"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":{"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":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = 256\nBATCH_SIZE = 32","metadata":{"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":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Upload Dataset","metadata":{}},{"cell_type":"code","source":"!kaggle datasets create -p /tmp/happywhale-tfrecords-25val -r zip","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /tmp/happywhale-tfrecords-25val","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls ~/.kaggle","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!cp ../input/kaggleapicreds/kaggle.json ~/.kaggle","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}