-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathmetrics_calculator.py
More file actions
187 lines (160 loc) · 5.67 KB
/
Copy pathmetrics_calculator.py
File metadata and controls
187 lines (160 loc) · 5.67 KB
1
2
3
4
5
6
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
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import logging
import math
from typing import Dict, List, Optional, Tuple
import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
from feast.types import PrimitiveFeastType
logger = logging.getLogger(__name__)
def _safe_float(val):
"""Return None for None/NaN/Inf, otherwise float."""
if val is None:
return None
f = float(val)
if math.isnan(f) or math.isinf(f):
return None
return f
_NUMERIC_TYPES = {
PrimitiveFeastType.INT32,
PrimitiveFeastType.INT64,
PrimitiveFeastType.FLOAT32,
PrimitiveFeastType.FLOAT64,
PrimitiveFeastType.DECIMAL,
}
_CATEGORICAL_TYPES = {
PrimitiveFeastType.STRING,
PrimitiveFeastType.BOOL,
}
class MetricsCalculator:
def __init__(self, histogram_bins: int = 20, top_n: int = 10):
self.histogram_bins = histogram_bins
self.top_n = top_n
@staticmethod
def classify_feature(dtype) -> Optional[str]:
primitive = dtype
if hasattr(dtype, "base_type"):
primitive = dtype.base_type if dtype.base_type else dtype
if isinstance(primitive, PrimitiveFeastType):
if primitive in _NUMERIC_TYPES:
return "numeric"
if primitive in _CATEGORICAL_TYPES:
return "categorical"
return None
@staticmethod
def classify_feature_arrow(arrow_type: pa.DataType) -> Optional[str]:
"""Classify a PyArrow data type as numeric or categorical."""
if (
pa.types.is_integer(arrow_type)
or pa.types.is_floating(arrow_type)
or pa.types.is_decimal(arrow_type)
):
return "numeric"
if (
pa.types.is_string(arrow_type)
or pa.types.is_large_string(arrow_type)
or pa.types.is_boolean(arrow_type)
):
return "categorical"
return None
def compute_numeric(self, array: pa.Array) -> Dict:
total = len(array)
null_count = array.null_count
result = {
"feature_type": "numeric",
"row_count": total,
"null_count": null_count,
"null_rate": null_count / total if total > 0 else 0.0,
"mean": None,
"stddev": None,
"min_val": None,
"max_val": None,
"p50": None,
"p75": None,
"p90": None,
"p95": None,
"p99": None,
"histogram": None,
}
valid = pc.drop_null(array) # type: ignore[attr-defined]
if len(valid) == 0:
return result
float_array = pc.cast(valid, pa.float64())
result["mean"] = _safe_float(pc.mean(float_array).as_py()) # type: ignore[attr-defined]
result["stddev"] = _safe_float(pc.stddev(float_array, ddof=1).as_py()) # type: ignore[attr-defined]
min_max = pc.min_max(float_array) # type: ignore[attr-defined]
result["min_val"] = min_max["min"].as_py()
result["max_val"] = min_max["max"].as_py()
quantiles = pc.quantile(float_array, q=[0.50, 0.75, 0.90, 0.95, 0.99]) # type: ignore[attr-defined]
q_values = quantiles.to_pylist()
result["p50"] = q_values[0]
result["p75"] = q_values[1]
result["p90"] = q_values[2]
result["p95"] = q_values[3]
result["p99"] = q_values[4]
np_array = float_array.to_numpy()
counts, bin_edges = np.histogram(np_array, bins=self.histogram_bins)
result["histogram"] = {
"bins": bin_edges.tolist(),
"counts": counts.tolist(),
"bin_width": float(bin_edges[1] - bin_edges[0])
if len(bin_edges) > 1
else 0,
}
return result
def compute_categorical(self, array: pa.Array) -> Dict:
total = len(array)
null_count = array.null_count
result = {
"feature_type": "categorical",
"row_count": total,
"null_count": null_count,
"null_rate": null_count / total if total > 0 else 0.0,
"mean": None,
"stddev": None,
"min_val": None,
"max_val": None,
"p50": None,
"p75": None,
"p90": None,
"p95": None,
"p99": None,
"histogram": None,
}
valid = pc.drop_null(array) # type: ignore[attr-defined]
if len(valid) == 0:
return result
value_counts = pc.value_counts(valid) # type: ignore[attr-defined]
entries = [
{"value": vc["values"].as_py(), "count": vc["counts"].as_py()}
for vc in value_counts
]
entries.sort(key=lambda x: x["count"], reverse=True)
unique_count = len(entries)
top_entries = entries[: self.top_n]
other_count = sum(e["count"] for e in entries[self.top_n :])
result["histogram"] = {
"values": top_entries,
"other_count": other_count,
"unique_count": unique_count,
}
return result
def compute_all(
self,
table: pa.Table,
feature_fields: List[Tuple[str, str]],
) -> List[Dict]:
results = []
for name, ftype in feature_fields:
if name not in table.column_names:
logger.warning("Column '%s' not found in arrow table, skipping", name)
continue
column = table.column(name)
if ftype == "numeric":
metrics = self.compute_numeric(column)
elif ftype == "categorical":
metrics = self.compute_categorical(column)
else:
continue
metrics["feature_name"] = name
results.append(metrics)
return results