Repository navigation
Expand file tree
/
Copy pathexperiment.py
More file actions
279 lines (225 loc) · 10.3 KB
/
Copy pathexperiment.py
File metadata and controls
279 lines (225 loc) · 10.3 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
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
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
268
269
270
271
272
273
274
275
276
277
278
279
import time
from typing import Tuple, Dict, List
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tree.base import DecisionTree
from metrics import *
np.random.seed(42)
num_average_time = 100
# Generating the random data
def make_data_discrete_features(N: int, M: int, K: int = 2) -> pd.DataFrame:
"""Generate binary (0/1) features with shape (N, M)."""
X = pd.DataFrame(np.random.randint(0, 2, size=(N, M)),
columns=[f"f{i}" for i in range(M)])
return X
def make_data_real_features(N: int, M: int) -> pd.DataFrame:
"""Generate real-valued features from N(0,1)."""
X = pd.DataFrame(np.random.randn(N, M),
columns=[f"x{i}" for i in range(M)])
return X
def make_targets_discrete_from_binary(X: pd.DataFrame, K: int = 2) -> pd.Series:
"""Generate classification labels from binary features."""
N, M = X.shape
w = np.array([2.0, -1.5, 1.0, 1.0, -0.5][:min(5, M)])
s = (X.iloc[:, :len(w)].values @ w)
if K == 2:
y = (s > np.median(s)).astype(int)
else:
qs = np.quantile(s, np.linspace(0, 1, K + 1))
y = np.digitize(s, qs[1:-1])
return pd.Series(y, dtype="category")
def make_targets_discrete_from_real(X: pd.DataFrame, K: int = 3) -> pd.Series:
"""Generate classification labels from real features."""
N, M = X.shape
w = np.random.randn(M)
s = X.values @ w + 0.25 * np.random.randn(N)
qs = np.quantile(s, np.linspace(0, 1, K + 1))
y = np.digitize(s, qs[1:-1])
return pd.Series(y, dtype="category")
def make_targets_real_from_binary(X: pd.DataFrame) -> pd.Series:
"""Generate regression targets from binary features."""
N, M = X.shape
w = np.array([1.5, -2.0, 0.75, 1.0, -0.5][:min(5, M)])
mu = (X.iloc[:, :len(w)].values @ w)
y = mu + 0.5 * np.random.randn(N)
return pd.Series(y.astype(float))
def make_targets_real_from_real(X: pd.DataFrame) -> pd.Series:
"""Generate regression targets from real features."""
N, M = X.shape
w = np.linspace(1, 2, M)
y = (X.values @ w) + 0.5 * np.random.randn(N)
return pd.Series(y.astype(float))
# Definig the timing utilities
def time_fit_predict(tree: DecisionTree, X_train: pd.DataFrame,
y_train: pd.Series, X_test: pd.DataFrame,
reps: int = 5) -> Tuple[float, float]:
"""Return average fit and predict time over `reps` runs."""
fit_times, pred_times = [], []
for _ in range(reps):
t0 = time.perf_counter()
tree.fit(X_train, y_train)
t1 = time.perf_counter()
_ = tree.predict(X_test)
t2 = time.perf_counter()
fit_times.append(t1 - t0)
pred_times.append(t2 - t1)
return float(np.mean(fit_times)), float(np.mean(pred_times))
def run_sweeps(N_list: List[int], M_list: List[int],
reps: int = 5, max_depth: int = 5) -> Dict[str, dict]:
"""
Run timing sweeps for all 4 cases:
A) discrete features, discrete output
B) discrete features, real output
C) real features, discrete output
D) real features, real output
"""
results = {"disc-disc": {}, "disc-real": {}, "real-disc": {}, "real-real": {}}
M_fixed = M_list[len(M_list)//2]
N_fixed = N_list[len(N_list)//2]
# Varying the samples N keeping the feature M fixed
def _do_case(case_name: str, makeX, makeY, criterion: str):
fitN, predN = [], []
for N in N_list:
X, y = makeX(N, M_fixed), makeY(makeX(N, M_fixed))
n_train = max(1, int(0.8 * N))
Xtr, Xte, ytr, yte = X.iloc[:n_train], X.iloc[n_train:], y.iloc[:n_train], y.iloc[n_train:]
tree = DecisionTree(criterion=criterion, max_depth=max_depth)
f, p = time_fit_predict(tree, Xtr, ytr, Xte, reps=reps)
fitN.append(f); predN.append(p)
# Varying the features M keeping the samples N fixed
fitM, predM = [], []
for M in M_list:
X, y = makeX(N_fixed, M), makeY(makeX(N_fixed, M))
n_train = max(1, int(0.8 * N_fixed))
Xtr, Xte, ytr, yte = X.iloc[:n_train], X.iloc[n_train:], y.iloc[:n_train], y.iloc[n_train:]
tree = DecisionTree(criterion=criterion, max_depth=max_depth)
f, p = time_fit_predict(tree, Xtr, ytr, Xte, reps=reps)
fitM.append(f); predM.append(p)
results[case_name]["vary_N"] = {"N": N_list, "fit": fitN, "pred": predN, "M_fixed": M_fixed}
results[case_name]["vary_M"] = {"M": M_list, "fit": fitM, "pred": predM, "N_fixed": N_fixed}
# Case 1: Discrete Input, Discrete Output
_do_case("disc-disc",
makeX=lambda N, M: make_data_discrete_features(N, M),
makeY=lambda X: make_targets_discrete_from_binary(X, K=2),
criterion="information_gain")
# Case 2: Discrete Input, Real Output
_do_case("disc-real",
makeX=lambda N, M: make_data_discrete_features(N, M),
makeY=make_targets_real_from_binary,
criterion="information_gain")
# Case 3: Real Input, Discrete Output
_do_case("real-disc",
makeX=lambda N, M: make_data_real_features(N, M),
makeY=lambda X: make_targets_discrete_from_real(X, K=3),
criterion="gini_index")
# Case 4: Real Input, Real Output
_do_case("real-real",
makeX=lambda N, M: make_data_real_features(N, M),
makeY=make_targets_real_from_real,
criterion="information_gain")
return results
# Plotting the time analysis data
def plot_times(results: Dict[str, dict], save_prefix: str = None):
"""Plot fit & predict times vs N and M for each case."""
# Varying the samples N
for case, bundle in results.items():
N, fit, pred, M_fixed = bundle["vary_N"]["N"], bundle["vary_N"]["fit"], bundle["vary_N"]["pred"], bundle["vary_N"]["M_fixed"]
plt.figure()
plt.plot(N, fit, marker="o", label="fit() time")
plt.plot(N, pred, marker="s", label="predict() time")
plt.xlabel("N (samples)")
plt.ylabel("time (seconds)")
plt.title(f"{case} | Vary N (M={M_fixed})")
plt.legend(); plt.grid(True)
if save_prefix:
plt.savefig(f"{save_prefix}_{case}_varyN.png", bbox_inches="tight", dpi=160)
plt.show()
# Varying the features M
M, fit, pred, N_fixed = bundle["vary_M"]["M"], bundle["vary_M"]["fit"], bundle["vary_M"]["pred"], bundle["vary_M"]["N_fixed"]
plt.figure()
plt.plot(M, fit, marker="o", label="fit() time")
plt.plot(M, pred, marker="s", label="predict() time")
plt.xlabel("M (features)")
plt.ylabel("time (seconds)")
plt.title(f"{case} | Vary M (N={N_fixed})")
plt.legend(); plt.grid(True)
if save_prefix:
plt.savefig(f"{save_prefix}_{case}_varyM.png", bbox_inches="tight", dpi=160)
plt.show()
def print_theory_cheatsheet():
"""Print standard time complexity formulas for decision trees."""
txt = """
== Theoretical Time Complexity (coarse) ==
Let N = samples, M = features, d = depth, and T = #nodes (~O(2^d) worst-case).
Training (per node):
• Discrete features: O(MN)
• Numeric features: O(M N log N)
Overall training:
• O(T * M N) (discrete)
• O(T * M N log N) (numeric)
Prediction:
• O(d) per sample → O(N_test * d)
Empirical expectation:
• fit() vs N: roughly linear (steeper for numeric features due to log N).
• fit() vs M: roughly linear.
• predict() vs N_test: linear; vs M: weak dependence.
"""
print(txt)
if __name__ == "__main__":
N_list = [200, 400, 800]
M_list = [4, 8, 16]
reps = 2
max_depth = 4
print_theory_cheatsheet()
def run_sweeps_fast(N_list, M_list, reps, max_depth):
results = {
"disc-disc": {}, "disc-real": {}, "real-disc": {}, "real-real": {}
}
M_fixed = M_list[len(M_list)//2]
N_fixed = N_list[len(N_list)//2]
def _do_case(tag, makeX, makeY, criterion):
print(f"\n== Running case: {tag} ==")
fitN, predN = [], []
for N in N_list:
print(f" vary N: N={N}, M={M_fixed}", flush=True)
X = makeX(N, M_fixed); y = makeY(X)
ntr = max(1, int(0.8*N))
Xtr, Xte = X.iloc[:ntr], X.iloc[ntr:]; ytr, yte = y.iloc[:ntr], y.iloc[ntr:]
tree = DecisionTree(criterion=criterion, max_depth=max_depth, one_hot_categoricals=False)
f, p = time_fit_predict(tree, Xtr, ytr, Xte, reps=reps)
fitN.append(f); predN.append(p)
fitM, predM = [], []
for M in M_list:
print(f" vary M: N={N_fixed}, M={M}", flush=True)
X = makeX(N_fixed, M); y = makeY(X)
ntr = max(1, int(0.8*N_fixed))
Xtr, Xte = X.iloc[:ntr], X.iloc[ntr:]; ytr, yte = y.iloc[:ntr], y.iloc[ntr:]
tree = DecisionTree(criterion=criterion, max_depth=max_depth, one_hot_categoricals=False)
f, p = time_fit_predict(tree, Xtr, ytr, Xte, reps=reps)
fitM.append(f); predM.append(p)
results[tag]["vary_N"] = {"N": N_list, "fit": fitN, "pred": predN, "M_fixed": M_fixed}
results[tag]["vary_M"] = {"M": M_list, "fit": fitM, "pred": predM, "N_fixed": N_fixed}
# Case 1: Discrete Input, Discrete Output
_do_case("disc-disc",
makeX=lambda N, M: make_data_discrete_features(N, M),
makeY=lambda X: make_targets_discrete_from_binary(X, K=2),
criterion="information_gain")
# Case 2: Discrete Input, Real Output
_do_case("disc-real",
makeX=lambda N, M: make_data_discrete_features(N, M),
makeY=make_targets_real_from_binary,
criterion="information_gain")
# Case 3: Real Input, Discrete Output
_do_case("real-disc",
makeX=lambda N, M: make_data_real_features(N, M),
makeY=lambda X: make_targets_discrete_from_real(X, K=3),
criterion="gini_index")
# Case 4: Real Input, Real Output
_do_case("real-real",
makeX=lambda N, M: make_data_real_features(N, M),
makeY=make_targets_real_from_real,
criterion="information_gain")
return results
results = run_sweeps_fast(N_list, M_list, reps=reps, max_depth=max_depth)
plot_times(results, save_prefix="dt_runtime_fast")