Import Dataset CIFAR-10 Melalui Github

Lakukan clone repository github berikut:

!git clone https://github.com/YoongiKim/CIFAR-10-images.git

Tambahkan kode berikut untuk load dataset

import tensorflow as tf
import numpy as np
import os

def load_data(image_root='CIFAR-10-images', img_size=(32, 32), batch_size=32, as_numpy=True):
    train_dir = os.path.join(image_root, 'train')
    test_dir = os.path.join(image_root, 'test')

    train_ds = tf.keras.utils.image_dataset_from_directory(
        train_dir,
        labels='inferred',
        label_mode='int',
        image_size=img_size,
        batch_size=batch_size,
        shuffle=True
    )

    test_ds = tf.keras.utils.image_dataset_from_directory(
        test_dir,
        labels='inferred',
        label_mode='int',
        image_size=img_size,
        batch_size=batch_size,
        shuffle=False
    )

    if as_numpy:
        x_train, y_train = [], []
        for imgs, labels in train_ds:
            x_train.append(imgs.numpy())
            y_train.append(labels.numpy())
        x_train = np.concatenate(x_train, axis=0)
        if batch_size == None:
          y_train = np.stack(y_train, axis=0).reshape(-1, 1)
        else:
          y_train = np.concatenate(y_train, axis=0).reshape(-1, 1)

        x_test, y_test = [], []
        for imgs, labels in test_ds:
            x_test.append(imgs.numpy())
            y_test.append(labels.numpy())
        x_test = np.concatenate(x_test, axis=0)
        if batch_size == None:
          y_test = np.stack(y_test, axis=0).reshape(-1, 1)
        else:
          y_test = np.concatenate(y_test, axis=0).reshape(-1, 1)

        return (x_train.astype(np.uint8), y_train.astype(np.uint8)), (x_test.astype(np.uint8), y_test.astype(np.uint8))

    return train_ds, test_ds

Train dan Test Dataset bisa langsung di load dengan kode berikut

(X_train, y_train), (X_test, y_test) = load_data()