Download modeling_linear_regression.py from Eric-Yyvuw/ml-from-scratch: direct link, hf CLI and curl.
- Browser
- Download file 1.57 kB
-
https://huggingface.co/Eric-Yyvuw/ml-from-scratch/resolve/main/modeling_linear_regression.py
- Command line
-
hf download hf://Eric-Yyvuw/ml-from-scratch/modeling_linear_regression.py
-
curl -L -o modeling_linear_regression.py https://huggingface.co/Eric-Yyvuw/ml-from-scratch/resolve/main/modeling_linear_regression.py
1.57 kB
| """ | |
| 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) |