{"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-24T07:03:47.979629Z","iopub.execute_input":"2022-02-24T07:03:47.98014Z","iopub.status.idle":"2022-02-24T07:03:53.431578Z","shell.execute_reply.started":"2022-02-24T07:03:47.980099Z","shell.execute_reply":"2022-02-24T07:03:53.430545Z"},"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/prepare-data-6329/train_fold10_onlymore2_6329.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-24T07:03:55.024698Z","iopub.execute_input":"2022-02-24T07:03:55.025065Z","iopub.status.idle":"2022-02-24T07:03:55.221514Z","shell.execute_reply.started":"2022-02-24T07:03:55.024998Z","shell.execute_reply":"2022-02-24T07:03:55.220301Z"},"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-24T07:03:56.299618Z","iopub.execute_input":"2022-02-24T07:03:56.299963Z","iopub.status.idle":"2022-02-24T07:03:57.127558Z","shell.execute_reply.started":"2022-02-24T07:03:56.299927Z","shell.execute_reply":"2022-02-24T07:03:57.126621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"yolo5_train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-02-24T07:03:57.915965Z","iopub.execute_input":"2022-02-24T07:03:57.916276Z","iopub.status.idle":"2022-02-24T07:03:57.940462Z","shell.execute_reply.started":"2022-02-24T07:03:57.916246Z","shell.execute_reply":"2022-02-24T07:03:57.939623Z"},"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-24T07:04:00.245125Z","iopub.execute_input":"2022-02-24T07:04:00.245692Z","iopub.status.idle":"2022-02-24T07:04:00.36693Z","shell.execute_reply.started":"2022-02-24T07:04:00.245658Z","shell.execute_reply":"2022-02-24T07:04:00.365748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-02-24T07:04:01.718468Z","iopub.execute_input":"2022-02-24T07:04:01.718811Z","iopub.status.idle":"2022-02-24T07:04:01.735665Z","shell.execute_reply.started":"2022-02-24T07:04:01.718778Z","shell.execute_reply":"2022-02-24T07:04:01.734687Z"},"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-24T07:04:04.200332Z","iopub.execute_input":"2022-02-24T07:04:04.200965Z","iopub.status.idle":"2022-02-24T07:04:04.205685Z","shell.execute_reply.started":"2022-02-24T07:04:04.200926Z","shell.execute_reply":"2022-02-24T07:04:04.204827Z"},"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-24T07:04:08.470569Z","iopub.execute_input":"2022-02-24T07:04:08.470833Z","iopub.status.idle":"2022-02-24T07:04:08.483348Z","shell.execute_reply.started":"2022-02-24T07:04:08.470805Z","shell.execute_reply":"2022-02-24T07:04:08.482118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"row = train_df.iloc[1610]\nrow","metadata":{"execution":{"iopub.status.busy":"2022-02-24T07:04:11.891092Z","iopub.execute_input":"2022-02-24T07:04:11.892121Z","iopub.status.idle":"2022-02-24T07:04:11.902281Z","shell.execute_reply.started":"2022-02-24T07:04:11.892079Z","shell.execute_reply":"2022-02-24T07:04:11.900912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_crop(row, {'yolov5'})","metadata":{"execution":{"iopub.status.busy":"2022-02-24T07:04:13.753166Z","iopub.execute_input":"2022-02-24T07:04:13.754123Z","iopub.status.idle":"2022-02-24T07:04:15.633099Z","shell.execute_reply.started":"2022-02-24T07:04:13.754064Z","shell.execute_reply":"2022-02-24T07:04:15.632373Z"},"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-24T07:04:21.436942Z","iopub.execute_input":"2022-02-24T07:04:21.437695Z","iopub.status.idle":"2022-02-24T07:04:21.645397Z","shell.execute_reply.started":"2022-02-24T07:04:21.43765Z","shell.execute_reply":"2022-02-24T07:04:21.644455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"detic_train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-02-24T07:04:24.231932Z","iopub.execute_input":"2022-02-24T07:04:24.232248Z","iopub.status.idle":"2022-02-24T07:04:24.243905Z","shell.execute_reply.started":"2022-02-24T07:04:24.232216Z","shell.execute_reply":"2022-02-24T07:04:24.243189Z"},"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-24T07:04:27.809902Z","iopub.execute_input":"2022-02-24T07:04:27.810462Z","iopub.status.idle":"2022-02-24T07:04:27.825609Z","shell.execute_reply.started":"2022-02-24T07:04:27.810418Z","shell.execute_reply":"2022-02-24T07:04:27.824442Z"},"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-24T07:04:30.736384Z","iopub.execute_input":"2022-02-24T07:04:30.736667Z","iopub.status.idle":"2022-02-24T07:04:30.744452Z","shell.execute_reply.started":"2022-02-24T07:04:30.736639Z","shell.execute_reply":"2022-02-24T07:04:30.743565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"row = train_df.iloc[1610]\nrow","metadata":{"execution":{"iopub.status.busy":"2022-02-24T07:04:32.328994Z","iopub.execute_input":"2022-02-24T07:04:32.330207Z","iopub.status.idle":"2022-02-24T07:04:32.337212Z","shell.execute_reply.started":"2022-02-24T07:04:32.330148Z","shell.execute_reply":"2022-02-24T07:04:32.336467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_crop(row, {'detic'})","metadata":{"execution":{"iopub.status.busy":"2022-02-24T07:04:50.589166Z","iopub.execute_input":"2022-02-24T07:04:50.589959Z","iopub.status.idle":"2022-02-24T07:04:52.160597Z","shell.execute_reply.started":"2022-02-24T07:04:50.589921Z","shell.execute_reply":"2022-02-24T07:04:52.159782Z"},"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-24T07:04:52.546966Z","iopub.execute_input":"2022-02-24T07:04:52.547273Z","iopub.status.idle":"2022-02-24T07:04:52.584152Z","shell.execute_reply.started":"2022-02-24T07:04:52.547241Z","shell.execute_reply":"2022-02-24T07:04:52.58324Z"},"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-512_6329'\n\n!rm -rf /tmp/{DATASET_NAME}\n\nos.makedirs(f'/tmp/{DATASET_NAME}', exist_ok=True)\n\nwith open('../input/kaggleapicreds/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-24T07:05:21.506855Z","iopub.execute_input":"2022-02-24T07:05:21.507308Z","iopub.status.idle":"2022-02-24T07:05:25.046752Z","shell.execute_reply.started":"2022-02-24T07:05:21.507274Z","shell.execute_reply":"2022-02-24T07:05:25.045723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create TFRecords","metadata":{}},{"cell_type":"code","source":"train_df['fold'] = train_df['kfold']\ntrain_df[\"species\"] = train_df[\"species_num\"]\ntrain_df[\"individual_id\"] = train_df[\"individual_id_num\"]","metadata":{"execution":{"iopub.status.busy":"2022-02-24T07:05:50.791731Z","iopub.execute_input":"2022-02-24T07:05:50.792488Z","iopub.status.idle":"2022-02-24T07:05:50.807088Z","shell.execute_reply.started":"2022-02-24T07:05:50.79244Z","shell.execute_reply":"2022-02-24T07:05:50.806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-24T07:06:07.536169Z","iopub.execute_input":"2022-02-24T07:06:07.536636Z","iopub.status.idle":"2022-02-24T07:06:07.544263Z","shell.execute_reply.started":"2022-02-24T07:06:07.536585Z","shell.execute_reply":"2022-02-24T07:06:07.543339Z"},"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-24T07:06:09.547916Z","iopub.execute_input":"2022-02-24T07:06:09.548389Z","iopub.status.idle":"2022-02-24T07:06:09.558477Z","shell.execute_reply.started":"2022-02-24T07:06:09.548338Z","shell.execute_reply":"2022-02-24T07:06:09.55787Z"},"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-24T07:06:14.598701Z","iopub.execute_input":"2022-02-24T07:06:14.599391Z","iopub.status.idle":"2022-02-24T07:06:14.608893Z","shell.execute_reply.started":"2022-02-24T07:06:14.599339Z","shell.execute_reply":"2022-02-24T07:06:14.60788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create_tf_records(0, progress=True)","metadata":{"execution":{"iopub.status.busy":"2022-02-24T06:42:32.721394Z","iopub.execute_input":"2022-02-24T06:42:32.721616Z","iopub.status.idle":"2022-02-24T06:42:32.73745Z","shell.execute_reply.started":"2022-02-24T06:42:32.721589Z","shell.execute_reply":"2022-02-24T06:42:32.736769Z"},"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-24T07:06:20.769694Z","iopub.execute_input":"2022-02-24T07:06:20.770004Z"},"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":{"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":{"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":"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-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":{"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 version -m {version_name} -p /tmp/{DATASET_NAME} -r zip -q","metadata":{"execution":{"iopub.status.busy":"2022-02-24T06:42:43.860588Z","iopub.status.idle":"2022-02-24T06:42:43.861115Z","shell.execute_reply.started":"2022-02-24T06:42:43.860818Z","shell.execute_reply":"2022-02-24T06:42:43.860846Z"},"trusted":true},"execution_count":null,"outputs":[]}]}