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 Examples: 1. Try to train when x & y are of same len
(self, x, y)
| 43 | return np.mean((labels - prediction) ** 2) |
| 44 | |
| 45 | def train(self, x, y): |
| 46 | """ |
| 47 | train: |
| 48 | @param x: a one-dimensional numpy array |
| 49 | @param y: a one-dimensional numpy array. |
| 50 | The contents of y are the labels for the corresponding X values |
| 51 | |
| 52 | train() does not have a return value |
| 53 | |
| 54 | Examples: |
| 55 | 1. Try to train when x & y are of same length & 1 dimensions (No errors) |
| 56 | >>> dt = DecisionTree() |
| 57 | >>> dt.train(np.array([10,20,30,40,50]),np.array([0,0,0,1,1])) |
| 58 | |
| 59 | 2. Try to train when x is 2 dimensions |
| 60 | >>> dt = DecisionTree() |
| 61 | >>> dt.train(np.array([[1,2,3,4,5],[1,2,3,4,5]]),np.array([0,0,0,1,1])) |
| 62 | Traceback (most recent call last): |
| 63 | ... |
| 64 | ValueError: Input data set must be one-dimensional |
| 65 | |
| 66 | 3. Try to train when x and y are not of the same length |
| 67 | >>> dt = DecisionTree() |
| 68 | >>> dt.train(np.array([1,2,3,4,5]),np.array([[0,0,0,1,1],[0,0,0,1,1]])) |
| 69 | Traceback (most recent call last): |
| 70 | ... |
| 71 | ValueError: x and y have different lengths |
| 72 | |
| 73 | 4. Try to train when x & y are of the same length but different dimensions |
| 74 | >>> dt = DecisionTree() |
| 75 | >>> dt.train(np.array([1,2,3,4,5]),np.array([[1],[2],[3],[4],[5]])) |
| 76 | Traceback (most recent call last): |
| 77 | ... |
| 78 | ValueError: Data set labels must be one-dimensional |
| 79 | |
| 80 | This section is to check that the inputs conform to our dimensionality |
| 81 | constraints |
| 82 | """ |
| 83 | if x.ndim != 1: |
| 84 | raise ValueError("Input data set must be one-dimensional") |
| 85 | if len(x) != len(y): |
| 86 | raise ValueError("x and y have different lengths") |
| 87 | if y.ndim != 1: |
| 88 | raise ValueError("Data set labels must be one-dimensional") |
| 89 | |
| 90 | if len(x) < 2 * self.min_leaf_size: |
| 91 | self.prediction = np.mean(y) |
| 92 | return |
| 93 | |
| 94 | if self.depth == 1: |
| 95 | self.prediction = np.mean(y) |
| 96 | return |
| 97 | |
| 98 | best_split = 0 |
| 99 | min_error = self.mean_squared_error(x, np.mean(y)) * 2 |
| 100 | |
| 101 | """ |
| 102 | loop over all possible splits for the decision tree. find the best split. |
no test coverage detected