|
1 | | -# SPDX-License-Identifier: MIT |
2 | | -# Copyright (c) 2019 Intel Corporation |
3 | | -""" |
4 | | -Description of what this model does |
5 | | -""" |
6 | | -from typing import AsyncIterator, Tuple, Any, List |
7 | | - |
8 | | -from dffml.record import Record |
9 | | -from dffml.source.source import Sources |
10 | | -from dffml.feature import Features |
11 | | -from dffml.model.accuracy import Accuracy |
12 | | -from dffml.model.model import ModelContext, Model |
13 | | -from dffml.util.entrypoint import entrypoint |
14 | | -from dffml.base import config |
| 1 | +import pathlib |
| 2 | +import statistics |
| 3 | +from typing import AsyncIterator, Tuple, Any, Type, List |
| 4 | + |
| 5 | +from dffml import ( |
| 6 | + config, |
| 7 | + field, |
| 8 | + entrypoint, |
| 9 | + SimpleModel, |
| 10 | + ModelNotTrained, |
| 11 | + Accuracy, |
| 12 | + Feature, |
| 13 | + Features, |
| 14 | + Sources, |
| 15 | + Record, |
| 16 | +) |
| 17 | + |
| 18 | + |
| 19 | +def matrix_subtract(one, two): |
| 20 | + return [ |
| 21 | + one_element - two_element for one_element, two_element in zip(one, two) |
| 22 | + ] |
| 23 | + |
| 24 | + |
| 25 | +def matrix_multiply(one, two): |
| 26 | + return [ |
| 27 | + one_element * two_element for one_element, two_element in zip(one, two) |
| 28 | + ] |
| 29 | + |
| 30 | + |
| 31 | +def squared_error(y, line): |
| 32 | + return sum(map(lambda element: element ** 2, matrix_subtract(y, line))) |
| 33 | + |
| 34 | + |
| 35 | +def coeff_of_deter(y, regression_line): |
| 36 | + y_mean_line = [statistics.mean(y)] * len(y) |
| 37 | + squared_error_mean = squared_error(y, y_mean_line) |
| 38 | + squared_error_regression = squared_error(y, regression_line) |
| 39 | + return 1 - (squared_error_regression / squared_error_mean) |
| 40 | + |
| 41 | + |
| 42 | +def best_fit_line(x, y): |
| 43 | + mean_x = statistics.mean(x) |
| 44 | + mean_y = statistics.mean(y) |
| 45 | + m = (mean_x * mean_y - statistics.mean(matrix_multiply(x, y))) / ( |
| 46 | + (mean_x ** 2) - statistics.mean(matrix_multiply(x, x)) |
| 47 | + ) |
| 48 | + b = mean_y - (m * mean_x) |
| 49 | + regression_line = [m * x + b for x in x] |
| 50 | + accuracy = coeff_of_deter(y, regression_line) |
| 51 | + return (m, b, accuracy) |
15 | 52 |
|
16 | 53 |
|
17 | 54 | @config |
18 | 55 | class MiscModelConfig: |
19 | | - # This model never uses the directory, but chances are if you want to save |
20 | | - # and load data from disk you will need to |
21 | | - directory: str |
22 | | - classifications: List[str] |
23 | | - features: Features |
| 56 | + predict: Feature = field("Label or the value to be predicted") |
| 57 | + features: Features = field("Features to train on. For SLR only 1 allowed") |
| 58 | + directory: pathlib.Path = field( |
| 59 | + "Directory where state should be saved", |
| 60 | + default=pathlib.Path("~", ".cache", "dffml", "miscmodel"), |
| 61 | + ) |
24 | 62 |
|
25 | 63 |
|
26 | | -class MiscModelContext(ModelContext): |
27 | | - """ |
28 | | - Model wraping model_name API |
29 | | - """ |
| 64 | +@entrypoint("miscmodel") |
| 65 | +class MiscModel(SimpleModel): |
| 66 | + # The configuration class needs to be set as the CONFIG property |
| 67 | + CONFIG: Type[MiscModelConfig] = MiscModelConfig |
| 68 | + # Simple Linear Regression only supports training on a single feature. |
| 69 | + # Do not define NUM_SUPPORTED_FEATURES if you support arbitrary numbers of |
| 70 | + # features. |
| 71 | + NUM_SUPPORTED_FEATURES: int = 1 |
| 72 | + # We only support single dimensional values, non-matrix / array |
| 73 | + # Do not define SUPPORTED_LENGTHS if you support arbitrary dimensions |
| 74 | + SUPPORTED_LENGTHS: List[int] = [1] |
30 | 75 |
|
31 | | - async def train(self, sources: Sources): |
32 | | - """ |
33 | | - Train using records as the data to learn from. |
34 | | - """ |
35 | | - pass |
| 76 | + async def train(self, sources: Sources) -> None: |
| 77 | + # X and Y data |
| 78 | + x = [] |
| 79 | + y = [] |
| 80 | + # Go through all records that have the feature we're training on and the |
| 81 | + # feature we want to predict. Since our model only supports 1 feature, |
| 82 | + # the self.features list will only have one element at index 0. |
| 83 | + async for record in sources.with_features( |
| 84 | + self.features + [self.config.predict.NAME] |
| 85 | + ): |
| 86 | + x.append(record.feature(self.features[0])) |
| 87 | + y.append(record.feature(self.config.predict.NAME)) |
| 88 | + # Use self.logger to report how many records are being used for training |
| 89 | + self.logger.debug("Number of input records: %d", len(x)) |
| 90 | + # Save m, b, and accuracy |
| 91 | + self.storage["regression_line"] = best_fit_line(x, y) |
36 | 92 |
|
37 | 93 | async def accuracy(self, sources: Sources) -> Accuracy: |
38 | | - """ |
39 | | - Evaluates the accuracy of our model after training using the input records |
40 | | - as test data. |
41 | | - """ |
42 | | - # Lies |
43 | | - return 1.0 |
| 94 | + # Load saved regression line |
| 95 | + regression_line = self.storage.get("regression_line", None) |
| 96 | + # Ensure the model has been trained before we try to make a prediction |
| 97 | + if regression_line is None: |
| 98 | + raise ModelNotTrained("Train model before assessing for accuracy.") |
| 99 | + # Accuracy is the last element in regression_line, which is a list of |
| 100 | + # three values: m, b, and accuracy. |
| 101 | + return Accuracy(regression_line[2]) |
44 | 102 |
|
45 | 103 | async def predict( |
46 | 104 | self, records: AsyncIterator[Record] |
47 | 105 | ) -> AsyncIterator[Tuple[Record, Any, float]]: |
48 | | - """ |
49 | | - Uses trained data to make a prediction about the quality of a record. |
50 | | - """ |
| 106 | + # Load saved regression line |
| 107 | + regression_line = self.storage.get("regression_line", None) |
| 108 | + # Ensure the model has been trained before we try to make a prediction |
| 109 | + if regression_line is None: |
| 110 | + raise ModelNotTrained("Train model before prediction.") |
| 111 | + # Expand the regression_line into named variables |
| 112 | + m, b, accuracy = regression_line |
| 113 | + # Iterate through each record that needs a prediction |
51 | 114 | async for record in records: |
52 | | - yield record, self.parent.config.classifications[ |
53 | | - record.feature(self.parent.config.features.names()[0]) |
54 | | - ], 1.0 |
55 | | - |
56 | | - |
57 | | -@entrypoint("misc") |
58 | | -class MiscModel(Model): |
59 | | - |
60 | | - CONTEXT = MiscModelContext |
| 115 | + # Grab the x data from the record |
| 116 | + x = record.feature(self.features[0]) |
| 117 | + # Calculate y |
| 118 | + y = m * x + b |
| 119 | + # Set the calculated value with the estimated accuracy |
| 120 | + record.predicted(self.config.predict.NAME, y, accuracy) |
| 121 | + # Yield the record to the caller |
| 122 | + yield record |
0 commit comments