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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
latitude_mean: 39.95184413388056
|
2 |
+
latitude_std: 0.0006308700565432299
|
3 |
+
longitude_mean: -75.19147985909444
|
4 |
+
longitude_std: 0.0006379960634765379
|
5 |
+
|
6 |
+
To run input tensors to `predict_from_model(input_tensor)`:
|
7 |
+
|
8 |
+
```
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
import torchvision.transforms as transforms
|
12 |
+
from torch.utils.data import DataLoader, Dataset
|
13 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
14 |
+
from huggingface_hub import PyTorchModelHubMixin
|
15 |
+
from PIL import Image
|
16 |
+
import os
|
17 |
+
import numpy as np
|
18 |
+
|
19 |
+
def predict_from_model(input_tensor):
|
20 |
+
import torch
|
21 |
+
import torchvision.transforms as transforms
|
22 |
+
import matplotlib.pyplot as plt
|
23 |
+
from geopy.distance import geodesic
|
24 |
+
from datasets import load_dataset
|
25 |
+
from huggingface_hub import hf_hub_download
|
26 |
+
import numpy as np
|
27 |
+
#############
|
28 |
+
path_map = {"best region models/region_model_lr_0.0002_step_10_gamma_0.1_epochs_15.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="best region models/region_model_lr_0.0002_step_10_gamma_0.1_epochs_15.pth"),
|
29 |
+
"best region models/region_model_lr_0.00035_step_10_gamma_0.1_epochs_50.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="best region models/region_model_lr_0.00035_step_10_gamma_0.1_epochs_50.pth"),
|
30 |
+
"best region models/region_model_lr_0.0005_step_10_gamma_0.1_epochs_50.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="best region models/region_model_lr_0.0005_step_10_gamma_0.1_epochs_50.pth"),
|
31 |
+
"best region models/region_model_lr_0.0005_step_10_gamma_0.1_epochs_60.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="best region models/region_model_lr_0.0005_step_10_gamma_0.1_epochs_60.pth"),
|
32 |
+
"best region models/region_model_lr_0.002_step_10_gamma_0.1_epochs_100.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="best region models/region_model_lr_0.002_step_10_gamma_0.1_epochs_100.pth"),
|
33 |
+
"best region models/model_histories.json" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="best region models/model_histories.json"),
|
34 |
+
"models/location_model_0.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="models/location_model_0.pth"),
|
35 |
+
"models/location_model_1.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="models/location_model_1.pth"),
|
36 |
+
"models/location_model_2.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="models/location_model_2.pth"),
|
37 |
+
"models/location_model_3.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="models/location_model_3.pth"),
|
38 |
+
"models/location_model_4.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="models/location_model_4.pth"),
|
39 |
+
"models/location_model_5.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="models/location_model_5.pth"),
|
40 |
+
"models/location_model_6.pth" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="models/location_model_6.pth"),
|
41 |
+
"region_ensemble_weights.json" : hf_hub_download(repo_id="IanAndJohn/region_ensemble_model", filename="region_ensemble_weights.json")}
|
42 |
+
|
43 |
+
##############
|
44 |
+
import torch
|
45 |
+
import torch.nn as nn
|
46 |
+
import torchvision.transforms as transforms
|
47 |
+
from torch.utils.data import DataLoader, Dataset
|
48 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
49 |
+
from huggingface_hub import PyTorchModelHubMixin
|
50 |
+
from PIL import Image
|
51 |
+
import os
|
52 |
+
import numpy as np
|
53 |
+
|
54 |
+
class PredictedObject():
|
55 |
+
def __init__(self, image, lat, lon, region, original_lat=None, original_lon=None):
|
56 |
+
self.lat = lat
|
57 |
+
self.lon = lon
|
58 |
+
self.region = region
|
59 |
+
self.image = image
|
60 |
+
|
61 |
+
if original_lat is None or original_lon is None:
|
62 |
+
self.original_lat = lat
|
63 |
+
self.original_lon = lon
|
64 |
+
else:
|
65 |
+
self.original_lat = original_lat
|
66 |
+
self.original_lon = original_lon
|
67 |
+
|
68 |
+
self.predicted_region = None
|
69 |
+
self.predicted_lat = None
|
70 |
+
self.predicted_lon = None
|
71 |
+
|
72 |
+
def __lt__(self, other):
|
73 |
+
return self.predicted_region < other.predicted_region
|
74 |
+
|
75 |
+
def __eq__(self, other):
|
76 |
+
return self.predicted_region == other.predicted_region
|
77 |
+
|
78 |
+
class PredictionObjectDataset(Dataset):
|
79 |
+
def __init__(self, object_lst, transform=None, lat_mean=None, lat_std=None, lon_mean=None, lon_std=None, useRegions=False, give_originals=False):
|
80 |
+
self.object_lst = object_lst
|
81 |
+
self.transform = transform
|
82 |
+
self.useRegions = useRegions
|
83 |
+
self.give_originals = give_originals
|
84 |
+
|
85 |
+
# Compute mean and std from the dataframe if not provided
|
86 |
+
if (len(self.object_lst) == 1):
|
87 |
+
self.latitude_mean = self.object_lst[0].lat
|
88 |
+
self.latitude_std = 1
|
89 |
+
self.longitude_mean = self.object_lst[0].lon
|
90 |
+
self.longitude_std = 1
|
91 |
+
else:
|
92 |
+
self.latitude_mean = lat_mean if lat_mean is not None else np.mean(np.array([x.lat for x in self.object_lst]))
|
93 |
+
self.latitude_std = lat_std if lat_std is not None else np.std(np.array([x.lat for x in self.object_lst]))
|
94 |
+
self.longitude_mean = lon_mean if lon_mean is not None else np.mean(np.array([x.lon for x in self.object_lst]))
|
95 |
+
self.longitude_std = lon_std if lon_std is not None else np.std(np.array([x.lon for x in self.object_lst]))
|
96 |
+
|
97 |
+
self.normalize()
|
98 |
+
|
99 |
+
def normalize(self):
|
100 |
+
new_object_lst = []
|
101 |
+
for obj in self.object_lst:
|
102 |
+
obj.lat = (obj.lat - self.latitude_mean) / self.latitude_std
|
103 |
+
obj.lon = (obj.lon - self.longitude_mean) / self.longitude_std
|
104 |
+
new_object_lst.append(obj)
|
105 |
+
self.object_lst = new_object_lst
|
106 |
+
|
107 |
+
def __len__(self):
|
108 |
+
return len(self.object_lst)
|
109 |
+
|
110 |
+
def __getitem__(self, idx):
|
111 |
+
# Extract data
|
112 |
+
example = self.object_lst[idx]
|
113 |
+
|
114 |
+
# Load and process the image
|
115 |
+
image = example.image
|
116 |
+
latitude = example.lat
|
117 |
+
longitude = example.lon
|
118 |
+
region = example.region
|
119 |
+
|
120 |
+
# image = image.rotate(-90, expand=True)
|
121 |
+
if self.transform:
|
122 |
+
image = self.transform(image)
|
123 |
+
|
124 |
+
# Normalize GPS coordinates
|
125 |
+
gps_coords = torch.tensor([latitude, longitude], dtype=torch.float32)
|
126 |
+
gps_coords_orginal = torch.tensor([example.original_lat, example.original_lon], dtype=torch.float32)
|
127 |
+
|
128 |
+
if self.useRegions and self.give_originals:
|
129 |
+
return image, gps_coords, gps_coords_orginal, region
|
130 |
+
elif self.useRegions:
|
131 |
+
return image, gps_coords, region
|
132 |
+
elif self.give_originals:
|
133 |
+
return image, gps_coords, gps_coords_orginal
|
134 |
+
else:
|
135 |
+
return image, gps_coords
|
136 |
+
|
137 |
+
class TensorDataset(Dataset):
|
138 |
+
def __init__(self, tensors, transform=None, lat_mean=None, lat_std=None, lon_mean=None, lon_std=None, useRegions=False, give_originals=False):
|
139 |
+
# self.hf_dataset = hf_dataset.map(
|
140 |
+
self.tensors = tensors
|
141 |
+
|
142 |
+
def __len__(self):
|
143 |
+
return len(self.tensors)
|
144 |
+
|
145 |
+
def __getitem__(self, idx):
|
146 |
+
# Extract data
|
147 |
+
image = self.tensors[idx]
|
148 |
+
return image
|
149 |
+
##################
|
150 |
+
transform = transforms.Compose([
|
151 |
+
#transforms.RandomResizedCrop(224), # Random crop and resize to 224x224
|
152 |
+
transforms.Resize((224, 224)),
|
153 |
+
transforms.RandomHorizontalFlip(), # Random horizontal flip
|
154 |
+
# transforms.RandomRotation(degrees=15), # Random rotation between -15 and 15 degrees
|
155 |
+
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1), # Random color jitter
|
156 |
+
transforms.ToTensor(),
|
157 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
158 |
+
std=[0.229, 0.224, 0.225])
|
159 |
+
])
|
160 |
+
|
161 |
+
# Optionally, you can create a separate transform for inference without augmentations
|
162 |
+
inference_transform = transforms.Compose([
|
163 |
+
transforms.Resize((224, 224)),
|
164 |
+
transforms.ToTensor(),
|
165 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
166 |
+
std=[0.229, 0.224, 0.225])
|
167 |
+
])
|
168 |
+
|
169 |
+
|
170 |
+
# Create the training dataset and dataloader
|
171 |
+
train_dataset = TensorDataset(input_tensor)
|
172 |
+
train_dataloader = DataLoader(train_dataset, batch_size=32, shuffle=True)
|
173 |
+
|
174 |
+
# lat_mean = train_dataset.latitude_mean
|
175 |
+
# lat_std = train_dataset.latitude_std
|
176 |
+
# lon_mean = train_dataset.longitude_mean
|
177 |
+
# lon_std = train_dataset.longitude_std
|
178 |
+
|
179 |
+
#####################
|
180 |
+
import torch
|
181 |
+
import torch.nn as nn
|
182 |
+
import torchvision.transforms as transforms
|
183 |
+
from torch.utils.data import DataLoader, Dataset
|
184 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
185 |
+
from huggingface_hub import PyTorchModelHubMixin
|
186 |
+
from PIL import Image
|
187 |
+
import os
|
188 |
+
import numpy as np
|
189 |
+
import json
|
190 |
+
import torchvision.models as models
|
191 |
+
##################
|
192 |
+
import torch.nn.functional as F
|
193 |
+
class_frequency = torch.zeros(7)
|
194 |
+
|
195 |
+
region_one_hot = F.one_hot(torch.tensor([0,1,2,3,4,5,6]), num_classes=7)
|
196 |
+
|
197 |
+
# for _, _, region in train_dataset:
|
198 |
+
# class_frequency += region_one_hot[region]
|
199 |
+
|
200 |
+
# print(class_frequency)
|
201 |
+
# class_weights = torch.full((7,), len(train_dataset)) / class_frequency
|
202 |
+
# class_weights = class_weights / torch.max(class_weights)
|
203 |
+
# print(class_weights)
|
204 |
+
class_weights = [0.2839, 0.4268, 0.5583, 0.3873, 1.0000, 0.6036, 0.6009]
|
205 |
+
#####################
|
206 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
207 |
+
print(f'Using device: {device}')
|
208 |
+
|
209 |
+
per_model_weights = []
|
210 |
+
with open(path_map['region_ensemble_weights.json'], 'r') as file:
|
211 |
+
per_model_weights = json.load(file)
|
212 |
+
|
213 |
+
search_stats = []
|
214 |
+
with open(path_map['best region models/model_histories.json'], 'r') as file:
|
215 |
+
search_stats = json.load(file)
|
216 |
+
|
217 |
+
my_models = []
|
218 |
+
|
219 |
+
for i, (path, _, _, _, _, _, _, _, _) in enumerate(search_stats):
|
220 |
+
path = path_map[path]
|
221 |
+
state_dict = torch.load(path)
|
222 |
+
|
223 |
+
region_model = models.resnet18(pretrained=False)
|
224 |
+
num_features = region_model.fc.in_features
|
225 |
+
region_model.fc = nn.Sequential(nn.Dropout(0.5),
|
226 |
+
nn.Linear(num_features, 7))
|
227 |
+
region_model.load_state_dict(state_dict)
|
228 |
+
|
229 |
+
region_model.cpu()
|
230 |
+
|
231 |
+
my_models.append(region_model)
|
232 |
+
|
233 |
+
per_model_weights = torch.tensor(per_model_weights).to(device)
|
234 |
+
#########
|
235 |
+
torch.cuda.empty_cache()
|
236 |
+
##########
|
237 |
+
predicted_object_lst = []
|
238 |
+
|
239 |
+
num_regions = 7
|
240 |
+
|
241 |
+
for images in train_dataloader:
|
242 |
+
images = images.to(device)
|
243 |
+
# gps_coords_original = gps_coords_original.to(device)
|
244 |
+
|
245 |
+
outputs = torch.zeros((images.shape[0], 7)).to(device)
|
246 |
+
|
247 |
+
for i, model in enumerate(my_models):
|
248 |
+
model.eval()
|
249 |
+
model.to(device)
|
250 |
+
|
251 |
+
model_outputs = model(images)
|
252 |
+
outputs += per_model_weights[i] * model_outputs
|
253 |
+
|
254 |
+
model.cpu()
|
255 |
+
# print(i, len(predicted_object_lst))
|
256 |
+
|
257 |
+
outputs /= len(my_models)
|
258 |
+
|
259 |
+
_, predicted_regions = torch.max(outputs, 1)
|
260 |
+
|
261 |
+
predicted_regions = predicted_regions.cpu().numpy()
|
262 |
+
images = images.cpu().numpy()
|
263 |
+
|
264 |
+
for i in range(len(predicted_regions)):
|
265 |
+
predicted_object = PredictedObject(images[i], -1, -1, predicted_regions[i])
|
266 |
+
predicted_object.predicted_region = predicted_regions[i]
|
267 |
+
predicted_object_lst.append(predicted_object)
|
268 |
+
|
269 |
+
torch.cuda.empty_cache()
|
270 |
+
#################
|
271 |
+
predicted_object_lst = sorted(predicted_object_lst)
|
272 |
+
|
273 |
+
po_predicted_region_lst = [[] for _ in range(7)]
|
274 |
+
|
275 |
+
for po in predicted_object_lst:
|
276 |
+
po.lat = po.original_lat
|
277 |
+
po.lon = po.original_lon
|
278 |
+
|
279 |
+
po_predicted_region_lst[po.predicted_region].append(po)
|
280 |
+
|
281 |
+
po_datasets = [PredictionObjectDataset(x, give_originals=True) for x in po_predicted_region_lst]
|
282 |
+
po_loaders = [DataLoader(x, batch_size=32, shuffle=False) for x in po_datasets]
|
283 |
+
|
284 |
+
# lat_mean_lst = [x.latitude_mean for x in po_datasets]
|
285 |
+
# lat_std_lst = [x.latitude_std for x in po_datasets]
|
286 |
+
# lon_mean_lst = [x.longitude_mean for x in po_datasets]
|
287 |
+
# lon_std_lst = [x.longitude_std for x in po_datasets]
|
288 |
+
|
289 |
+
############
|
290 |
+
from sklearn.metrics import mean_absolute_error, mean_squared_error
|
291 |
+
import torch.nn.functional as F
|
292 |
+
|
293 |
+
# all_preds = []
|
294 |
+
# all_actuals = []
|
295 |
+
all_preds_norm = []
|
296 |
+
# all_actuals_norm = []
|
297 |
+
# all_regions = []
|
298 |
+
|
299 |
+
for i in range(num_regions):
|
300 |
+
# print(f'region {i}')
|
301 |
+
# model_all_preds = []
|
302 |
+
# model_all_actuals = []
|
303 |
+
model_all_preds_norm = []
|
304 |
+
# model_all_actuals_norm = []
|
305 |
+
# model_all_regions = []
|
306 |
+
|
307 |
+
val_dataloader = po_loaders[i]
|
308 |
+
|
309 |
+
state_dict = torch.load(path_map[f'models/location_model_{i}.pth'])
|
310 |
+
|
311 |
+
model_loction = models.resnet18(pretrained=False)
|
312 |
+
num_features = model_loction.fc.in_features
|
313 |
+
model_loction.fc = nn.Linear(num_features, 2)
|
314 |
+
|
315 |
+
model_loction.load_state_dict(state_dict)
|
316 |
+
|
317 |
+
model_loction.to(device)
|
318 |
+
|
319 |
+
model_loction.eval()
|
320 |
+
with torch.no_grad():
|
321 |
+
for images, _, _ in val_dataloader:
|
322 |
+
images = images.to(device)
|
323 |
+
|
324 |
+
outputs = model_loction(images)
|
325 |
+
|
326 |
+
# Denormalize predictions and actual values
|
327 |
+
preds_norm = outputs.cpu()
|
328 |
+
# actuals_norm = gps_coords.cpu()
|
329 |
+
# preds = outputs.cpu() * torch.tensor([lat_std_lst[i], lon_std_lst[i]]) + torch.tensor([lat_mean_lst[i], lon_mean_lst[i]])
|
330 |
+
# actuals = gps_coords.cpu() * torch.tensor([lat_std_lst[i], lon_std_lst[i]]) + torch.tensor([lat_mean_lst[i], lon_mean_lst[i]])#gps_coords_original.cpu()
|
331 |
+
|
332 |
+
# model_all_preds.append(preds)
|
333 |
+
# model_all_actuals.append(actuals)
|
334 |
+
model_all_preds_norm.append(preds_norm)
|
335 |
+
# model_all_actuals_norm.append(actuals_norm)
|
336 |
+
# model_all_regions.extend([i for _ in range(len(images))])
|
337 |
+
|
338 |
+
# Concatenate all batches
|
339 |
+
# model_all_preds = torch.cat(model_all_preds)
|
340 |
+
# model_all_actuals = torch.cat(model_all_actuals)
|
341 |
+
model_all_preds_norm = torch.cat(model_all_preds_norm)
|
342 |
+
# model_all_actuals_norm = torch.cat(model_all_actuals_norm)
|
343 |
+
|
344 |
+
|
345 |
+
# Compute error metrics
|
346 |
+
# rmse = F.mse_loss(model_all_actuals_norm, model_all_preds_norm)
|
347 |
+
|
348 |
+
# model_all_preds = model_all_preds.numpy()
|
349 |
+
# model_all_actuals = model_all_actuals.numpy()
|
350 |
+
model_all_preds_norm = model_all_preds_norm.numpy()
|
351 |
+
# model_all_actuals_norm = model_all_actuals_norm.numpy()
|
352 |
+
|
353 |
+
# print(model_all_preds[0])
|
354 |
+
# print(model_all_actuals[0])
|
355 |
+
# print(model_all_preds_norm[0])
|
356 |
+
# print(model_all_actuals_norm[0])
|
357 |
+
|
358 |
+
# print(f'Mean Squared Error: {rmse}')
|
359 |
+
|
360 |
+
# all_preds.append([model_all_preds])
|
361 |
+
# all_actuals.append([model_all_actuals])
|
362 |
+
all_preds_norm.append([model_all_preds_norm])
|
363 |
+
# all_actuals_norm.append([model_all_actuals_norm])
|
364 |
+
# all_regions.append(model_all_regions)
|
365 |
+
|
366 |
+
del model_loction
|
367 |
+
torch.cuda.empty_cache()
|
368 |
+
############
|
369 |
+
# all_preds_denorm = all_preds
|
370 |
+
# all_actuals_denorm = all_actuals
|
371 |
+
all_preds = all_preds_norm
|
372 |
+
# all_actuals = all_actuals_norm
|
373 |
+
# all_regions = all_regions
|
374 |
+
|
375 |
+
def flatten(lst):
|
376 |
+
newlst = []
|
377 |
+
for sublst in lst:
|
378 |
+
for item in sublst:
|
379 |
+
newlst.append(item)
|
380 |
+
return newlst
|
381 |
+
|
382 |
+
all_preds = flatten(all_preds)
|
383 |
+
# all_actuals = flatten(all_actuals)
|
384 |
+
# all_preds_denorm = flatten(all_preds_denorm)
|
385 |
+
# all_actuals_denorm = flatten(all_actuals_denorm)
|
386 |
+
# all_regions = list(flatten(all_regions))
|
387 |
+
#############
|
388 |
+
# actual_denorm_y = []
|
389 |
+
# actual_denorm_x = []
|
390 |
+
# for x in all_actuals_denorm:
|
391 |
+
# for e in x:
|
392 |
+
# actual_denorm_x.append(e[0])
|
393 |
+
# actual_denorm_y.append(e[1])
|
394 |
+
# # actual_denorm_x.append(x[0])
|
395 |
+
# # actual_denorm_y.append(x[1])
|
396 |
+
|
397 |
+
# pred_denorm_y = []
|
398 |
+
# pred_denorm_x = []
|
399 |
+
# for x in all_preds_denorm:
|
400 |
+
# for e in x:
|
401 |
+
# pred_denorm_x.append(e[0])
|
402 |
+
# pred_denorm_y.append(e[1])
|
403 |
+
# # pred_denorm_x.append(x[0])
|
404 |
+
# # pred_denorm_y.append(x[1])
|
405 |
+
|
406 |
+
# actual_y = []
|
407 |
+
# actual_x = []
|
408 |
+
# for x in all_actuals:
|
409 |
+
# for e in x:
|
410 |
+
# actual_x.append(e[0])
|
411 |
+
# actual_y.append(e[1])
|
412 |
+
# # actual_x.append(x[0])
|
413 |
+
# # actual_y.append(x[1])
|
414 |
+
|
415 |
+
pred_y = []
|
416 |
+
pred_x = []
|
417 |
+
for x in all_preds:
|
418 |
+
for e in x:
|
419 |
+
pred_x.append(e[0])
|
420 |
+
pred_y.append(e[1])
|
421 |
+
############
|
422 |
+
t = torch.zeros((len(pred_x), 2))
|
423 |
+
t[:, 0] = torch.tensor(pred_x)
|
424 |
+
t[:, 1] = torch.tensor(pred_y)
|
425 |
+
return t
|
426 |
+
|
427 |
+
# import matplotlib.pyplot as plt
|
428 |
+
# from geopy.distance import geodesic
|
429 |
+
# import seaborn as sns
|
430 |
+
|
431 |
+
# print(pred_x)
|
432 |
+
# print(pred_y)
|
433 |
+
# print(actual_x)
|
434 |
+
# print(actual_y)
|
435 |
+
# print(pred_denorm_x)
|
436 |
+
# print(pred_denorm_y)
|
437 |
+
# print(actual_denorm_x)
|
438 |
+
# print(actual_denorm_y)
|
439 |
+
|
440 |
+
# plt.scatter(actual_denorm_y, actual_denorm_x, label='Actual', color='black', alpha=0.5)
|
441 |
+
# # plt.scatter(all_preds_denorm[:, 1], all_preds_denorm[:, 0], label='Predicted', color='blue', alpha=0.5)
|
442 |
+
|
443 |
+
# over100 = 0
|
444 |
+
# under100 = 0
|
445 |
+
# under50 = 0
|
446 |
+
# under25 = 0
|
447 |
+
|
448 |
+
# all_over100 = []
|
449 |
+
# all_under100 = []
|
450 |
+
# all_under50 = []
|
451 |
+
# all_under25 = []
|
452 |
+
# average_dist = 0.0
|
453 |
+
|
454 |
+
# dists = []
|
455 |
+
|
456 |
+
# for i in range(len(actual_denorm_x)):
|
457 |
+
# pred_denorm_loc = (pred_denorm_x[i], pred_denorm_y[i])
|
458 |
+
# actual_denorm_loc = (actual_denorm_x[i], actual_denorm_y[i])
|
459 |
+
|
460 |
+
# dist = geodesic(actual_denorm_loc, pred_denorm_loc).meters
|
461 |
+
# dists.append(dist)
|
462 |
+
|
463 |
+
# if dist > 50:
|
464 |
+
# over100 += 1
|
465 |
+
# all_over100.append(pred_denorm_loc)
|
466 |
+
# elif dist > 25:
|
467 |
+
# under100 += 1
|
468 |
+
# all_under100.append(pred_denorm_loc)
|
469 |
+
# elif dist > 10:
|
470 |
+
# under50 += 1
|
471 |
+
# all_under50.append(pred_denorm_loc)
|
472 |
+
# else:
|
473 |
+
# under25 += 1
|
474 |
+
# all_under25.append(pred_denorm_loc)
|
475 |
+
|
476 |
+
# plt.plot(
|
477 |
+
# [actual_denorm_y[i], pred_denorm_y[i]],
|
478 |
+
# [actual_denorm_x[i], pred_denorm_x[i]],
|
479 |
+
# color='grey',
|
480 |
+
# alpha=0.5,
|
481 |
+
# linewidth=0.5
|
482 |
+
# )
|
483 |
+
|
484 |
+
# dists = np.array(dists)
|
485 |
+
|
486 |
+
# plt.scatter([y for x,y in all_over100], [x for x,y in all_over100], label=f'over 50m: {over100}', color='red', alpha=0.5)
|
487 |
+
# plt.scatter([y for x,y in all_under100], [x for x,y in all_under100], label=f'under 50m: {under100}', color='orange', alpha=0.5)
|
488 |
+
# plt.scatter([y for x,y in all_under50], [x for x,y in all_under50], label=f'under 25m: {under50}', color='green', alpha=0.5)
|
489 |
+
# plt.scatter([y for x,y in all_under25], [x for x,y in all_under25], label=f'under 10m: {under25}', color='blue', alpha=0.5)
|
490 |
+
|
491 |
+
|
492 |
+
# plt.legend()
|
493 |
+
|
494 |
+
# plt.xlabel('Longitude')
|
495 |
+
# plt.ylabel('Latitude')
|
496 |
+
# plt.title('Actual vs. Predicted GPS Coordinates with Error Lines')
|
497 |
+
# plt.show()
|
498 |
+
|
499 |
+
# regions_enum = {0 : "fisher bennett",
|
500 |
+
# 1 : "outer quad",
|
501 |
+
# 2 : "outside football",
|
502 |
+
# 3 : "chem building",
|
503 |
+
# 4 : "top of walk",
|
504 |
+
# 5 : "bottom of walk",
|
505 |
+
# 6 : "chem courtyard",
|
506 |
+
# 7 : "no assigned region"}
|
507 |
+
|
508 |
+
# colors = {0:'red',
|
509 |
+
# 1:'orange',
|
510 |
+
# 2:'yellow',
|
511 |
+
# 3:'green',
|
512 |
+
# 4:'blue',
|
513 |
+
# 5:'purple',
|
514 |
+
# 6:'pink',
|
515 |
+
# 7:'black'}
|
516 |
+
|
517 |
+
# for i in range(len(actual_denorm_x)):
|
518 |
+
|
519 |
+
# plt.plot(
|
520 |
+
# [actual_denorm_y[i], pred_denorm_y[i]],
|
521 |
+
# [actual_denorm_x[i], pred_denorm_x[i]],
|
522 |
+
# color='grey',
|
523 |
+
# alpha=0.25,
|
524 |
+
# linewidth=0.5
|
525 |
+
# )
|
526 |
+
|
527 |
+
# # plt.scatter([p[0] for p in pts], [p[1] for p in pts], s=15, c=[colors[i] for i in all_regions], edgecolors='black')
|
528 |
+
# colors_lst = [colors[i] for i in all_regions]
|
529 |
+
# plt.scatter(actual_denorm_y, actual_denorm_x, label='Actual', color=colors_lst, alpha=0.5)
|
530 |
+
# plt.scatter(pred_denorm_y, pred_denorm_x, label='Predicted', color=colors_lst, alpha=0.5)
|
531 |
+
# # plt.gca().invert_xaxis()
|
532 |
+
|
533 |
+
# plt.show()
|
534 |
+
|
535 |
+
# # Plot the distribution
|
536 |
+
# plt.figure(figsize=(10, 6))
|
537 |
+
# sns.histplot(dists, bins=30, kde=True, color='blue', alpha=0.7)
|
538 |
+
|
539 |
+
# # Add labels and title
|
540 |
+
# plt.title("Distribution of Geodesic Distances (Accuracy of Guesses)")
|
541 |
+
# plt.xlabel("Geodesic Distance (meters)")
|
542 |
+
# plt.ylabel("Frequency")
|
543 |
+
|
544 |
+
# # Add mean and median lines for context
|
545 |
+
# mean_distance = dists.mean()
|
546 |
+
# median_distance = np.median(dists)
|
547 |
+
# plt.axvline(mean_distance, color='red', linestyle='--', label=f'Mean: {mean_distance:.2f} meters')
|
548 |
+
# plt.axvline(median_distance, color='green', linestyle='--', label=f'Median: {median_distance:.2f} meters')
|
549 |
+
|
550 |
+
# plt.legend()
|
551 |
+
# plt.grid(True)
|
552 |
+
# plt.show()
|
553 |
+
|
554 |
+
torch.cuda.empty_cache()
|
555 |
+
predict_from_model(input)
|
556 |
+
```
|