|
| 1 | +# SPDX-License-Identifier: MIT |
| 2 | +# Copyright (c) 2019 Intel Corporation |
| 3 | +""" |
| 4 | +Description of what this model does |
| 5 | +""" |
| 6 | +import os |
| 7 | +import abc |
| 8 | +import json |
| 9 | +import hashlib |
| 10 | +from typing import AsyncIterator, Tuple, Any, List, Optional, NamedTuple, Dict |
| 11 | + |
| 12 | +import numpy as np |
| 13 | + |
| 14 | +from dffml.repo import Repo |
| 15 | +from dffml.source.source import Sources |
| 16 | +from dffml.feature import Features |
| 17 | +from dffml.accuracy import Accuracy |
| 18 | +from dffml.model.model import ModelConfig, ModelContext, Model |
| 19 | +from dffml.util.entrypoint import entry_point |
| 20 | +from dffml.util.cli.arg import Arg |
| 21 | + |
| 22 | + |
| 23 | +class SLRConfig(ModelConfig, NamedTuple): |
| 24 | + predict: str |
| 25 | + directory: str |
| 26 | + |
| 27 | + |
| 28 | +class SLRContext(ModelContext): |
| 29 | + def __init__(self, parent, features): |
| 30 | + super().__init__(parent, features) |
| 31 | + self.xData = np.array([]) |
| 32 | + self.yData = np.array([]) |
| 33 | + self.features = self.applicable_features(features) |
| 34 | + self._features_hash_ = hashlib.sha384( |
| 35 | + ("".join(sorted(self.features))).encode() |
| 36 | + ).hexdigest() |
| 37 | + |
| 38 | + @property |
| 39 | + def regression_line(self): |
| 40 | + return self.parent.saved.get(self._features_hash_, None) |
| 41 | + |
| 42 | + @regression_line.setter |
| 43 | + def regression_line(self, rline): |
| 44 | + self.parent.saved[self._features_hash_] = rline |
| 45 | + |
| 46 | + def applicable_features(self, features): |
| 47 | + usable = [] |
| 48 | + if len(features) != 1: |
| 49 | + raise ValueError( |
| 50 | + "Simple Linear Regression doesn't support features other than 1" |
| 51 | + ) |
| 52 | + for feature in features: |
| 53 | + if feature.dtype() != int and feature.dtype() != float: |
| 54 | + raise ValueError( |
| 55 | + "Simple Linear Regression only supports int or float feature" |
| 56 | + ) |
| 57 | + if feature.length() != 1: |
| 58 | + raise ValueError( |
| 59 | + "Simple LR only supports single values (non-matrix / array)" |
| 60 | + ) |
| 61 | + usable.append(feature.NAME) |
| 62 | + return sorted(usable) |
| 63 | + |
| 64 | + async def predict_input(self, x): |
| 65 | + prediction = self.regression_line[0] * x + self.regression_line[1] |
| 66 | + self.logger.debug( |
| 67 | + "Predicted Value of {} {}:".format( |
| 68 | + self.parent.config.predict, prediction |
| 69 | + ) |
| 70 | + ) |
| 71 | + return prediction |
| 72 | + |
| 73 | + async def squared_error(self, ys, yline): |
| 74 | + return sum((ys - yline) ** 2) |
| 75 | + |
| 76 | + async def coeff_of_deter(self, ys, regression_line): |
| 77 | + y_mean_line = [np.mean(ys) for y in ys] |
| 78 | + squared_error_mean = await self.squared_error(ys, y_mean_line) |
| 79 | + squared_error_regression = await self.squared_error( |
| 80 | + ys, regression_line |
| 81 | + ) |
| 82 | + return 1 - (squared_error_regression / squared_error_mean) |
| 83 | + |
| 84 | + async def best_fit_line(self): |
| 85 | + self.logger.debug("Number of input repos: {}".format(len(self.xData))) |
| 86 | + x = self.xData |
| 87 | + y = self.yData |
| 88 | + mean_x = np.mean(self.xData) |
| 89 | + mean_y = np.mean(self.yData) |
| 90 | + m = (mean_x * mean_y - np.mean(x * y)) / ( |
| 91 | + (mean_x ** 2) - np.mean(x * x) |
| 92 | + ) |
| 93 | + b = mean_y - (m * mean_x) |
| 94 | + regression_line = [m * x + b for x in x] |
| 95 | + accuracy = await self.coeff_of_deter(y, regression_line) |
| 96 | + return (m, b, accuracy) |
| 97 | + |
| 98 | + async def train(self, sources: Sources): |
| 99 | + async for repo in sources.with_features( |
| 100 | + self.features + [self.parent.config.predict] |
| 101 | + ): |
| 102 | + feature_data = repo.features( |
| 103 | + self.features + [self.parent.config.predict] |
| 104 | + ) |
| 105 | + self.xData = np.append(self.xData, feature_data[self.features[0]]) |
| 106 | + self.yData = np.append( |
| 107 | + self.yData, feature_data[self.parent.config.predict] |
| 108 | + ) |
| 109 | + self.regression_line = await self.best_fit_line() |
| 110 | + |
| 111 | + async def accuracy(self, sources: Sources) -> Accuracy: |
| 112 | + if self.regression_line is None: |
| 113 | + raise ValueError("Model Not Trained") |
| 114 | + accuracy_value = self.regression_line[2] |
| 115 | + return Accuracy(accuracy_value) |
| 116 | + |
| 117 | + async def predict( |
| 118 | + self, repos: AsyncIterator[Repo] |
| 119 | + ) -> AsyncIterator[Tuple[Repo, Any, float]]: |
| 120 | + async for repo in repos: |
| 121 | + feature_data = repo.features(self.features) |
| 122 | + yield repo, await self.predict_input( |
| 123 | + feature_data[self.features[0]] |
| 124 | + ), self.regression_line[2] |
| 125 | + |
| 126 | + |
| 127 | +@entry_point("slr") |
| 128 | +class SLR(Model): |
| 129 | + """ |
| 130 | + Simple Linear Regression Model for 2 variables implemented from scratch. Models are saved under the |
| 131 | + ``directory`` in subdirectories named after the hash of their feature names. |
| 132 | + """ |
| 133 | + |
| 134 | + CONTEXT = SLRContext |
| 135 | + |
| 136 | + def __init__(self, config: SLRConfig) -> None: |
| 137 | + super().__init__(config) |
| 138 | + self.saved = {} |
| 139 | + |
| 140 | + def _filename(self): |
| 141 | + return os.path.join( |
| 142 | + self.config.directory, |
| 143 | + hashlib.sha384(self.config.predict.encode()).hexdigest() + ".json", |
| 144 | + ) |
| 145 | + |
| 146 | + async def __aenter__(self) -> SLRContext: |
| 147 | + filename = self._filename() |
| 148 | + if os.path.isfile(filename): |
| 149 | + with open(filename, "r") as read: |
| 150 | + self.saved = json.load(read) |
| 151 | + return self |
| 152 | + |
| 153 | + async def __aexit__(self, exc_type, exc_value, traceback): |
| 154 | + filename = self._filename() |
| 155 | + with open(filename, "w") as write: |
| 156 | + json.dump(self.saved, write) |
| 157 | + |
| 158 | + @classmethod |
| 159 | + def args(cls, args, *above) -> Dict[str, Arg]: |
| 160 | + cls.config_set( |
| 161 | + args, |
| 162 | + above, |
| 163 | + "directory", |
| 164 | + Arg( |
| 165 | + default=os.path.join( |
| 166 | + os.path.expanduser("~"), ".cache", "dffml", "scratch" |
| 167 | + ), |
| 168 | + help="Directory where state should be saved", |
| 169 | + ), |
| 170 | + ) |
| 171 | + cls.config_set( |
| 172 | + args, |
| 173 | + above, |
| 174 | + "predict", |
| 175 | + Arg(type=str, help="Label or the value to be predicted"), |
| 176 | + ) |
| 177 | + return args |
| 178 | + |
| 179 | + @classmethod |
| 180 | + def config(cls, config, *above) -> "SLRConfig": |
| 181 | + return SLRConfig( |
| 182 | + directory=cls.config_get(config, above, "directory"), |
| 183 | + predict=cls.config_get(config, above, "predict"), |
| 184 | + ) |
0 commit comments