-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingle_split.py
More file actions
54 lines (36 loc) · 1.33 KB
/
single_split.py
File metadata and controls
54 lines (36 loc) · 1.33 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
import numpy as np
def mse(y: np.ndarray) -> float:
"""Calculate the MSE of a vector"""
mse = np.mean((y - np.mean(y)) ** 2)
return mse
def weighted_mse(y_left: np.ndarray, y_right: np.ndarray) -> float:
"""Calculate the weighted MSE of two vectors."""
mse_left = mse(y_left)
mse_right = mse(y_right)
N_left = y_left.size
N_right = y_right.size
mse_weighted = ((mse_left * N_left) + (mse_right * N_right)) / (N_left + N_right)
return mse_weighted
def split(X: np.ndarray, y: np.ndarray, feature: int) -> float:
"""Find the best split for a node (one feature)"""
# iterate through all values of the feature
thresholds = np.unique(X[:, feature])
best_threshold = None
best_mse = mse(y)
if y.size < 2:
return best_threshold
for threshold in thresholds:
# split the data
left_mask = X[:, feature] <= threshold
right_mask = X[:, feature] > threshold
y_left = y[left_mask]
y_right = y[right_mask]
if y_left.size == 0 or y_right.size == 0:
continue
# calculate the weighted mse
mse_weighted = (weighted_mse(y_left, y_right))
# update best threshold
if mse_weighted < best_mse:
best_mse = mse_weighted
best_threshold = threshold
return best_threshold