Views
No views yet
1!pip install geopy > delete.txt
2!pip install datasets > delete.txt
3!pip install torch torchvision datasets > delete.txt
4!pip install huggingface_hub > delete.txt
5!rm delete.txt
6!pip install transformers
7!pip install geopy
8
9import getpass
10from huggingface_hub import notebook_login
11# Securely input the Hugging Face token
12token = getpass.getpass("Enter your Hugging Face token: ")
13# Log in to Hugging Face Hub
14notebook_login(token)
15
16from huggingface_hub import hf_hub_download
17import torch
18from huggingface_hub import HfApi, HfFolder, Repository
19# Specify the repository and the filename of the model you want to load
20repo_id = "cis519-Image2GPS/ImageToGPSproject_resnet18_layer" # Replace with your repo name
21filename = "resnet_gps_regressor_complete.pth"
22model_path = hf_hub_download(repo_id=repo_id, filename=filename)
23# Load the model using torch
24model_test = torch.load(model_path)
25model_test.eval() # Set the model to evaluation mode
26
27from datasets import load_dataset, Image
28dataset_test = load_dataset("gydou/released_img", split="train")
29
30import torchvision.transforms as transforms
31import numpy as np
32from geopy.distance import geodesic
33device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
34transform = transforms.Compose([
35 transforms.RandomResizedCrop(224), # Random crop and resize to 224x224
36 transforms.RandomHorizontalFlip(), # Random horizontal flip
37 # transforms.RandomRotation(degrees=15), # Random rotation between -15 and 15 degrees
38 transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1), # Random color jitter
39 transforms.ToTensor(),
40 transforms.Normalize(mean=[0.485, 0.456, 0.406],
41 std=[0.229, 0.224, 0.225])
42])
43inference_transform = transforms.Compose([
44 transforms.Resize((224, 224)),
45 transforms.ToTensor(),
46 transforms.Normalize(mean=[0.485, 0.456, 0.406],
47 std=[0.229, 0.224, 0.225])
48])
49with torch.no_grad():
50 for data in dataset_test:
51 image = inference_transform(data["image"]).unsqueeze(0).to(device)
52 outputs = model_test(image)
53 # print("Predicted latitude & longitude:", outputs.cpu().numpy())
54lat_mean = 39.95169318421053
55lat_std = 0.0007139636196696079
56lon_mean = -75.19131129824562
57lon_std = 0.0006948352800088026
58all_distances = []
59model_test.eval()
60with torch.no_grad():
61 for data in dataset_test:
62 image = transform(data["image"]).unsqueeze(0).to(device)
63 outputs = model_test(image).cpu().numpy()
64 preds_denorm = outputs * np.array([lat_std, lon_std]) + np.array([lat_mean, lon_mean])
65 actual = [data["Latitude"], data["Longitude"]]
66 distance = geodesic(actual, preds_denorm[0]).meters
67 all_distances.append(distance)
68mean_error = np.mean(all_distances)
69rmse_error = np.sqrt(np.mean(np.square(all_distances)))
70print('mean_error: ', mean_error)
71print('rmse_error: ', rmse_error)
72