Skip to content

Module

build_xy(attributes, rows, target_names)

Source code in src/qualities/module.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
def build_xy(
    attributes,
    rows,
    target_names: set[str],
) -> tuple[np.ndarray, np.ndarray]:
    attr_names = [a[0] for a in attributes]

    target_idx = find_target_index(attributes, target_names)
    if target_idx is None:
        raise ValueError(
            f"Target feature not found among dataset attributes "
            f"(default_target_attribute={target_names!r})."
        )

    arr = np.array(rows, dtype=object)

    feature_idxs = [i for i in range(len(attr_names)) if i != target_idx]

    X_full = pd.DataFrame({attr_names[i]: arr[:, i] for i in feature_idxs})
    y_raw = arr[:, target_idx]

    if _numeric_column(y_raw):
        y = np.asarray(
            [np.nan if v is None else float(v) for v in y_raw]
        )
    else:
        y = pd.Categorical(y_raw).codes.astype(float)

    string_cols = X_full.select_dtypes(
        include=["object", "string"],
    ).columns
    multi_word_cols = [
        c
        for c in string_cols
        if X_full[c].dropna().astype(str).str.contains(r"\s").any()
    ]
    X_clean = X_full.drop(columns=multi_word_cols)

    for col in X_clean.select_dtypes(
        include=["object", "string"],
    ).columns:
        values = X_full[col].tolist()
        if _numeric_column(values):
            X_clean[col] = [
                np.nan if v is None else float(v) for v in values
            ]
        else:
            X_clean[col] = pd.Categorical(
                X_full[col],
            ).codes.astype(float)

    return X_clean.to_numpy(dtype=float), y

compute_dataset_qualities(attributes, rows, target_names)

Source code in src/qualities/module.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def compute_dataset_qualities(
    attributes,
    rows,
    target_names: set[str],
) -> list[Quality]:
    attr_types = [a[1] for a in attributes]

    target_idx = find_target_index(attributes, target_names)

    n_instances = len(rows)
    n_features = len(attributes)

    target_type_spec = attr_types[target_idx] if target_idx is not None else None
    target_is_numeric = isinstance(target_type_spec, str) and (
        target_type_spec.upper() in NUMERIC_TYPES
    )

    qualities: list[Quality] = []

    def add(name: str, value: float | None) -> None:
        qualities.append(Quality(name=name, value=value))

    # --- Counts / dimensions ---
    add("NumberOfInstances", float(n_instances))
    add("NumberOfFeatures", float(n_features))

    if target_idx is None or target_is_numeric:
        add("NumberOfClasses", None)
    else:
        target_col = (row[target_idx] for row in rows)
        distinct = {v for v in target_col if v is not None}
        add("NumberOfClasses", float(len(distinct)))

    add(
        "Dimensionality",
        n_features / n_instances if n_instances else None,
    )

    # --- Missing values ---
    n_missing = 0
    rows_with_missing = 0
    for row in rows:
        row_missing = sum(1 for v in row if v is None)
        n_missing += row_missing
        if row_missing:
            rows_with_missing += 1

    add(
        "NumberOfInstancesWithMissingValues",
        float(rows_with_missing),
    )
    add("NumberOfMissingValues", float(n_missing))
    add(
        "PercentageOfInstancesWithMissingValues",
        _pct(rows_with_missing, n_instances),
    )
    add(
        "PercentageOfMissingValues",
        _pct(n_missing, n_instances * n_features),
    )

    # --- Feature types ---
    n_numeric = 0
    n_symbolic = 0
    n_binary = 0
    for i, type_spec in enumerate(attr_types):
        if isinstance(type_spec, list):
            n_symbolic += 1
            if len(type_spec) == 2:
                n_binary += 1
        elif (
            isinstance(
                type_spec,
                str,
            )
            and type_spec.upper() in NUMERIC_TYPES
        ):
            n_numeric += 1
            col = (row[i] for row in rows)
            if len({v for v in col if v is not None}) == 2:
                n_binary += 1

    add("NumberOfNumericFeatures", float(n_numeric))
    add("NumberOfSymbolicFeatures", float(n_symbolic))
    add("NumberOfBinaryFeatures", float(n_binary))
    add(
        "PercentageOfNumericFeatures",
        _pct(n_numeric, n_features),
    )
    add(
        "PercentageOfSymbolicFeatures",
        _pct(n_symbolic, n_features),
    )
    add(
        "PercentageOfBinaryFeatures",
        _pct(n_binary, n_features),
    )

    # --- Class distribution ---
    if target_idx is None or target_is_numeric:
        add("MajorityClassSize", None)
        add("MinorityClassSize", None)
        add("MajorityClassPercentage", None)
        add("MinorityClassPercentage", None)
    else:
        target_col = (row[target_idx] for row in rows)
        counts = Counter(v for v in target_col if v is not None)
        if counts:
            total = sum(counts.values())
            majority = max(counts.values())
            minority = min(counts.values())
            add("MajorityClassSize", float(majority))
            add("MinorityClassSize", float(minority))
            add(
                "MajorityClassPercentage",
                majority / total * 100,
            )
            add(
                "MinorityClassPercentage",
                minority / total * 100,
            )
        else:
            add("MajorityClassSize", None)
            add("MinorityClassSize", None)
            add("MajorityClassPercentage", None)
            add("MinorityClassPercentage", None)

    add(
        "AutoCorrelation",
        _autocorrelation(rows, target_idx, target_is_numeric, n_instances),
    )

    return qualities

find_target_index(attributes, target_names)

Index of the first attribute whose name is in target_names.

None means the dataset has no usable target: either no default_target_attribute was set, or its name(s) match no attribute. Callers use this to decide up front whether supervised extraction (pymfe, landmarkers) is possible at all.

Source code in src/qualities/module.py
15
16
17
18
19
20
21
22
23
24
25
def find_target_index(attributes, target_names: set[str]) -> int | None:
    """Index of the first attribute whose name is in ``target_names``.

    ``None`` means the dataset has no usable target: either no
    ``default_target_attribute`` was set, or its name(s) match no attribute.
    Callers use this to decide up front whether supervised extraction
    (pymfe, landmarkers) is possible at all.
    """
    attr_names = [a[0] for a in attributes]
    target_idxs = [i for i, n in enumerate(attr_names) if n in target_names]
    return target_idxs[0] if target_idxs else None