MCPcopy Create free account
hub / github.com/subbarayudu-j/TheAlgorithms-Python / train

Method train

machine_learning/decision_tree.py:31–98  ·  view source on GitHub ↗

train: @param X: a one dimensional numpy array @param y: a one dimensional numpy array. The contents of y are the labels for the corresponding X values train does not have a return value

(self, X, y)

Source from the content-addressed store, hash-verified

29 return np.mean((labels - prediction) ** 2)
30
31 def train(self, X, y):
32 """
33 train:
34 @param X: a one dimensional numpy array
35 @param y: a one dimensional numpy array.
36 The contents of y are the labels for the corresponding X values
37
38 train does not have a return value
39 """
40
41 """
42 this section is to check that the inputs conform to our dimensionality constraints
43 """
44 if X.ndim != 1:
45 print("Error: Input data set must be one dimensional")
46 return
47 if len(X) != len(y):
48 print("Error: X and y have different lengths")
49 return
50 if y.ndim != 1:
51 print("Error: Data set labels must be one dimensional")
52 return
53
54 if len(X) < 2 * self.min_leaf_size:
55 self.prediction = np.mean(y)
56 return
57
58 if self.depth == 1:
59 self.prediction = np.mean(y)
60 return
61
62 best_split = 0
63 min_error = self.mean_squared_error(X,np.mean(y)) * 2
64
65
66 """
67 loop over all possible splits for the decision tree. find the best split.
68 if no split exists that is less than 2 * error for the entire array
69 then the data set is not split and the average for the entire array is used as the predictor
70 """
71 for i in range(len(X)):
72 if len(X[:i]) < self.min_leaf_size:
73 continue
74 elif len(X[i:]) < self.min_leaf_size:
75 continue
76 else:
77 error_left = self.mean_squared_error(X[:i], np.mean(y[:i]))
78 error_right = self.mean_squared_error(X[i:], np.mean(y[i:]))
79 error = error_left + error_right
80 if error < min_error:
81 best_split = i
82 min_error = error
83
84 if best_split != 0:
85 left_X = X[:best_split]
86 left_y = y[:best_split]
87 right_X = X[best_split:]
88 right_y = y[best_split:]

Callers 1

mainFunction · 0.95

Calls 2

mean_squared_errorMethod · 0.95
Decision_TreeClass · 0.85

Tested by

no test coverage detected