| 8 | |
| 9 | |
| 10 | class DecisionTree: |
| 11 | def __init__(self, depth=5, min_leaf_size=5): |
| 12 | self.depth = depth |
| 13 | self.decision_boundary = 0 |
| 14 | self.left = None |
| 15 | self.right = None |
| 16 | self.min_leaf_size = min_leaf_size |
| 17 | self.prediction = None |
| 18 | |
| 19 | def mean_squared_error(self, labels, prediction): |
| 20 | """ |
| 21 | mean_squared_error: |
| 22 | @param labels: a one-dimensional numpy array |
| 23 | @param prediction: a floating point value |
| 24 | return value: mean_squared_error calculates the error if prediction is used to |
| 25 | estimate the labels |
| 26 | >>> tester = DecisionTree() |
| 27 | >>> test_labels = np.array([1,2,3,4,5,6,7,8,9,10]) |
| 28 | >>> test_prediction = float(6) |
| 29 | >>> bool(tester.mean_squared_error(test_labels, test_prediction) == ( |
| 30 | ... TestDecisionTree.helper_mean_squared_error_test(test_labels, |
| 31 | ... test_prediction))) |
| 32 | True |
| 33 | >>> test_labels = np.array([1,2,3]) |
| 34 | >>> test_prediction = float(2) |
| 35 | >>> bool(tester.mean_squared_error(test_labels, test_prediction) == ( |
| 36 | ... TestDecisionTree.helper_mean_squared_error_test(test_labels, |
| 37 | ... test_prediction))) |
| 38 | True |
| 39 | """ |
| 40 | if labels.ndim != 1: |
| 41 | print("Error: Input labels must be one dimensional") |
| 42 | |
| 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() |