File size: 4,364 Bytes
529cb6f 7266e2a 529cb6f | 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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | import torch
import sys
import pandas as pd
from typing import TypedDict, Optional, Tuple
import datetime
import math
import importlib.util
from huggingface_hub import hf_hub_download
from MLmodel import MLmodel
import numpy as np
import pickle
class ProcessedSynapse(TypedDict):
property_id: Optional[str]
nextplace_id: Optional[str]
listing_id: Optional[str]
address: Optional[str]
city: Optional[str]
state: Optional[str]
zip_code: Optional[str]
beds: Optional[int]
baths: Optional[float]
sqft: Optional[int]
lot_size: Optional[int]
year_built: Optional[int]
latitude: Optional[float]
longitude: Optional[float]
property_type: Optional[str]
last_sale_date: Optional[str]
hoa_dues: Optional[float]
market: Optional[str]
listing_price: Optional[float]
listing_date: Optional[str]
sale_price: Optional[float]
sale_date: Optional[str]
class MLBaseModelDriver:
def __init__(self):
self.model, self.scaler1, self.scaler2 = self.load_model()
def _download_model_files(self) -> Tuple[str, str, str, str]:
model_path = "Pratham0712/NextPlace"
model_file = hf_hub_download(repo_id=model_path, filename="model.pkl")
model_class_file = hf_hub_download(repo_id=model_path, filename="MLmodel.py")
scaler1 = hf_hub_download(repo_id=model_file, filename="scaler.pkl")
scaler2 = hf_hub_download(repo_id=model_file, filename="scaler.pkl")
return model_file, scaler1, scaler2, model_class_file
def load_model(self) -> Tuple[any, any, any]:
print(f"Loading the model")
model_file, scaler_1, scaler_2, model_class_file = self._download_model_files()
model_class = self._import_model_class(model_class_file)
model = model_class(input_dim = 4)
with open(model_file, 'rb') as f:
state_dict = pickle.load(f)
model.load_state_dict(state_dict)
model.eval()
with open(scaler_1, 'rb') as f:
scaler1 = pickle.load(f)
with open(scaler_2, 'rb') as f:
scaler2 = pickle.load(f)
print(f"Model is loaded")
return model, scaler1, scaler2
def _import_model_class(self, model_class_file):
module_name = "MLmodel"
spec = importlib.util.spec_from_file_location(module_name, model_class_file)
model_module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = model_module
spec.loader.exec_module(model_module)
if hasattr(model_module, "MLmodel"):
return model_module.MLmodel
else:
raise AttributeError(f"Nope")
def _preprocess_input(self, data: ProcessedSynapse) -> torch.tensor:
"""
preprocess the input for inference
:param data: synapse from the validator
:return: tensor representing the synapse
beds baths sqft listing_price
"""
df = pd.DataFrame([data])
default_beds = 3
default_sqft = 1500.0
df['beds'] = df['beds'].fillna(default_beds)
df['baths'] = df['baths'].fillna(default_beds)
df['sqft'] = pd.to_numeric(df['sqft'], errors='coerce').fillna(default_sqft)
X = df[['beds', 'baths', 'sqft', 'listing_price']]
input_tensor = torch.tensor(X.values, dtype=torch.float32)
return input_tensor
def run_inference(self, input_data: ProcessedSynapse)-> Tuple[float, str]:
input_tensor = self._preprocess_input(input_data)
with torch.no_grad():
predict = self.model(input_tensor)
predict_sale_scaled, predict_days_scaled = predict[0].numpy()
predict_price = self._inverseScale_price(predict_sale_scaled)
predict_date = self._inverseScale_date(input_data["listing_date"], input_data["last_sale_date"], predict_days_scaled)
return float(predict_price), predict_date
def _inverseScale_price(self, price):
predict_price = self.scaler1.inverse_transform(price[:, 1].reshape(-1, 1))
return predict_price
def _inverseScale_date(self, listing_date, last_sale_date, date):
predict_date_inv = self.scaler2.inverse_transform(date[:, 0].reshape(-1, 1))
ref_date = pd.to_datetime('2024-11-01')
return (predict_date_inv + ref_date)
|