File size: 1,568 Bytes
eca7417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
LinearRegressionModel — a minimal transformers-compatible model.

Lets you load the trained CS401 linear regression weights straight from the Hub:

    from transformers import AutoModel

    model = AutoModel.from_pretrained(
        "Eric-Yyvuw/linear-regression", trust_remote_code=True
    )
    model.predict([150.0])   # -> tensor([450.0])  (150 m^2 -> ~450 €k)

Requires torch + transformers. A no-dependency (numpy-only) loader appears in
the model card for anyone who wants to read the weights without transformers.
"""

import torch
from torch import nn

from transformers import AutoConfig, AutoModel, PreTrainedConfig, PreTrainedModel

from configuration_linear_regression import LinearRegressionConfig


class LinearRegressionModel(PreTrainedModel):
    config_class = LinearRegressionConfig
    base_model_prefix = "model"

    def __init__(self, config):
        super().__init__(config)
        self.theta0 = nn.Parameter(torch.tensor(config.theta0, dtype=torch.float32))
        self.theta1 = nn.Parameter(torch.tensor(config.theta1, dtype=torch.float32))

    def forward(self, x):
        # h(x) = theta0 + theta1 * x
        return self.theta0 + self.theta1 * x

    def predict(self, x):
        """Price (€k) for area(s) x (m^2). Accepts a float, list, or tensor."""
        if not isinstance(x, torch.Tensor):
            x = torch.tensor(x, dtype=torch.float32)
        return self.forward(x).detach()


AutoConfig.register("linear_regression", LinearRegressionConfig)
AutoModel.register(LinearRegressionConfig, LinearRegressionModel)