Datasets:

Languages:
English
ArXiv:
License:

Using with keras/tensorflow

#14
by RichardWhitehead - opened

Manually downloading the official files from ImageNet for use with tensorflow datasets takes forever - about 4 days. Whereas the Hugging Face equivalent loads in under 2 hours.
While doing the download and using tensorflow throughout is probably the right way to go, adapting the hugging face api to tensorflow is also an option that I wanted to investigate.

It took me a long time to work out how to pipe the hugging face dataset into keras. To save others the same pain, here is my code; it uses the keras pretrained ResNet50 model as an example.

from datasets import load_dataset
from keras.applications.resnet50 import ResNet50, preprocess_input
from keras.preprocessing.image import img_to_array
import numpy as np
import tensorflow as tf

BATCH_SIZE = 32
INPUT_SHAPE = (224, 224, 3)

dataset_train = load_dataset('imagenet-1k', split='train', streaming=False, token='<my_token>', trust_remote_code=True)

def train_image_generator():
    for example in dataset_train:
        # Load the image and resize it to the size expected by ResNet50
        img = img_to_array(example['image'])
        # Convert single-channel images to RGB
        if img.shape[2] == 1:
            img = np.dstack([img] * 3)
        elif img.shape[2] == 4:
            img = img[..., :3]
        img = tf.image.resize(img, INPUT_SHAPE[:2])
        img = preprocess_input(img)
        yield img

ds_train = tf.data.Dataset.from_generator(train_image_generator, output_signature=(
    tf.TensorSpec(shape=INPUT_SHAPE, dtype=tf.float32)))

ds_train = ds_train.batch(BATCH_SIZE)

model = ResNet50(weights='imagenet', include_top=True)

# predict batch-by-batch to avoid running out of memory
total_predicted = 0
total_correct = 0
for batch in ds_train:
    train_pred = model.predict_on_batch(batch)

    # keras model outputs are one-hot
    # compare to hugging face ground truth, which is categorical
    num_predicted = len(train_pred)
    num_correct = np.count_nonzero(np.argmax(train_pred, axis=1) == dataset_train[total_predicted : total_predicted + len(batch)]['label'])

    total_predicted += num_predicted
    total_correct += num_correct

print(f"Accuracy: {100.0 * total_correct / total_predicted:.2f}% from {total_predicted} samples")

Sign up or log in to comment