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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Image to GPS Project - ConvNext, MobileNet and EfficientNet Ensemble
|
| 2 |
+
```bash
|
| 3 |
+
## Training Data Statistics
|
| 4 |
+
lat_mean = 39.951537011424264
|
| 5 |
+
lat_std = 0.0006940325318781937
|
| 6 |
+
lon_mean = -75.19152009539549
|
| 7 |
+
lon_std = 0.0007607716964655242
|
| 8 |
+
```
|
| 9 |
+
|
| 10 |
+
## How to Load the Model and Perform Inference
|
| 11 |
+
```bash
|
| 12 |
+
# install dependencies
|
| 13 |
+
pip install geopy datasets torch torchvision huggingface_hub
|
| 14 |
+
# import packages
|
| 15 |
+
import numpy as np
|
| 16 |
+
from geopy.distance import geodesic
|
| 17 |
+
import torch
|
| 18 |
+
from torch.utils.data import DataLoader, Dataset
|
| 19 |
+
from torchvision import transforms
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
from torchvision.models import mobilenet_v2, MobileNet_V2_Weights, convnext_tiny, ConvNeXt_Tiny_Weights, efficientnet_b0, EfficientNet_B0_Weights
|
| 22 |
+
from datasets import load_dataset
|
| 23 |
+
from huggingface_hub import hf_hub_download
|
| 24 |
+
# load the model
|
| 25 |
+
repo_id = "cis519projectA/Ensemble_ConvNeXt_MobileNet_EfficientNet_Weight_Adjustment"
|
| 26 |
+
filename = "custom_ensemble_weight_adjust.pth"
|
| 27 |
+
model_path = hf_hub_download(repo_id=repo_id, filename=filename)
|
| 28 |
+
# define models
|
| 29 |
+
class CustomEfficientNetModel(nn.Module):
|
| 30 |
+
def __init__(self, weights=EfficientNet_B0_Weights.DEFAULT, num_classes=2):
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.efficientnet = efficientnet_b0(weights=weights)
|
| 33 |
+
in_features = self.efficientnet.classifier[1].in_features
|
| 34 |
+
self.efficientnet.classifier = nn.Sequential(
|
| 35 |
+
nn.Linear(in_features, 512),
|
| 36 |
+
nn.ReLU(),
|
| 37 |
+
nn.Dropout(p=0.3),
|
| 38 |
+
nn.Linear(512, num_classes)
|
| 39 |
+
)
|
| 40 |
+
for param in self.efficientnet.features[:3].parameters():
|
| 41 |
+
param.requires_grad = False
|
| 42 |
+
|
| 43 |
+
def forward(self, x):
|
| 44 |
+
return self.efficientnet(x)
|
| 45 |
+
|
| 46 |
+
class CustomConvNeXtModel(nn.Module):
|
| 47 |
+
def __init__(self, weights=ConvNeXt_Tiny_Weights.DEFAULT, num_classes=2):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.convnext = convnext_tiny(weights=weights)
|
| 50 |
+
in_features = self.convnext.classifier[2].in_features
|
| 51 |
+
self.convnext.classifier = nn.Sequential(
|
| 52 |
+
nn.AdaptiveAvgPool2d(1),
|
| 53 |
+
nn.Flatten(),
|
| 54 |
+
nn.Linear(in_features, 512),
|
| 55 |
+
nn.BatchNorm1d(512),
|
| 56 |
+
nn.ReLU(),
|
| 57 |
+
nn.Dropout(p=0.3),
|
| 58 |
+
nn.Linear(512, num_classes)
|
| 59 |
+
)
|
| 60 |
+
for param in self.convnext.features[:4].parameters():
|
| 61 |
+
param.requires_grad = False
|
| 62 |
+
def forward(self, x):
|
| 63 |
+
return self.convnext(x)
|
| 64 |
+
|
| 65 |
+
class CustomMobileNetModel(nn.Module):
|
| 66 |
+
def __init__(self, weights=MobileNet_V2_Weights.DEFAULT, num_classes=2):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.mobilenet = mobilenet_v2(weights=weights)
|
| 69 |
+
in_features = self.mobilenet.classifier[1].in_features
|
| 70 |
+
self.mobilenet.classifier = nn.Sequential(
|
| 71 |
+
nn.Linear(in_features, 1024),
|
| 72 |
+
nn.ReLU(),
|
| 73 |
+
nn.Dropout(p=0.5),
|
| 74 |
+
nn.Linear(1024, 512),
|
| 75 |
+
nn.ReLU(),
|
| 76 |
+
nn.Dropout(p=0.5),
|
| 77 |
+
nn.Linear(512, num_classes)
|
| 78 |
+
)
|
| 79 |
+
for param in self.mobilenet.features[:5].parameters():
|
| 80 |
+
param.requires_grad = False
|
| 81 |
+
|
| 82 |
+
def forward(self, x):
|
| 83 |
+
return self.mobilenet(x)
|
| 84 |
+
|
| 85 |
+
class EnsembleModel(nn.Module):
|
| 86 |
+
def __init__(self, convnext_model, mobilenet_model, efficientnet_model, num_classes=2):
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.convnext = convnext_model
|
| 89 |
+
self.mobilenet = mobilenet_model
|
| 90 |
+
self.efficientnet = efficientnet_model
|
| 91 |
+
self.weight_convnext = nn.Parameter(torch.tensor(1.0))
|
| 92 |
+
self.weight_mobilenet = nn.Parameter(torch.tensor(1.0))
|
| 93 |
+
self.weight_efficientnet = nn.Parameter(torch.tensor(1.0))
|
| 94 |
+
self.fc = nn.Sequential(
|
| 95 |
+
nn.Linear(num_classes * 3, 512),
|
| 96 |
+
nn.ReLU(),
|
| 97 |
+
nn.Dropout(p=0.3),
|
| 98 |
+
nn.Linear(512, num_classes)
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def forward(self, x):
|
| 102 |
+
convnext_out = self.convnext(x)
|
| 103 |
+
mobilenet_out = self.mobilenet(x)
|
| 104 |
+
efficientnet_out = self.efficientnet(x)
|
| 105 |
+
weights = torch.softmax(torch.stack([self.weight_convnext, self.weight_mobilenet, self.weight_efficientnet]), dim=0)
|
| 106 |
+
combined = (weights[0] * convnext_out +
|
| 107 |
+
weights[1] * mobilenet_out +
|
| 108 |
+
weights[2] * efficientnet_out)
|
| 109 |
+
return combined
|
| 110 |
+
|
| 111 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 112 |
+
convnext_model = CustomConvNeXtModel(weights=ConvNeXt_Tiny_Weights.DEFAULT, num_classes=2)
|
| 113 |
+
mobilenet_model = CustomMobileNetModel(weights=MobileNet_V2_Weights.DEFAULT, num_classes=2)
|
| 114 |
+
efficientnet_model = CustomEfficientNetModel(weights=EfficientNet_B0_Weights.DEFAULT, num_classes=2)
|
| 115 |
+
ensemble_model = EnsembleModel(convnext_model, mobilenet_model, efficientnet_model, num_classes=2).to(device)
|
| 116 |
+
# load the model weights
|
| 117 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 118 |
+
state_dict = torch.load(model_path, map_location=device)
|
| 119 |
+
ensemble_model.load_state_dict(state_dict)
|
| 120 |
+
ensemble_model.to(device)
|
| 121 |
+
ensemble_model.eval()
|
| 122 |
+
# load the dataset
|
| 123 |
+
dataset_test = load_dataset("gydou/released_img", split="train")
|
| 124 |
+
# define transformers
|
| 125 |
+
inference_transform = transforms.Compose([
|
| 126 |
+
transforms.Resize((224, 224)),
|
| 127 |
+
transforms.ToTensor(),
|
| 128 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 129 |
+
])
|
| 130 |
+
# Parameters for denormalization
|
| 131 |
+
lat_mean = 39.951537011424264
|
| 132 |
+
lat_std = 0.0006940325318781937
|
| 133 |
+
lon_mean = -75.19152009539549
|
| 134 |
+
lon_std = 0.0007607716964655242
|
| 135 |
+
class GPSImageDataset(Dataset):
|
| 136 |
+
def __init__(self, hf_dataset, transform=None, lat_mean=None, lat_std=None, lon_mean=None, lon_std=None):
|
| 137 |
+
self.hf_dataset = hf_dataset
|
| 138 |
+
self.transform = transform
|
| 139 |
+
self.latitude_mean = lat_mean
|
| 140 |
+
self.latitude_std = lat_std
|
| 141 |
+
self.longitude_mean = lon_mean
|
| 142 |
+
self.longitude_std = lon_std
|
| 143 |
+
def __len__(self):
|
| 144 |
+
return len(self.hf_dataset)
|
| 145 |
+
def __getitem__(self, idx):
|
| 146 |
+
example = self.hf_dataset[idx]
|
| 147 |
+
image = example['image']
|
| 148 |
+
latitude = example['Latitude']
|
| 149 |
+
longitude = example['Longitude']
|
| 150 |
+
if self.transform:
|
| 151 |
+
image = self.transform(image)
|
| 152 |
+
latitude = (latitude - self.latitude_mean) / self.latitude_std
|
| 153 |
+
longitude = (longitude - self.longitude_mean) / self.longitude_std
|
| 154 |
+
gps_coords = torch.tensor([latitude, longitude], dtype=torch.float32)
|
| 155 |
+
return image, gps_coords
|
| 156 |
+
# transform test data
|
| 157 |
+
test_dataset = GPSImageDataset(
|
| 158 |
+
hf_dataset=dataset_test,
|
| 159 |
+
transform=inference_transform,
|
| 160 |
+
lat_mean=lat_mean,
|
| 161 |
+
lat_std=lat_std,
|
| 162 |
+
lon_mean=lon_mean,
|
| 163 |
+
lon_std=lon_std
|
| 164 |
+
)
|
| 165 |
+
test_dataloader = DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)
|
| 166 |
+
# evaluate
|
| 167 |
+
def evaluate_model_single_batch(model, dataloader, lat_mean, lat_std, lon_mean, lon_std):
|
| 168 |
+
all_distances = []
|
| 169 |
+
model.eval()
|
| 170 |
+
with torch.no_grad():
|
| 171 |
+
for batch_idx, (images, gps_coords) in enumerate(dataloader):
|
| 172 |
+
images, gps_coords = images.to(device), gps_coords.to(device)
|
| 173 |
+
outputs = model(images)
|
| 174 |
+
preds_denorm = outputs.cpu().numpy() * np.array([lat_std, lon_std]) + np.array([lat_mean, lon_mean])
|
| 175 |
+
actuals_denorm = gps_coords.cpu().numpy() * np.array([lat_std, lon_std]) + np.array([lat_mean, lon_mean])
|
| 176 |
+
for pred, actual in zip(preds_denorm, actuals_denorm):
|
| 177 |
+
distance = geodesic((actual[0], actual[1]), (pred[0], pred[1])).meters
|
| 178 |
+
all_distances.append(distance)
|
| 179 |
+
break
|
| 180 |
+
mean_error = np.mean(all_distances)
|
| 181 |
+
rmse_error = np.sqrt(np.mean(np.square(all_distances)))
|
| 182 |
+
return mean_error, rmse_error
|
| 183 |
+
# Evaluate using only one batch
|
| 184 |
+
mean_error, rmse_error = evaluate_model_single_batch(
|
| 185 |
+
ensemble_model, test_dataloader, lat_mean, lat_std, lon_mean, lon_std
|
| 186 |
+
)
|
| 187 |
+
print(f"Mean Error (meters): {mean_error:.2f}, RMSE (meters): {rmse_error:.2f}")
|
| 188 |
+
```
|