/
ml_problem_example.py
234 lines (175 loc) · 6.92 KB
/
ml_problem_example.py
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
from typing import Sequence
import numpy as np
import pandas as pd
import pandas.api.types as pdt
import visions
from visions.relations import IdentityRelation, TypeRelation
from visions.typesets.typeset import get_type_from_path
class Nominal(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(Categorical)]
@classmethod
def contains_op(cls, series: pd.Series, state: dict) -> bool:
return not pdt.is_categorical_dtype(series) or (
pdt.is_categorical_dtype(series) and not series.cat.ordered
)
class Categorical(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
# This example could be extended to show how low-cardinality discrete variables would be
# inferred to nominal / ordinal. This can be achieved with an InferenceRelation.
return [IdentityRelation(visions.Generic)]
@classmethod
def contains_op(cls, series: pd.Series, state: dict) -> bool:
return pdt.is_object_dtype(series)
class Binary(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(Nominal)]
@classmethod
def contains_op(cls, series: pd.Series, state: dict) -> bool:
state["n_distinct"] = state.get("n_distinct") or series.nunique()
return state["n_distinct"] == 2
class Ordinal(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(Categorical)]
@classmethod
def contains_op(cls, series: pd.Series, state: dict) -> bool:
return pdt.is_categorical_dtype(series) and series.cat.ordered
class Numeric(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(visions.Generic)]
@classmethod
def contains_op(cls, series: pd.Series, state: dict) -> bool:
return pdt.is_numeric_dtype(series)
class Continuous(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(Numeric)]
@classmethod
def contains_op(cls, series: pd.Series, state: dict) -> bool:
return not pdt.is_integer_dtype(series)
class Discrete(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(Numeric)]
@classmethod
def contains_op(cls, series: pd.Series, state: dict) -> bool:
return pdt.is_integer_dtype(series)
class VariableTypeset(visions.VisionsTypeset):
def __init__(self):
types = {
visions.Generic,
Categorical,
Nominal,
Ordinal,
Numeric,
Continuous,
Discrete,
Binary,
}
super().__init__(types)
variable_set = VariableTypeset()
variable_set.output_graph("variable_set.pdf")
class Classification(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(visions.Generic)]
@classmethod
def contains_op(cls, series, state):
state["dtype"] = state.get("dtype") or variable_set.detect_type(series)
return state["dtype"] in [Nominal, Categorical, Ordinal, Binary]
class BinaryClassification(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(Classification)]
@classmethod
def contains_op(cls, series, state):
state["dtype"] = state.get("dtype") or variable_set.detect_type(series)
return state["dtype"] == Binary
class MultiClassification(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(Classification)]
@classmethod
def contains_op(cls, series, state):
state["dtype"] = state.get("dtype") or variable_set.detect_type(series)
return state["dtype"] != Binary
class Regression(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(visions.Generic)]
@classmethod
def contains_op(cls, series, state):
state["dtype"] = state.get("dtype") or variable_set.detect_type(series)
return state["dtype"] in [Continuous, Discrete]
class PoissonRegression(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(Regression)]
@classmethod
def contains_op(cls, series, state):
state["dtype"] = state.get("dtype") or variable_set.detect_type(series)
if not state["dtype"] == Discrete:
return False
# This is a simplified test if poisson regression applies that doesn't take into account if
# the ratio is significant
state["mean_var_ratio"] = state.get("mean_var_rate") or np.mean(
series
) / np.var(series)
return np.isclose(state["mean_var_ratio"], 1, rtol=0.05)
class NegBinomRegression(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(Regression)]
@classmethod
def contains_op(cls, series, state):
state["dtype"] = state.get("dtype") or variable_set.detect_type(series)
if not state["dtype"] == Discrete:
return False
# See comment at poisson regression
state["mean_var_ratio"] = state.get("mean_var_rate") or np.mean(
series
) / np.var(series)
return state["mean_var_ratio"] > 1.05
class OrdinalRegression(visions.VisionsBaseType):
@staticmethod
def get_relations() -> Sequence[TypeRelation]:
return [IdentityRelation(Classification)]
@classmethod
def contains_op(cls, series, state):
state["dtype"] = state.get("dtype") or variable_set.detect_type(series)
return state["dtype"] == Ordinal
class MLProblemTypeset(visions.VisionsTypeset):
def __init__(self):
types = {
visions.Generic,
Classification,
BinaryClassification,
MultiClassification,
Regression,
NegBinomRegression,
PoissonRegression,
OrdinalRegression,
}
super().__init__(types)
problem_set = MLProblemTypeset()
problem_set.output_graph("problem_set.pdf")
# Example
dataset = pd.DataFrame(
{
"target_3": ["cat", "dog", "dog", "cat", "horse"],
"target_2": ["cat", "dog", "dog", "cat", "dog"],
"target_num": [1, 2, 2, 1, 2],
}
)
for target in dataset.columns:
_, problem_types, state = problem_set.detect(dataset[target])
problem_type = get_type_from_path(problem_types)
print(
f"The target variable '{target}' is of the {state['dtype']} statistical type."
)
print(f"Our logic found that a {problem_type} model should be used.")