{"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":"# Creating TfRecords for Backfin Crops","metadata":{}},{"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\nfrom tqdm import tqdm","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-02-27T09:24:02.262493Z","iopub.execute_input":"2022-02-27T09:24:02.263206Z","iopub.status.idle":"2022-02-27T09:24:07.39523Z","shell.execute_reply.started":"2022-02-27T09:24:02.263079Z","shell.execute_reply":"2022-02-27T09:24:07.394303Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\n### Create Kaggle Dataset if not exists \n\nDATASET_NAME = f'backfintfrecords'\n\n!rm -r /tmp/{DATASET_NAME}\n\nos.makedirs(f'/tmp/{DATASET_NAME}', exist_ok=True)\n\nwith open('../input/d/jpbremer/kaggle-api-creds/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\n\nwith open(f'/tmp/{DATASET_NAME}/dataset-metadata.json') as f:\n    dataset_meta = json.load(f)\ndataset_meta['id'] = f'jpbremer/{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-27T09:24:07.39702Z","iopub.execute_input":"2022-02-27T09:24:07.397354Z","iopub.status.idle":"2022-02-27T09:24:19.134718Z","shell.execute_reply.started":"2022-02-27T09:24:07.39731Z","shell.execute_reply":"2022-02-27T09:24:19.133826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv('../input/happywhale-splits/skf_species_10folds.csv')\n\ntrain_df = train_df.iloc[:]\ntest_df = pd.read_csv('../input/happy-whale-and-dolphin/sample_submission.csv')\ntest_df = test_df.iloc[:]\ntest_df['split'] = test_df.index%10\ntrain_df.agg(['min','max','count','nunique'])","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:27.853836Z","iopub.execute_input":"2022-02-27T09:25:27.854136Z","iopub.status.idle":"2022-02-27T09:25:27.979298Z","shell.execute_reply.started":"2022-02-27T09:25:27.854104Z","shell.execute_reply":"2022-02-27T09:25:27.978148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df2 = pd.read_csv(\"../input/backfin-detection-with-yolov5/train.csv\")\ntest_df2 = pd.read_csv(\"../input/backfin-detection-with-yolov5/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:36.704957Z","iopub.execute_input":"2022-02-27T09:25:36.705761Z","iopub.status.idle":"2022-02-27T09:25:37.220047Z","shell.execute_reply.started":"2022-02-27T09:25:36.705713Z","shell.execute_reply":"2022-02-27T09:25:37.21932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df2 = train_df2.iloc[:, :]\ntrain_df2 = train_df2[[\"species\", \"bbox\", \"image\"]]\ntrain_df2.columns = [\"species_x\", \"bbox\", \"image\"]\n\n\ntest_df2 = test_df2.iloc[:, :]\ntest_df2 = test_df2[[\"bbox\", \"image\"]]\ntest_df2.columns = [\"bbox\", \"image\"]","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:37.221342Z","iopub.execute_input":"2022-02-27T09:25:37.222119Z","iopub.status.idle":"2022-02-27T09:25:37.244319Z","shell.execute_reply.started":"2022-02-27T09:25:37.222068Z","shell.execute_reply":"2022-02-27T09:25:37.243526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df2[\"image\"] = train_df2[\"image\"].astype(object)\ntrain_df = pd.merge(train_df2, train_df, on = \"image\")\n\ntest_df2[\"image\"] = test_df2[\"image\"].astype(object)\ntest_df = pd.merge(test_df2, test_df, on = \"image\")","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:37.245845Z","iopub.execute_input":"2022-02-27T09:25:37.246103Z","iopub.status.idle":"2022-02-27T09:25:37.28732Z","shell.execute_reply.started":"2022-02-27T09:25:37.246073Z","shell.execute_reply":"2022-02-27T09:25:37.286376Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"arr = [\n         'blue_whale',\n         'bottlenose_dolphin',\n         'brydes_whale',\n         'commersons_dolphin',\n         'common_dolphin',\n         'cuviers_beaked_whale',\n         'dusky_dolphin',\n         'false_killer_whale',\n         'fin_whale',\n         'frasiers_dolphin',\n         'globis',\n         'humpback_whale',\n         'killer_whale',\n         'long_finned_pilot_whale',\n         'melon_headed_whale',\n         'minke_whale',\n         'pantropic_spotted_dolphin',\n         'pilot_whale',\n         'pygmy_killer_whale',\n         'rough_toothed_dolphin',\n         'sei_whale',\n         'short_finned_pilot_whale',\n         'spinner_dolphin',\n         'spotted_dolphin',\n         'white_sided_dolphin'\n    \n        ]\n\ntrain_df = train_df[train_df[\"species_x\"].isin(arr)]","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:37.28916Z","iopub.execute_input":"2022-02-27T09:25:37.289447Z","iopub.status.idle":"2022-02-27T09:25:37.296886Z","shell.execute_reply.started":"2022-02-27T09:25:37.289415Z","shell.execute_reply":"2022-02-27T09:25:37.295834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = test_df[~(test_df[\"bbox\"].str.find(\"[[]]\") != -1)].reset_index(drop = True)","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:37.298448Z","iopub.execute_input":"2022-02-27T09:25:37.298861Z","iopub.status.idle":"2022-02-27T09:25:37.312781Z","shell.execute_reply.started":"2022-02-27T09:25:37.298828Z","shell.execute_reply":"2022-02-27T09:25:37.311869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = train_df[~train_df[\"bbox\"].isna()]\ntest_df = test_df[~test_df[\"bbox\"].isna()]","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:37.314008Z","iopub.execute_input":"2022-02-27T09:25:37.314307Z","iopub.status.idle":"2022-02-27T09:25:37.324861Z","shell.execute_reply.started":"2022-02-27T09:25:37.314267Z","shell.execute_reply":"2022-02-27T09:25:37.323946Z"},"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', \"bbox\"]]\n    return val_df","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:37.326076Z","iopub.execute_input":"2022-02-27T09:25:37.326432Z","iopub.status.idle":"2022-02-27T09:25:37.338537Z","shell.execute_reply.started":"2022-02-27T09:25:37.326397Z","shell.execute_reply":"2022-02-27T09:25:37.3376Z"},"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 serialize_example(image,image_name,target,species):\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      }\n    example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n    return example_proto.SerializeToString()","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:37.340259Z","iopub.execute_input":"2022-02-27T09:25:37.341234Z","iopub.status.idle":"2022-02-27T09:25:37.648147Z","shell.execute_reply.started":"2022-02-27T09:25:37.341125Z","shell.execute_reply":"2022-02-27T09:25:37.64688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_tf_records(fold  = 0):\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        for i,row in df.iterrows():\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            \n            img = cv2.imread(f\"../input/happy-whale-and-dolphin/train_images/{image_id}\")\n  \n            bbox = row[\"bbox\"]\n            bbox = re.findall(r'\\d+', bbox)\n        \n            x1, x2, y1, y2 = int(bbox[1]),  int(bbox[3]) , int(bbox[0]) , int(bbox[2])\n            \n            img = img[x1 : x2, y1:y2]\n            \n            cv2.imwrite(f'/tmp/{DATASET_NAME}/temp{fold}.png', img)\n\n            image_encoded = tf.io.read_file(f'/tmp/{DATASET_NAME}/temp{fold}.png')\n            \n            img = cv2.imread(image_path)\n            \n            rgb_tensor = tf.convert_to_tensor(img, dtype=tf.float32)           \n            \n            image_name = str.encode(image_id)\n            example = serialize_example(image_encoded,image_name,target,species)\n            writer.write(example)","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:37.649452Z","iopub.execute_input":"2022-02-27T09:25:37.650428Z","iopub.status.idle":"2022-02-27T09:25:37.661464Z","shell.execute_reply.started":"2022-02-27T09:25:37.650378Z","shell.execute_reply":"2022-02-27T09:25:37.660405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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))\n    )#'\\xff\\xd8\\xff\\xe0\\x00\\x10JFIF\\x00\\x01\\x01\\\n","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:37.664569Z","iopub.execute_input":"2022-02-27T09:25:37.664941Z","iopub.status.idle":"2022-02-27T09:25:53.299568Z","shell.execute_reply.started":"2022-02-27T09:25:37.664881Z","shell.execute_reply":"2022-02-27T09:25:53.298589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_test_tf_records(fold  = 0):\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        for i,row in df.iterrows():\n            image_id = row.image\n            target = -1\n            species = -1\n            try:\n                img = cv2.imread(f\"../input/happy-whale-and-dolphin/test_images/{image_id}\")\n\n                bbox = row[\"bbox\"]\n                bbox = re.findall(r'\\d+', bbox)\n\n                x1, x2, y1, y2 = int(bbox[1]),  int(bbox[3]) , int(bbox[0]) , int(bbox[2])\n\n                img = img[x1 : x2, y1:y2]\n\n                cv2.imwrite(f'/tmp/{DATASET_NAME}/temp{fold}.png', img)\n                \n                image_encoded = tf.io.read_file(f'/tmp/{DATASET_NAME}/temp{fold}.png')\n\n                image_name = str.encode(image_id)\n                example = serialize_example(image_encoded,image_name,target,species)\n                writer.write(example)\n            except:\n                continue","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:53.300855Z","iopub.execute_input":"2022-02-27T09:25:53.301376Z","iopub.status.idle":"2022-02-27T09:25:53.310382Z","shell.execute_reply.started":"2022-02-27T09:25:53.301343Z","shell.execute_reply":"2022-02-27T09:25:53.309613Z"},"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    )\n","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:53.311678Z","iopub.execute_input":"2022-02-27T09:25:53.312015Z","iopub.status.idle":"2022-02-27T09:25:57.62474Z","shell.execute_reply.started":"2022-02-27T09:25:53.311985Z","shell.execute_reply":"2022-02-27T09:25:57.623628Z"},"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-27T09:25:57.626799Z","iopub.execute_input":"2022-02-27T09:25:57.627118Z","iopub.status.idle":"2022-02-27T09:25:57.633049Z","shell.execute_reply.started":"2022-02-27T09:25:57.627077Z","shell.execute_reply":"2022-02-27T09:25:57.632147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /tmp/{DATASET_NAME}","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:57.634558Z","iopub.execute_input":"2022-02-27T09:25:57.635031Z","iopub.status.idle":"2022-02-27T09:25:58.550032Z","shell.execute_reply.started":"2022-02-27T09:25:57.634988Z","shell.execute_reply":"2022-02-27T09:25:58.549104Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DATASET_NAME","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:58.551599Z","iopub.execute_input":"2022-02-27T09:25:58.551839Z","iopub.status.idle":"2022-02-27T09:25:58.559272Z","shell.execute_reply.started":"2022-02-27T09:25:58.551813Z","shell.execute_reply":"2022-02-27T09:25:58.558662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!kaggle datasets version -m {version_name} -p /tmp/{DATASET_NAME} -r zip -q","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:25:58.56003Z","iopub.execute_input":"2022-02-27T09:25:58.560258Z","iopub.status.idle":"2022-02-27T09:28:47.201681Z","shell.execute_reply.started":"2022-02-27T09:25:58.560222Z","shell.execute_reply":"2022-02-27T09:28:47.20051Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Verify TFRecords","metadata":{}},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\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):\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    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = example['target']\n    return image, label # returns a dataset of (image, label) pairs\n\ndef load_dataset(filenames, 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(read_labeled_tfrecord)\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():\n    dataset = load_dataset(TRAINING_FILENAMES, 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-27T09:28:47.221033Z","iopub.status.idle":"2022-02-27T09:28:47.22179Z","shell.execute_reply.started":"2022-02-27T09:28:47.221532Z","shell.execute_reply":"2022-02-27T09:28:47.22156Z"},"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\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.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\n\ndef display_single_sample(image, label, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\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 = 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(images[:rows*cols], labels[:rows*cols])):\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-27T09:28:47.223372Z","iopub.status.idle":"2022-02-27T09:28:47.224067Z","shell.execute_reply.started":"2022-02-27T09:28:47.22382Z","shell.execute_reply":"2022-02-27T09:28:47.223847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = 256\nBATCH_SIZE = 32","metadata":{"execution":{"iopub.status.busy":"2022-02-27T09:28:47.225524Z","iopub.status.idle":"2022-02-27T09:28:47.226267Z","shell.execute_reply.started":"2022-02-27T09:28:47.225978Z","shell.execute_reply":"2022-02-27T09:28:47.226006Z"},"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, 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-27T09:28:47.227661Z","iopub.status.idle":"2022-02-27T09:28:47.228405Z","shell.execute_reply.started":"2022-02-27T09:28:47.228123Z","shell.execute_reply":"2022-02-27T09:28:47.228161Z"},"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, 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-27T09:28:47.229921Z","iopub.status.idle":"2022-02-27T09:28:47.230685Z","shell.execute_reply.started":"2022-02-27T09:28:47.230438Z","shell.execute_reply":"2022-02-27T09:28:47.230466Z"},"trusted":true},"execution_count":null,"outputs":[]}]}