Pratham0712 commited on
Commit
529cb6f
·
verified ·
1 Parent(s): 262c8c4

Upload 5 files

Browse files
Files changed (5) hide show
  1. MLbaseModelDriver.py +122 -0
  2. MLmodel.py +21 -0
  3. model.pkl +3 -0
  4. scaler.pkl +3 -0
  5. scaler1.pkl +3 -0
MLbaseModelDriver.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import sys
3
+ import pandas as pd
4
+ from typing import TypedDict, Optional, Tuple
5
+ import datetime
6
+ import math
7
+ import importlib.util
8
+ from huggingface_hub import hf_hub_download
9
+ from MLmodel import MLmodel
10
+ import numpy as np
11
+ import pickle
12
+
13
+ class ProcessedSynapse(TypedDict):
14
+ property_id: Optional[str]
15
+ nextplace_id: Optional[str]
16
+ listing_id: Optional[str]
17
+ address: Optional[str]
18
+ city: Optional[str]
19
+ state: Optional[str]
20
+ zip_code: Optional[str]
21
+ beds: Optional[int]
22
+ baths: Optional[float]
23
+ sqft: Optional[int]
24
+ lot_size: Optional[int]
25
+ year_built: Optional[int]
26
+ latitude: Optional[float]
27
+ longitude: Optional[float]
28
+ property_type: Optional[str]
29
+ last_sale_date: Optional[str]
30
+ hoa_dues: Optional[float]
31
+ market: Optional[str]
32
+ listing_price: Optional[float]
33
+ listing_date: Optional[str]
34
+ sale_price: Optional[float]
35
+ sale_date: Optional[str]
36
+
37
+ class MLBaseModelDriver:
38
+ def __init__(self):
39
+ self.model, self.scaler1, self.scaler2 = self.load_model()
40
+
41
+ def _download_model_files(self) -> Tuple[str, str, str, str]:
42
+
43
+ model_path = "Pratham0712/NextPlace"
44
+ model_file = hf_hub_download(repo_id=model_path, filename="model.pkl")
45
+ model_class_file = hf_hub_download(repo_id=model_path, filename="MLmodel.py")
46
+ scaler1 = hf_hub_download(repo_id=model_file, filename="scaler.pkl")
47
+ scaler2 = hf_hub_download(repo_id=model_file, filename="scaler.pkl")
48
+
49
+ return model_file, scaler1, scaler2, model_class_file
50
+
51
+ def load_model(self) -> Tuple[any, any, any]:
52
+ print(f"Loading the model")
53
+ model_file, scaler_1, scaler_2, model_class_file = self._download_model_files()
54
+
55
+ model_class = self._import_model_class(model_class_file)
56
+ model = model_class(input_dim = 4)
57
+
58
+ with open(model_file, 'rb') as f:
59
+ state_dict = pickle.load(f)
60
+
61
+ model.load_state_dict(state_dict)
62
+ model.eval()
63
+
64
+ with open(scaler_1, 'rb') as f:
65
+ scaler1 = pickle.load(f)
66
+ with open(scaler_2, 'rb') as f:
67
+ scaler2 = pickle.load(f)
68
+
69
+ print(f"Model is loaded")
70
+ return model, scaler1, scaler2
71
+
72
+ def _import_model_class(self, model_class_file):
73
+ module_name = "MLmodel"
74
+ spec = importlib.util.spec_from_file_location(module_name, model_class_file)
75
+ model_module = importlib.util.module_from_spec(spec)
76
+ sys.modules[module_name] = model_module
77
+ spec.loader.exec_module(model_module)
78
+
79
+ if hasattr(model_module, "MLmodel"):
80
+ return model_module.MLmodel
81
+ else:
82
+ raise AttributeError(f"Nope")
83
+
84
+ def _preprocess_input(self, data: ProcessedSynapse) -> torch.tensor:
85
+ """
86
+ preprocess the input for inference
87
+ :param data: synapse from the validator
88
+ :return: tensor representing the synapse
89
+ beds baths sqft listing_price
90
+ """
91
+ df = pd.DataFrame([data])
92
+ default_beds = 3
93
+ default_sqft = 1500.0
94
+ df['beds'] = df['beds'].fillna(default_beds)
95
+ df['baths'] = df['baths'].fillna(default_beds)
96
+ df['sqft'] = pd.to_numeric(df['sqft'], errors='coerce').fillna(default_sqft)
97
+
98
+ X = df[['beds', 'baths', 'sqft', 'listing_price']]
99
+ input_tensor = torch.tensor(X.values, dtype=torch.float32)
100
+ return input_tensor
101
+
102
+ def (self, input_data: ProcessedSynapse)-> Tuple[float, str]:
103
+ input_tensor = self._preprocess_input(input_data)
104
+
105
+ with torch.no_grad():
106
+ predict = self.model(input_tensor)
107
+ predict_sale_scaled, predict_days_scaled = predict[0].numpy()
108
+ predict_price = self._inverseScale_price(predict_sale_scaled)
109
+ predict_date = self._inverseScale_date(input_data["listing_date"], input_data["last_sale_date"], predict_days_scaled)
110
+
111
+ return float(predict_price), predict_date
112
+
113
+ def _inverseScale_price(self, price):
114
+ predict_price = self.scaler1.inverse_transform(price[:, 1].reshape(-1, 1))
115
+ return predict_price
116
+
117
+ def _inverseScale_date(self, listing_date, last_sale_date, date):
118
+ predict_date_inv = self.scaler2.inverse_transform(date[:, 0].reshape(-1, 1))
119
+ ref_date = pd.to_datetime('2024-11-01')
120
+ return (predict_date_inv + ref_date)
121
+
122
+
MLmodel.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+
6
+ class MLmodel(nn.Module):
7
+ def __init__(self, input_dim):
8
+ super(MLmodel, self).__init__()
9
+ self.fc1 = nn.Linear(input_dim, 128)
10
+ self.bn1 = nn.BatchNorm1d(128)
11
+ self.fc2 = nn.Linear(128, 64)
12
+ self.bn2 = nn.BatchNorm1d(64)
13
+ self.fc3 = nn.Linear(64, 2)
14
+ self.relu = nn.ReLU()
15
+ self.sm = nn.Softmax(dim = 1)
16
+
17
+ def forward(self, x):
18
+ x = self.relu(self.bn1(self.fc1(x)))
19
+ x = self.relu(self.bn2(self.fc2(x)))
20
+ x = self.sm(self.fc3(x))
21
+ return x
model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c982ba4aae94f95142090719ee1a643aa65c0949b2f62f077b6a3d3f768d1fc1
3
+ size 45729
scaler.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2cac2c05d895c907dfd15ba46d97a01ace72978c1ee83103afe84519ae2f91c
3
+ size 625
scaler1.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae130e2e6401dad3f4a4f2cf5566145bb9e3423b28906a6d4744f2b90131b2f4
3
+ size 622