jonathanjordan21 commited on
Commit
cecdf58
·
verified ·
1 Parent(s): 81135c5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +253 -0
app.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from torch import nn
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+ from utils2 import compute_features, DATASET_COLUMNS
9
+ from scipy.stats import nbinom
10
+
11
+ from xgboost import XGBRegressor
12
+ import json
13
+
14
+ # class NegBinomialModel(nn.Module):
15
+ # def __init__(self, in_features):
16
+ # super().__init__()
17
+ # self.linear = nn.Linear(in_features, 1)
18
+ # self.alpha = nn.Parameter(torch.tensor(0.5))
19
+
20
+ # def forward(self, x):
21
+ # # safer activation than exp()
22
+ # mu = torch.exp(torch.clamp(self.linear(x), min=-5, max=5))
23
+ # alpha = torch.clamp(self.alpha, min=1e-3, max=10)
24
+ # return mu.squeeze(), alpha
25
+
26
+
27
+ # model = NegBinomialModel(12)
28
+ # model.load_state_dict(torch.load("model_weights.pt", map_location='cpu'))
29
+ # model.eval()
30
+
31
+ # MU_BANKS = 2.6035915713614286
32
+ # STD_BANKS = 3.0158890435512125
33
+
34
+
35
+ # with open("xgb_model(1).json", "r") as f:
36
+ # params = json.load(f)
37
+
38
+ xgb_model = XGBRegressor()
39
+ xgb_model.load_model("xgb_model(1).json")
40
+
41
+ def predict_score(lat, lon):
42
+ # Convert input to tensor
43
+ # inputs = torch.tensor([[lat, lon]], dtype=torch.float32)
44
+ inputs = compute_features((lat,lon))
45
+ print("[INPUTS]", inputs)
46
+ num_banks = inputs.pop("num_banks_in_radius", 0)
47
+
48
+ input_dict = inputs.copy()
49
+
50
+ inputs = torch.tensor(list(inputs.values()), dtype=torch.float32)
51
+
52
+ # # Get model output
53
+ # with torch.no_grad():
54
+ # mu_pred, alpha = model(inputs)
55
+
56
+ # # Unpack into respective values
57
+ # mu_pred = mu_pred.numpy().flatten()
58
+
59
+ mu_pred2 = xgb_model.predict(inputs.unsqueeze(0).numpy())
60
+
61
+ # r = 1/alpha
62
+ # p = r / (r + mu_pred)
63
+
64
+ # # Compute pmf and mode
65
+ # k_mode = int((r - 1) * (1 - p) / p) # mode of NB
66
+ # p_k = nbinom.pmf(num_banks, r, p)
67
+ # p_mode = nbinom.pmf(k_mode, r, p)
68
+
69
+ # # Score normalized 0–100
70
+ # score = (p_k / p_mode) * 100
71
+ # score = np.clip(score, 0, 100)
72
+
73
+ # diff = (num_banks - mu_pred) / (mu_pred + 1e-6)
74
+ # # score = (1 - np.tanh(diff))
75
+
76
+ # print("[TANH]", np.tanh(diff))
77
+
78
+ # diff = mu_pred2 - num_banks
79
+ # score = 100 / (1 + np.exp(-alpha * diff))
80
+
81
+ # score = np.abs(1 + np.tanh(diff)) / 2 * 100
82
+
83
+
84
+ # score = (1 * np.abs(mu_pred2 + 0.1)) * 100
85
+
86
+ # score = np.sigmoid(mu_pred2 - num_banks + 0.1) * 100
87
+
88
+ score = 100 / (1 + np.exp(num_banks - mu_pred2))
89
+
90
+ # You can apply any post-processing here
91
+ return (
92
+ round(float(score), 3),
93
+ num_banks,
94
+ # round(float(mu_pred), 3),
95
+ round(float(mu_pred2), 3),
96
+ # round(float(log_score),3)
97
+ # "Normal Score": round(float(normal_score), 3),
98
+ input_dict["total_amenities"],
99
+
100
+ *[v for k,v in input_dict.items() if k[:3] == "num"]
101
+
102
+ )
103
+
104
+ # ======== Gradio Interface ========
105
+ interface = gr.Interface(
106
+ fn=predict_score,
107
+ inputs=[
108
+ gr.Number(label="Latitude"),
109
+ gr.Number(label="Longitude"),
110
+ ],
111
+ outputs=[
112
+ gr.Number(label="Score (0 - 100)"),
113
+ gr.Number(label="Current ATMs"),
114
+ # gr.Number(label="Number of Ideal Banks (Negative Binomial)"),
115
+ gr.Number(label="Ideal ATMs (XGBoost)"),
116
+ # gr.Number(label="Log Score Probability"),
117
+
118
+ gr.Number(label="Total Amenities"),
119
+
120
+ *[gr.Number(label=x) for x in DATASET_COLUMNS]
121
+
122
+ # gr.Number(label="Dining and Drinking"),
123
+ # gr.Number(label="Community and Government"),
124
+ # gr.Number(label="Retail"),
125
+ # gr.Number(label="Business and Professional Services"),
126
+ # gr.Number(label="Landmarks and Outdoors"),
127
+ # gr.Number(label="Arts and Entertainment"),
128
+ # gr.Number(label="Health and Medicine"),
129
+ # gr.Number(label="Travel and Transportation"),
130
+ # gr.Number(label="Sports and Recreation"),
131
+ # gr.Number(label="Event"),
132
+ ],
133
+ title="Bank Location Scoring Model",
134
+ description="Enter latitude and longitude to get the predicted score, number of banks, and normalized score.",
135
+ )
136
+
137
+
138
+ interface.launch()
139
+
140
+
141
+ # import gradio as gr
142
+ # import torch
143
+ # from torch import nn
144
+
145
+ # import numpy as np
146
+ # import pandas as pd
147
+
148
+ # from utils import compute_features
149
+ # from scipy.stats import nbinom
150
+
151
+ # from xgboost import XGBRegressor
152
+ # import json
153
+
154
+ # class NegBinomialModel(nn.Module):
155
+ # def __init__(self, in_features):
156
+ # super().__init__()
157
+ # self.linear = nn.Linear(in_features, 1)
158
+ # self.alpha = nn.Parameter(torch.tensor(0.5))
159
+
160
+ # def forward(self, x):
161
+ # # safer activation than exp()
162
+ # mu = torch.exp(torch.clamp(self.linear(x), min=-5, max=5))
163
+ # alpha = torch.clamp(self.alpha, min=1e-3, max=10)
164
+ # return mu.squeeze(), alpha
165
+
166
+
167
+ # model = NegBinomialModel(12)
168
+ # model.load_state_dict(torch.load("model_weights(1).pt", map_location='cpu'))
169
+ # model.eval()
170
+
171
+ # # MU_BANKS = 2.6035915713614286
172
+ # # STD_BANKS = 3.0158890435512125
173
+
174
+
175
+ # # with open("xgb_model(1).json", "r") as f:
176
+ # # params = json.load(f)
177
+
178
+ # xgb_model = XGBRegressor()
179
+ # xgb_model.load_model("xgb_model(1).json")
180
+
181
+ # def predict_score(lat, lon):
182
+ # # Convert input to tensor
183
+ # # inputs = torch.tensor([[lat, lon]], dtype=torch.float32)
184
+ # inputs = compute_features((lat,lon))
185
+ # print("[INPUTS]", inputs)
186
+ # num_banks = inputs.pop("num_banks_in_radius", 0)
187
+
188
+ # inputs = torch.tensor(list(inputs.values()), dtype=torch.float32)
189
+
190
+ # # Get model output
191
+ # with torch.no_grad():
192
+ # mu_pred, alpha = model(inputs)
193
+
194
+ # # Unpack into respective values
195
+ # mu_pred = mu_pred.numpy().flatten()
196
+
197
+ # mu_pred2 = xgb_model.predict(inputs.unsqueeze(0).numpy())
198
+
199
+ # # r = 1/alpha
200
+ # # p = r / (r + mu_pred)
201
+
202
+ # # # Compute pmf and mode
203
+ # # k_mode = int((r - 1) * (1 - p) / p) # mode of NB
204
+ # # p_k = nbinom.pmf(num_banks, r, p)
205
+ # # p_mode = nbinom.pmf(k_mode, r, p)
206
+
207
+ # # # Score normalized 0–100
208
+ # # score = (p_k / p_mode) * 100
209
+ # # score = np.clip(score, 0, 100)
210
+
211
+ # # diff = (num_banks - mu_pred) / (mu_pred + 1e-6)
212
+ # # # score = (1 - np.tanh(diff))
213
+
214
+ # # print("[TANH]", np.tanh(diff))
215
+
216
+ # diff = mu_pred - num_banks
217
+ # score = 100 / (1 + np.exp(-alpha * diff))
218
+
219
+ # score = np.abs(1 + np.tanh(diff)) / 2 * 100
220
+
221
+
222
+ # # score = (1 * np.abs(mu_pred + 0.1)) * 100
223
+
224
+ # # You can apply any post-processing here
225
+ # return (
226
+ # round(float(score), 3),
227
+ # num_banks,
228
+ # round(float(mu_pred), 3),
229
+ # round(float(mu_pred2), 3),
230
+ # # round(float(log_score),3)
231
+ # # "Normal Score": round(float(normal_score), 3),
232
+ # )
233
+
234
+ # # ======== Gradio Interface ========
235
+ # interface = gr.Interface(
236
+ # fn=predict_score,
237
+ # inputs=[
238
+ # gr.Number(label="Latitude"),
239
+ # gr.Number(label="Longitude"),
240
+ # ],
241
+ # outputs=[
242
+ # gr.Number(label="Score (0 - 100)"),
243
+ # gr.Number(label="Number of Current Banks"),
244
+ # gr.Number(label="Number of Ideal Banks (Negative Binomial)"),
245
+ # gr.Number(label="Number of Ideal Banks (XGBoost)"),
246
+ # # gr.Number(label="Log Score Probability"),
247
+ # ],
248
+ # title="Bank Location Scoring Model",
249
+ # description="Enter latitude and longitude to get the predicted score, number of banks, and normalized score.",
250
+ # )
251
+
252
+
253
+ # interface.launch()