splits a dataset into a left half and a right half e g train test args dataset a tf data dataset a torch utils data dataset object or a listtuple of arrays with the same length leftsize if float in the range 0 1 it signifies the fraction of the data to pack in the left dataset if integer it signifies the number of samples to pack in the left dataset if none defaults to the complement to rightsize defaults to none rightsize if float in the range 0 1 it signifies the fraction of the data to pack in the right dataset if integer it signifies the number of samples to pack in the right dataset if none defaults to the complement to leftsize defaults to none shuffle boolean whether to shuffle the data before splitting it seed a random seed for shuffling returns a tuple of two tf data dataset objects the left and right splits example data np random randomsize1000 4 leftds rightds keras utils splitdatasetdata leftsize0 8 intleftds cardinality 800 intrightds cardinality 200 apply batching to the splits if the dataset is batched convert dataset object to a list of samples args dataset a tf data dataset a torch utils data dataset object or a listtuple of arrays datasettypespec the type of the dataset datasizewarningflag if set to true a warning will be issued if the dataset takes longer than 10 seconds to iterate defaults to true ensureshapesimilarity if set to true the shape of the first sample will be used to validate the shape of rest of the samples defaults to true returns list a list of samples the tryexcept here is for numpy 1 24 compatibility see https numpy orgnepsnep0034inferdtypeisobject html get the iterator from a dataset args dataset a tf data dataset a torch utils data dataset object or a listtuple of arrays datasettypespec the type of the dataset returns iterator an iterator object yield data samples from the datasetiterator args datasetiterator an iterator object ensureshapesimilarity if set to true the shape of the first sample will be used to validate the shape of rest of the samples defaults to true datasizewarningflag if set to true a warning will be issued if the dataset takes longer than 10 seconds to iterate defaults to true starttime float the start time of the dataset iteration this is used only if datasizewarningflag is set to true yields datasample the next sample warns user if the dataset is too large to iterate within 10s rescale the dataset split sizes we want to ensure that the sum of the split sizes is equal to the total length of the dataset args leftsize the size of the left dataset split rightsize the size of the right dataset split totallength the total length of the dataset returns tuple a tuple of rescaled leftsize and rightsize integers check both leftsize and rightsize are integers or floats check leftsize is a integer or float check rightsize is a integer or float check leftsize and rightsize are nonzero check leftsize is nonnegative and less than 1 and less than totallength check rightsize is nonnegative and less than 1 and less than totallength check sum of leftsize and rightsize is less than or equal to totallength restore the dataset from the list of arrays if datasettypespec in tuple list return tuplenp arraysample for sample in zipdatasetaslist elif datasettypespec tf data dataset if isinstanceoriginaldataset elementspec dict restoreddataset for d in datasetaslist for k v in d items if k not in restoreddataset restoreddatasetk v else restoreddatasetk appendv return restoreddataset else return tuplenp arraysample for sample in zipdatasetaslist elif istorchdatasetoriginaldataset return tuplenp arraysample for sample in zipdatasetaslist return datasetaslist def isbatcheddataset get the batch size of the dataset if isbatcheddataset return dataset batchsize else return none def gettypespecdataset list all files in directory with their labels args directory directory where the data is located if labels is inferred it should contain subdirectories each containing files for a class otherwise the directory structure is ignored labels either inferred labels are generated from the directory structure none no labels or a listtuple of integer labels of the same size as the number of valid files found in the directory labels should be sorted according to the alphanumeric order of the image file paths obtained via os walkdirectory in python formats allowlist of file extensions to index e g jpg txt classnames only valid if labelsinferred this is the explicit list of class names must match names of subdirectories used to control the order of the classes otherwise alphanumerical order is used shuffle whether to shuffle the data default true if set to false sorts the data in alphanumeric order seed optional random seed for shuffling followlinks whether to visits subdirectories pointed to by symlinks returns tuple filepaths labels classnames filepaths list of file paths strings labels list of matching integer labels same length as filepaths classnames names of the classes corresponding to these labels in order in the explicitnolabel cases index from the parent directory down build an index of the files in the different class subfolders inferred labels manual labels shuffle globally to erase macrostructure recursively walks directory and list image paths and their class index args directory string target directory classindices dict mapping class names to their index followlinks boolean whether to recursively follow subdirectories if false we only list toplevel images in directory formats allowlist of file extensions to index e g jpg txt returns tuple filenames labels filenames is a list of relative file paths and labels is a list of integer labels corresponding to these files potentially restict samples labels to a training or validation split args samples list of elements labels list of corresponding labels validationsplit float fraction of data to reserve for validation subset subset of the data to return either training validation or none if none we return all of the data returns tuple samples labels potentially restricted to the specified subset create a tf data dataset from the listtuple of labels args labels listtuple of labels to be converted into a tf data dataset labelmode string describing the encoding of labels options are binary indicates that the labels there can be only 2 are encoded as float32 scalars with values 0 or 1 e g for binarycrossentropy categorical means that the labels are mapped into a categorical vector e g for categoricalcrossentropy loss numclasses number of classes of labels returns a tf data dataset instance raise errors in case of invalid argument values args validationsplit float between 0 and 1 fraction of data to reserve for validation subset one of training validation or both only used if validationsplit is set shuffle whether to shuffle the data either true or false seed random seed for shuffling and transformations splits a dataset into a left half and a right half e g train test args dataset a tf data dataset a torch utils data dataset object or a list tuple of arrays with the same length left_size if float in the range 0 1 it signifies the fraction of the data to pack in the left dataset if integer it signifies the number of samples to pack in the left dataset if none defaults to the complement to right_size defaults to none right_size if float in the range 0 1 it signifies the fraction of the data to pack in the right dataset if integer it signifies the number of samples to pack in the right dataset if none defaults to the complement to left_size defaults to none shuffle boolean whether to shuffle the data before splitting it seed a random seed for shuffling returns a tuple of two tf data dataset objects the left and right splits example data np random random size 1000 4 left_ds right_ds keras utils split_dataset data left_size 0 8 int left_ds cardinality 800 int right_ds cardinality 200 apply batching to the splits if the dataset is batched convert dataset object to a list of samples args dataset a tf data dataset a torch utils data dataset object or a list tuple of arrays dataset_type_spec the type of the dataset data_size_warning_flag if set to true a warning will be issued if the dataset takes longer than 10 seconds to iterate defaults to true ensure_shape_similarity if set to true the shape of the first sample will be used to validate the shape of rest of the samples defaults to true returns list a list of samples the try except here is for numpy 1 24 compatibility see https numpy org neps nep 0034 infer dtype is object html get the iterator from a dataset args dataset a tf data dataset a torch utils data dataset object or a list tuple of arrays dataset_type_spec the type of the dataset returns iterator an iterator object yield data samples from the dataset_iterator args dataset_iterator an iterator object ensure_shape_similarity if set to true the shape of the first sample will be used to validate the shape of rest of the samples defaults to true data_size_warning_flag if set to true a warning will be issued if the dataset takes longer than 10 seconds to iterate defaults to true start_time float the start time of the dataset iteration this is used only if data_size_warning_flag is set to true yields data_sample the next sample warns user if the dataset is too large to iterate within 10s rescale the dataset split sizes we want to ensure that the sum of the split sizes is equal to the total length of the dataset args left_size the size of the left dataset split right_size the size of the right dataset split total_length the total length of the dataset returns tuple a tuple of rescaled left_size and right_size integers check both left_size and right_size are integers or floats check left_size is a integer or float check right_size is a integer or float check left_size and right_size are non zero check left_size is non negative and less than 1 and less than total_length check right_size is non negative and less than 1 and less than total_length check sum of left_size and right_size is less than or equal to total_length restore the dataset from the list of arrays check if the tf data dataset is batched get the batch size of the dataset get the type spec of the dataset list all files in directory with their labels args directory directory where the data is located if labels is inferred it should contain subdirectories each containing files for a class otherwise the directory structure is ignored labels either inferred labels are generated from the directory structure none no labels or a list tuple of integer labels of the same size as the number of valid files found in the directory labels should be sorted according to the alphanumeric order of the image file paths obtained via os walk directory in python formats allowlist of file extensions to index e g jpg txt class_names only valid if labels inferred this is the explicit list of class names must match names of subdirectories used to control the order of the classes otherwise alphanumerical order is used shuffle whether to shuffle the data default true if set to false sorts the data in alphanumeric order seed optional random seed for shuffling follow_links whether to visits subdirectories pointed to by symlinks returns tuple file_paths labels class_names file_paths list of file paths strings labels list of matching integer labels same length as file_paths class_names names of the classes corresponding to these labels in order keep provided order in the explicit no label cases index from the parent directory down build an index of the files in the different class subfolders inferred labels manual labels shuffle globally to erase macro structure recursively walks directory and list image paths and their class index args directory string target directory class_indices dict mapping class names to their index follow_links boolean whether to recursively follow subdirectories if false we only list top level images in directory formats allowlist of file extensions to index e g jpg txt returns tuple filenames labels filenames is a list of relative file paths and labels is a list of integer labels corresponding to these files potentially restict samples labels to a training or validation split args samples list of elements labels list of corresponding labels validation_split float fraction of data to reserve for validation subset subset of the data to return either training validation or none if none we return all of the data returns tuple samples labels potentially restricted to the specified subset create a tf data dataset from the list tuple of labels args labels list tuple of labels to be converted into a tf data dataset label_mode string describing the encoding of labels options are binary indicates that the labels there can be only 2 are encoded as float32 scalars with values 0 or 1 e g for binary_crossentropy categorical means that the labels are mapped into a categorical vector e g for categorical_crossentropy loss num_classes number of classes of labels returns a tf data dataset instance raise errors in case of invalid argument values args validation_split float between 0 and 1 fraction of data to reserve for validation subset one of training validation or both only used if validation_split is set shuffle whether to shuffle the data either true or false seed random seed for shuffling and transformations
import os
import random
import time
import warnings
from multiprocessing.pool import ThreadPool

import numpy as np

from keras.api_export import keras_export
from keras.utils import io_utils
from keras.utils.module_utils import tensorflow as tf


@keras_export("keras.utils.split_dataset")
def split_dataset(
    dataset, left_size=None, right_size=None, shuffle=False, seed=None
):
    
    dataset_type_spec = _get_type_spec(dataset)

    if dataset_type_spec is None:
        raise TypeError(
            "The `dataset` argument must be either"
            "a `tf.data.Dataset`, a `torch.utils.data.Dataset`"
            "object, or a list/tuple of arrays. "
            f"Received: dataset={dataset} of type {type(dataset)}"
        )

    if right_size is None and left_size is None:
        raise ValueError(
            "At least one of the `left_size` or `right_size` "
            "must be specified. Received: left_size=None and "
            "right_size=None"
        )

    dataset_as_list = _convert_dataset_to_list(dataset, dataset_type_spec)

    if shuffle:
        if seed is None:
            seed = random.randint(0, int(1e6))
        random.seed(seed)
        random.shuffle(dataset_as_list)

    total_length = len(dataset_as_list)

    left_size, right_size = _rescale_dataset_split_sizes(
        left_size, right_size, total_length
    )
    left_split = list(dataset_as_list[:left_size])
    right_split = list(dataset_as_list[-right_size:])

    left_split = _restore_dataset_from_list(
        left_split, dataset_type_spec, dataset
    )
    right_split = _restore_dataset_from_list(
        right_split, dataset_type_spec, dataset
    )

    left_split = tf.data.Dataset.from_tensor_slices(left_split)
    right_split = tf.data.Dataset.from_tensor_slices(right_split)

    
    if dataset_type_spec is tf.data.Dataset and is_batched(dataset):
        batch_size = get_batch_size(dataset)
        if batch_size is not None:
            left_split = left_split.batch(batch_size)
            right_split = right_split.batch(batch_size)

    left_split = left_split.prefetch(tf.data.AUTOTUNE)
    right_split = right_split.prefetch(tf.data.AUTOTUNE)
    return left_split, right_split


def _convert_dataset_to_list(
    dataset,
    dataset_type_spec,
    data_size_warning_flag=True,
    ensure_shape_similarity=True,
):
    
    dataset_iterator = _get_data_iterator_from_dataset(
        dataset, dataset_type_spec
    )
    dataset_as_list = []

    start_time = time.time()
    for sample in _get_next_sample(
        dataset_iterator,
        ensure_shape_similarity,
        data_size_warning_flag,
        start_time,
    ):
        if dataset_type_spec in [tuple, list]:
            
            
            try:
                arr = np.array(sample)
            except ValueError:
                arr = np.array(sample, dtype=object)
            dataset_as_list.append(arr)
        else:
            dataset_as_list.append(sample)

    return dataset_as_list


def _get_data_iterator_from_dataset(dataset, dataset_type_spec):
    
    if dataset_type_spec == list:
        if len(dataset) == 0:
            raise ValueError(
                "Received an empty list dataset. "
                "Please provide a non-empty list of arrays."
            )

        if _get_type_spec(dataset[0]) is np.ndarray:
            expected_shape = dataset[0].shape
            for i, element in enumerate(dataset):
                if np.array(element).shape[0] != expected_shape[0]:
                    raise ValueError(
                        "Received a list of NumPy arrays with different "
                        f"lengths. Mismatch found at index {i}, "
                        f"Expected shape={expected_shape} "
                        f"Received shape={np.array(element).shape}."
                        "Please provide a list of NumPy arrays with "
                        "the same length."
                    )
        else:
            raise ValueError(
                "Expected a list of `numpy.ndarray` objects,"
                f"Received: {type(dataset[0])}"
            )

        return iter(zip(*dataset))
    elif dataset_type_spec == tuple:
        if len(dataset) == 0:
            raise ValueError(
                "Received an empty list dataset."
                "Please provide a non-empty tuple of arrays."
            )

        if _get_type_spec(dataset[0]) is np.ndarray:
            expected_shape = dataset[0].shape
            for i, element in enumerate(dataset):
                if np.array(element).shape[0] != expected_shape[0]:
                    raise ValueError(
                        "Received a tuple of NumPy arrays with different "
                        f"lengths. Mismatch found at index {i}, "
                        f"Expected shape={expected_shape} "
                        f"Received shape={np.array(element).shape}."
                        "Please provide a tuple of NumPy arrays with "
                        "the same length."
                    )
        else:
            raise ValueError(
                "Expected a tuple of `numpy.ndarray` objects, "
                f"Received: {type(dataset[0])}"
            )

        return iter(zip(*dataset))
    elif dataset_type_spec == tf.data.Dataset:
        if is_batched(dataset):
            dataset = dataset.unbatch()
        return iter(dataset)

    elif is_torch_dataset(dataset):
        return iter(dataset)
    elif dataset_type_spec == np.ndarray:
        return iter(dataset)
    raise ValueError(f"Invalid dataset_type_spec: {dataset_type_spec}")


def _get_next_sample(
    dataset_iterator,
    ensure_shape_similarity,
    data_size_warning_flag,
    start_time,
):
    
    try:
        dataset_iterator = iter(dataset_iterator)
        first_sample = next(dataset_iterator)
        if isinstance(first_sample, (tf.Tensor, np.ndarray)) or is_torch_tensor(
            first_sample
        ):
            first_sample_shape = np.array(first_sample).shape
        else:
            first_sample_shape = None
            ensure_shape_similarity = False
        yield first_sample
    except StopIteration:
        raise ValueError(
            "Received an empty dataset. Argument `dataset` must "
            "be a non-empty list/tuple of `numpy.ndarray` objects "
            "or `tf.data.Dataset` objects."
        )

    for i, sample in enumerate(dataset_iterator):
        if ensure_shape_similarity:
            if first_sample_shape != np.array(sample).shape:
                raise ValueError(
                    "All `dataset` samples must have same shape, "
                    f"Expected shape: {np.array(first_sample).shape} "
                    f"Received shape: {np.array(sample).shape} at index "
                    f"{i}."
                )
        if data_size_warning_flag:
            if i % 10 == 0:
                cur_time = time.time()
                
                if int(cur_time - start_time) > 10 and data_size_warning_flag:
                    warnings.warn(
                        "The dataset is taking longer than 10 seconds to "
                        "iterate over. This may be due to the size of the "
                        "dataset. Keep in mind that the `split_dataset` "
                        "utility is only for small in-memory dataset "
                        "(e.g. < 10,000 samples).",
                        category=ResourceWarning,
                        source="split_dataset",
                    )
                    data_size_warning_flag = False
        yield sample


def is_torch_tensor(value):
    if hasattr(value, "__class__"):
        for parent in value.__class__.__mro__:
            if parent.__name__ == "Tensor" and str(parent.__module__).endswith(
                "torch"
            ):
                return True
    return False


def is_torch_dataset(dataset):
    if hasattr(dataset, "__class__"):
        for parent in dataset.__class__.__mro__:
            if parent.__name__ == "Dataset" and str(
                parent.__module__
            ).startswith("torch.utils.data"):
                return True
    return False


def _rescale_dataset_split_sizes(left_size, right_size, total_length):
    
    left_size_type = type(left_size)
    right_size_type = type(right_size)

    
    if (left_size is not None and left_size_type not in [int, float]) and (
        right_size is not None and right_size_type not in [int, float]
    ):
        raise TypeError(
            "Invalid `left_size` and `right_size` Types. Expected: "
            "integer or float or None, Received: type(left_size)="
            f"{left_size_type} and type(right_size)={right_size_type}"
        )

    
    if left_size is not None and left_size_type not in [int, float]:
        raise TypeError(
            "Invalid `left_size` Type. Expected: int or float or None, "
            f"Received: type(left_size)={left_size_type}.  "
        )

    
    if right_size is not None and right_size_type not in [int, float]:
        raise TypeError(
            "Invalid `right_size` Type. "
            "Expected: int or float or None,"
            f"Received: type(right_size)={right_size_type}."
        )

    
    if left_size == 0 and right_size == 0:
        raise ValueError(
            "Both `left_size` and `right_size` are zero. "
            "At least one of the split sizes must be non-zero."
        )

    
    if (
        left_size_type == int
        and (left_size <= 0 or left_size >= total_length)
        or left_size_type == float
        and (left_size <= 0 or left_size >= 1)
    ):
        raise ValueError(
            "`left_size` should be either a positive integer "
            f"smaller than {total_length}, or a float "
            "within the range `[0, 1]`. Received: left_size="
            f"{left_size}"
        )

    
    
    if (
        right_size_type == int
        and (right_size <= 0 or right_size >= total_length)
        or right_size_type == float
        and (right_size <= 0 or right_size >= 1)
    ):
        raise ValueError(
            "`right_size` should be either a positive integer "
            f"and smaller than {total_length} or a float "
            "within the range `[0, 1]`. Received: right_size="
            f"{right_size}"
        )

    
    
    if (
        right_size_type == left_size_type == float
        and right_size + left_size > 1
    ):
        raise ValueError(
            "The sum of `left_size` and `right_size` is greater "
            "than 1. It must be less than or equal to 1."
        )

    if left_size_type == float:
        left_size = round(left_size * total_length)
    elif left_size_type == int:
        left_size = float(left_size)

    if right_size_type == float:
        right_size = round(right_size * total_length)
    elif right_size_type == int:
        right_size = float(right_size)

    if left_size is None:
        left_size = total_length - right_size
    elif right_size is None:
        right_size = total_length - left_size

    if left_size + right_size > total_length:
        raise ValueError(
            "The sum of `left_size` and `right_size` should "
            "be smaller than the {total_length}. "
            f"Received: left_size + right_size = {left_size+right_size}"
            f"and total_length = {total_length}"
        )

    for split, side in [(left_size, "left"), (right_size, "right")]:
        if split == 0:
            raise ValueError(
                f"With `dataset` of length={total_length}, `left_size`="
                f"{left_size} and `right_size`={right_size}."
                f"Resulting {side} side dataset split will be empty. "
                "Adjust any of the aforementioned parameters"
            )

    left_size, right_size = int(left_size), int(right_size)
    return left_size, right_size


def _restore_dataset_from_list(
    dataset_as_list, dataset_type_spec, original_dataset
):
    
    if dataset_type_spec in [tuple, list]:
        return tuple(np.array(sample) for sample in zip(*dataset_as_list))
    elif dataset_type_spec == tf.data.Dataset:
        if isinstance(original_dataset.element_spec, dict):
            restored_dataset = {}
            for d in dataset_as_list:
                for k, v in d.items():
                    if k not in restored_dataset:
                        restored_dataset[k] = [v]
                    else:
                        restored_dataset[k].append(v)
            return restored_dataset
        else:
            return tuple(np.array(sample) for sample in zip(*dataset_as_list))

    elif is_torch_dataset(original_dataset):
        return tuple(np.array(sample) for sample in zip(*dataset_as_list))
    return dataset_as_list


def is_batched(dataset):
    
    return hasattr(dataset, "_batch_size")


def get_batch_size(dataset):
    
    if is_batched(dataset):
        return dataset._batch_size
    else:
        return None


def _get_type_spec(dataset):
    
    if isinstance(dataset, tuple):
        return tuple
    elif isinstance(dataset, list):
        return list
    elif isinstance(dataset, np.ndarray):
        return np.ndarray
    elif isinstance(dataset, dict):
        return dict
    elif isinstance(dataset, tf.data.Dataset):
        return tf.data.Dataset
    elif is_torch_dataset(dataset):
        from torch.utils.data import Dataset as torchDataset

        return torchDataset
    else:
        return None


def index_directory(
    directory,
    labels,
    formats,
    class_names=None,
    shuffle=True,
    seed=None,
    follow_links=False,
):
    
    if labels == "inferred":
        subdirs = []
        for subdir in sorted(tf.io.gfile.listdir(directory)):
            if tf.io.gfile.isdir(tf.io.gfile.join(directory, subdir)):
                if not subdir.startswith("."):
                    if subdir.endswith("/"):
                        subdir = subdir[:-1]
                    subdirs.append(subdir)
        if class_names is not None:
            if not set(class_names).issubset(set(subdirs)):
                raise ValueError(
                    "The `class_names` passed did not match the "
                    "names of the subdirectories of the target directory. "
                    f"Expected: {subdirs} (or a subset of it), "
                    f"but received: class_names={class_names}"
                )
            subdirs = class_names  
    else:
        
        subdirs = [""]
        if class_names is not None:
            if labels is None:
                raise ValueError(
                    "When `labels=None` (no labels), argument `class_names` "
                    "cannot be specified."
                )
            else:
                raise ValueError(
                    "When argument `labels` is specified, argument "
                    "`class_names` cannot be specified (the `class_names` "
                    "will be the sorted list of labels)."
                )
    class_names = subdirs
    class_indices = dict(zip(class_names, range(len(class_names))))

    
    
    pool = ThreadPool()
    results = []
    filenames = []

    for dirpath in (tf.io.gfile.join(directory, subdir) for subdir in subdirs):
        results.append(
            pool.apply_async(
                index_subdirectory,
                (dirpath, class_indices, follow_links, formats),
            )
        )
    labels_list = []
    for res in results:
        partial_filenames, partial_labels = res.get()
        labels_list.append(partial_labels)
        filenames += partial_filenames

    if labels == "inferred":
        
        i = 0
        labels = np.zeros((len(filenames),), dtype="int32")
        for partial_labels in labels_list:
            labels[i : i + len(partial_labels)] = partial_labels
            i += len(partial_labels)
    elif labels is None:
        class_names = None
    else:
        
        if len(labels) != len(filenames):
            raise ValueError(
                "Expected the lengths of `labels` to match the number "
                "of files in the target directory. len(labels) is "
                f"{len(labels)} while we found {len(filenames)} files "
                f"in directory {directory}."
            )
        class_names = [str(label) for label in sorted(set(labels))]

    if labels is None:
        io_utils.print_msg(f"Found {len(filenames)} files.")
    else:
        io_utils.print_msg(
            f"Found {len(filenames)} files belonging "
            f"to {len(class_names)} classes."
        )
    pool.close()
    pool.join()
    file_paths = [tf.io.gfile.join(directory, fname) for fname in filenames]

    if shuffle:
        
        if seed is None:
            seed = np.random.randint(1e6)
        rng = np.random.RandomState(seed)
        rng.shuffle(file_paths)
        if labels is not None:
            rng = np.random.RandomState(seed)
            rng.shuffle(labels)
    return file_paths, labels, class_names


def iter_valid_files(directory, follow_links, formats):
    if not follow_links:
        walk = tf.io.gfile.walk(directory)
    else:
        walk = os.walk(directory, followlinks=follow_links)
    for root, _, files in sorted(walk, key=lambda x: x[0]):
        for fname in sorted(files):
            if fname.lower().endswith(formats):
                yield root, fname


def index_subdirectory(directory, class_indices, follow_links, formats):
    
    dirname = os.path.basename(directory)
    valid_files = iter_valid_files(directory, follow_links, formats)
    labels = []
    filenames = []
    for root, fname in valid_files:
        labels.append(class_indices[dirname])
        absolute_path = tf.io.gfile.join(root, fname)
        relative_path = tf.io.gfile.join(
            dirname, os.path.relpath(absolute_path, directory)
        )
        filenames.append(relative_path)
    return filenames, labels


def get_training_or_validation_split(samples, labels, validation_split, subset):
    
    if not validation_split:
        return samples, labels

    num_val_samples = int(validation_split * len(samples))
    if subset == "training":
        io_utils.print_msg(
            f"Using {len(samples) - num_val_samples} " f"files for training."
        )
        samples = samples[:-num_val_samples]
        if labels is not None:
            labels = labels[:-num_val_samples]
    elif subset == "validation":
        io_utils.print_msg(f"Using {num_val_samples} files for validation.")
        samples = samples[-num_val_samples:]
        if labels is not None:
            labels = labels[-num_val_samples:]
    else:
        raise ValueError(
            '`subset` must be either "training" '
            f'or "validation", received: {subset}'
        )
    return samples, labels


def labels_to_dataset(labels, label_mode, num_classes):
    
    label_ds = tf.data.Dataset.from_tensor_slices(labels)
    if label_mode == "binary":
        label_ds = label_ds.map(
            lambda x: tf.expand_dims(tf.cast(x, "float32"), axis=-1),
            num_parallel_calls=tf.data.AUTOTUNE,
        )
    elif label_mode == "categorical":
        label_ds = label_ds.map(
            lambda x: tf.one_hot(x, num_classes),
            num_parallel_calls=tf.data.AUTOTUNE,
        )
    return label_ds


def check_validation_split_arg(validation_split, subset, shuffle, seed):
    
    if validation_split and not 0 < validation_split < 1:
        raise ValueError(
            "`validation_split` must be between 0 and 1, "
            f"received: {validation_split}"
        )
    if (validation_split or subset) and not (validation_split and subset):
        raise ValueError(
            "If `subset` is set, `validation_split` must be set, and inversely."
        )
    if subset not in ("training", "validation", "both", None):
        raise ValueError(
            '`subset` must be either "training", '
            f'"validation" or "both", received: {subset}'
        )
    if validation_split and shuffle and seed is None:
        raise ValueError(
            "If using `validation_split` and shuffling the data, you must "
            "provide a `seed` argument, to make sure that there is no "
            "overlap between the training and validation subset."
        )