|
| 1 | +import pathlib |
| 2 | +from typing import AsyncIterator, Tuple, Any |
| 3 | + |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +from dffml import ( |
| 7 | + config, |
| 8 | + field, |
| 9 | + entrypoint, |
| 10 | + SimpleModel, |
| 11 | + ModelNotTrained, |
| 12 | + Accuracy, |
| 13 | + Feature, |
| 14 | + Features, |
| 15 | + Sources, |
| 16 | + Record, |
| 17 | +) |
| 18 | + |
| 19 | + |
| 20 | +@config |
| 21 | +class LogisticRegressionConfig: |
| 22 | + predict: Feature = field("Label or the value to be predicted") |
| 23 | + features: Features = field("Features to train on") |
| 24 | + directory: pathlib.Path = field( |
| 25 | + "Directory where state should be saved", |
| 26 | + default=pathlib.Path("~", ".cache", "dffml", "scratch"), |
| 27 | + ) |
| 28 | + |
| 29 | + |
| 30 | +@entrypoint("scratchlgr") |
| 31 | +class LogisticRegression(SimpleModel): |
| 32 | + |
| 33 | + # The configuration class needs to be set as the CONFIG property |
| 34 | + CONFIG = LogisticRegressionConfig |
| 35 | + # Logistic Regression only supports training on a single feature |
| 36 | + NUM_SUPPORTED_FEATURES = 1 |
| 37 | + # We only support single dimensional values, non-matrix / array |
| 38 | + SUPPORTED_LENGTHS = [1] |
| 39 | + |
| 40 | + def __init__(self, config): |
| 41 | + super().__init__(config) |
| 42 | + self.xData = np.array([]) |
| 43 | + self.yData = np.array([]) |
| 44 | + |
| 45 | + @property |
| 46 | + def separating_line(self): |
| 47 | + """ |
| 48 | + Load separating_line from disk, if it hasn't been set yet, return None |
| 49 | + """ |
| 50 | + return self.storage.get("separating_line", None) |
| 51 | + |
| 52 | + @separating_line.setter |
| 53 | + def separating_line(self, rline): |
| 54 | + """ |
| 55 | + Set separating_line in self.storage so it will be saved to disk |
| 56 | + """ |
| 57 | + self.storage["separating_line"] = rline |
| 58 | + |
| 59 | + def predict_input(self, x): |
| 60 | + """ |
| 61 | + Use the regression |
| 62 | + line to make a prediction by returning ``m * x + b``. |
| 63 | + """ |
| 64 | + prediction = self.separating_line[0] * x + self.separating_line[1] |
| 65 | + if prediction > 0.5: |
| 66 | + prediction = 1 |
| 67 | + else: |
| 68 | + prediction = 0 |
| 69 | + self.logger.debug( |
| 70 | + "Predicted Value of {} {}:".format( |
| 71 | + self.config.predict.NAME, prediction |
| 72 | + ) |
| 73 | + ) |
| 74 | + return prediction |
| 75 | + |
| 76 | + def best_fit_line(self): |
| 77 | + self.logger.debug( |
| 78 | + "Number of input records: {}".format(len(self.xData)) |
| 79 | + ) |
| 80 | + x = self.xData |
| 81 | + y = self.yData |
| 82 | + learning_rate = 0.01 |
| 83 | + w = 0.01 |
| 84 | + b = 0.0 |
| 85 | + for _ in range(1, 1500): |
| 86 | + z = w * x + b |
| 87 | + val = -np.multiply(y, z) |
| 88 | + num = -np.multiply(y, np.exp(val)) |
| 89 | + den = 1 + np.exp(val) |
| 90 | + f = num / den |
| 91 | + gradJ = np.sum(x * f) |
| 92 | + w = w - learning_rate * gradJ / len(x) |
| 93 | + error = 0 |
| 94 | + for x_id in range(len(x)): |
| 95 | + yhat = x[x_id] * w + b > 0.5 |
| 96 | + if yhat: |
| 97 | + yhat = 1 |
| 98 | + else: |
| 99 | + yhat = 0 |
| 100 | + if yhat != y[x_id]: |
| 101 | + error += 1 |
| 102 | + accuracy = 1 - (error / len(x)) |
| 103 | + return (w, b, accuracy) |
| 104 | + |
| 105 | + async def train(self, sources: Sources): |
| 106 | + async for record in sources.with_features( |
| 107 | + self.features + [self.config.predict.NAME] |
| 108 | + ): |
| 109 | + feature_data = record.features( |
| 110 | + self.features + [self.config.predict.NAME] |
| 111 | + ) |
| 112 | + self.xData = np.append(self.xData, feature_data[self.features[0]]) |
| 113 | + self.yData = np.append( |
| 114 | + self.yData, feature_data[self.config.predict.NAME] |
| 115 | + ) |
| 116 | + self.separating_line = self.best_fit_line() |
| 117 | + |
| 118 | + async def accuracy(self, sources: Sources) -> Accuracy: |
| 119 | + # Ensure the model has been trained before we try to make a prediction |
| 120 | + if self.separating_line is None: |
| 121 | + raise ModelNotTrained("Train model before assessing for accuracy.") |
| 122 | + accuracy_value = self.separating_line[2] |
| 123 | + return Accuracy(accuracy_value) |
| 124 | + |
| 125 | + async def predict( |
| 126 | + self, records: AsyncIterator[Record] |
| 127 | + ) -> AsyncIterator[Tuple[Record, Any, float]]: |
| 128 | + # Ensure the model has been trained before we try to make a prediction |
| 129 | + if self.separating_line is None: |
| 130 | + raise ModelNotTrained("Train model before prediction.") |
| 131 | + target = self.config.predict.NAME |
| 132 | + async for record in records: |
| 133 | + feature_data = record.features(self.features) |
| 134 | + record.predicted( |
| 135 | + target, |
| 136 | + self.predict_input(feature_data[self.features[0]]), |
| 137 | + self.separating_line[2], |
| 138 | + ) |
| 139 | + yield record |
0 commit comments