Skip to content

tabular_data

preprocess_inputs(generate_func)

Validates and converts X for tabular data generators.

Preprocessing: X is converted to a 2D numpy array.

Source code in badgers/core/decorators/tabular_data.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def preprocess_inputs(generate_func):
    """
    Validates and converts X for tabular data generators.

    Preprocessing:
    X is converted to a 2D numpy array.
    """

    @functools.wraps(generate_func)
    def wrapper(self, X, *args, **kwargs):
        # Validate and preprocess X
        if isinstance(X, list):
            X = np.array(X)
        elif isinstance(X, pd.DataFrame):
            X = X.values
        elif isinstance(X, pd.Series):
            X = X.values.reshape(-1, 1)
        elif isinstance(X, np.ndarray):
            pass
        else:
            raise ValueError(
                f"X must be a list, numpy array, pandas Series, or pandas DataFrame\n"
                f"X is: {type(X)}"
            )

        # Ensure X is writable: pandas 3.0 (Copy-on-Write) and some inputs
        # yield read-only arrays, but generators mutate X in place.
        if not X.flags.writeable:
            X = X.copy()

        # Validate dimensionality of X
        if X.ndim == 1:
            X = X.reshape(-1, 1)
        if X.ndim > 2:
            raise ValueError(
                "X has more than 2 dimensions where it is expected to have either 1 or 2!"
            )

        # Call the original function with the preprocessed input
        return generate_func(self, X, *args, **kwargs)

    return wrapper