How to Improve Holiday Itinerary with Machine Learning

jingles.dev
Perfect your travel plans with this strategy - use machine learning to optimize your holiday itinerary!

In October 2019, my friends and I are planning our awesome holiday in Greece and Amalfi. The way we plan our perfect holiday itinerary is by using Google Map. We search for the places to visit and pin markers on Google Map for attractions that might interest us.

For me, to optimise our vacation to the fullest, as to cover as much ground as possible; I have three questions:

  • How many days should I spend at one location?
  • Which attractions/locations should I visit each day?
  • What is the most optimal route from a place to another?

Let me show you the itinerary my algorithms have proposed for us. It is recommending the best sequence of places to visit, day by day.

jingles.dev
  • Start from Athens, visit the Acropolis and other historic archaeological sites. That’s a great start!
  • Travel to Santorini, a beautiful island with whitewashed homes and picture-perfect sunsets.
  • Sail to Crete, for a road trip adventure of a lifetime, by exploring hidden corners and tasting the best of Greek cuisine.
  • Fly to Italy and travel to Amalfi and Ravello where the terraces are blending along the cliffs with the most spectacular coastal scenery.
  • Travel to Sorrento and Naples, indulge in the best pasta, pizza, limoncello, and gelato.

Great holiday itinerary isn’t it?! This sequence of locations is fully generated by the algorithm. Would you like to try this for your next holiday? I have the codes ready for you.

In this article, I am going to show you exactly how you can do it too for your next vacation!

View of Atrani, while hiking to Ravello [photo by

View of Atrani, while hiking to Ravello [photo by Jingles]

Preparation

Pin locations on Google Maps. Visit My Maps and create a new map for your next holiday destination. Look for places you want to visit. Attractions? Theme parks? Restaurants? Fill up your map with markers by searching for these places and “Add to map”. Keep doing this until you have all the places you want to visit on the map. I will wait for you.

jingles.devjingles.dev

Export map and upload into Colab. After all the hard work of researching and pinning places to visit, we are ready to export the map. Select “Export to KML/KMZ”, and remember to check “Export as KML”. You will download a KML file.

Export KML file from Export KML file from Export KML file from

Export KML file from Google Maps and upload it in Colab

Next, go to Colab, an excellent Notebook environment maintained by Google. Open the File drawer on the left and upload the KML file which you have downloaded. We will be loading this KML file with BeautifulSoup later.

Get the Google API key. We will be plotting markers on Google Maps, so we need an API key. You can get it from the developers API page. Follow the instructions and you should get a key that looks like this:

ZIzkSyDwhp5B0_tH1$Is@fAkeAp1keY3eLYmPLY

Psst: this is a fake API key 🙃

Amalfi, Italy [photo by

Amalfi, Italy [photo by Tan Ying Ying]

Code walkthrough on Colab

You can get the codes and run it on Colab.

Define the parameters. Let’s set the API key, KML filename, and the desired number of days for your long-awaited holiday.

The API key is for plotting interactive Google Maps on Colab. The KML file contains the places of interests you have pinned on Google Maps. And lastly, the algorithm will determine where you should visit for each day based on the number of days you have set.

jingles.dev

Load the data. KML files are XML, and we can parse it with BeautifulSoup. Our places of interests are inside the “Placemark” tag, so we will extract the “name”, and “coordinates” from each “Placemark”.

places = []

with open(kml_filename, "r") as file:
    content = file.readlines()
    content = "".join(content)
    bs_content = BeautifulSoup(content, "xml")

    placemarks = bs_content.findAll('Placemark')
    for placemark in placemarks:

        coordinates = placemark.find('coordinates').text.strip()
        long = coordinates.split(',')[0]
        lat = coordinates.split(',')[1]

        places.append({
            'name': placemark.find('name').text.strip(),
            'lat': lat,
            'long': long
        })

places = pd.DataFrame(places)
places['lat'] = places['lat'].astype(float)
places['long'] = places['long'].astype(float)

mean_lat = places['lat'].mean()
mean_long = places['long'].mean()

places

Let’s see if the DataFrame contains places we are planning to visit.

NameLatitudeLongitude
Athens International Airport37.935646723.9484156
Ancient Agora of Athens37.974650723.7219716
Tzistarakis Mosque37.975920423
Roman Forum37.974374923.7255435
Theatre of Dionysus37.970365823.7278553
Parthenon37.971528523.7267166
Acropolis Museum37.968449923.7285227
Temple of Olympian Zeus37.969323
Plaka37.972552923.7303363999999
Temple of Zeus37.969283823.7331012
.........

Group locations by proximity. With the coordinates for each location in the DataFrame, we can group them into clusters. If two places are near each other, they will be in the same cluster. There are a few methods for clustering, I will introduce K-Means, spectral and mean-shift clustering.

K-Means clustering aims to partition data points into a specified number of clusters. In which each data point belongs to the cluster that it is nearest to.

Spectral clustering is useful when the structure of the individual clusters is highly non-convex. It performs dimensionality reduction before clustering in fewer dimensions.

Mean shift clustering is a centroid-based algorithm which aims to discover blobs in a smooth density of data points. It works by updating candidates for centroids to be the mean of the points within a region.

## KMeans
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=int(num_days), random_state=0).fit(places_lat_long)
group = list(kmeans.labels_)

## MeanShift
from sklearn.cluster import MeanShift, estimate_bandwidth
bandwidth = estimate_bandwidth(places_lat_long, quantile=0.2)
clustering = MeanShift(bandwidth=bandwidth).fit(places_lat_long)
group = clustering.labels_

## SpectralClustering
from sklearn.cluster import SpectralClustering
clustering = SpectralClustering(n_clusters=9,
         assign_labels="discretize",
         random_state=0).fit(places_lat_long)
group = clustering.labels_

Which one did I end up using? K-Means. Because it is straight forward, and the most common one.

Plot it on Google Maps! Now, we are ready to plot it on Google Maps to visualise the 12 main areas (because we are planning a holiday for 12 days). If you are running this on Colab, this map is interactive.

Athens. Santorini and Crete. Amalfi and Naples.Athens. Santorini and Crete. Amalfi and Naples.Athens. Santorini and Crete. Amalfi and Naples.

Athens. Santorini and Crete. Amalfi and Naples.

The clustering algorithm did a great job grouping locations by proximity. Next, I am interested in finding out the most optimal route from a region to another region.

Find the middle of each cluster. We need to find the middle point of each cluster. We do this with Pandas groupby function:

places.groupby(‘cluster’).mean()

That will give us a DataFrame, where each row represents a cluster of locations, and it’s latitude and longitude.

ClusterLatitudeLongitude
040.84639514.281423
136.41188125.418702
237.95853523.747617
335.35907324.500997
435.44929123.570038
540.64534714.610990
635.32540325.158296
735.51723224.019294
840.62734514.400411
935.05145524.814546
1035.20433625.454937
1135.22006724.019934

Find the distance between cluster. We need to find the distance between each cluster. We use the middle point of each cluster and calculate the distance between clusters with Scipy cdist function.

from scipy.spatial.distance import cdist

distance_matrix = cdist(
    mean_lat_long_by_group.values,
    mean_lat_long_by_group.values
)

df_distance_matrix = pd.DataFrame(distance_matrix)
df_distance_matrix

That will give us a DataFrame, with the distance of each cluster to every other cluster. We will call this matrix the distance matrix. Each value represents the distance between two clusters. A smaller value means the cluster is closer to each other.

01234567891011
00.00000011.9876569.89689711.59958610.7427700.38605012.19785811.1007260.24928112.02198112.51719811.246962
111.9876560.0000002.2769861.3966342.08425911.6072771.1172491.66094511.7971551.4885431.2080881.837654
29.8968972.2769860.0000002.7064332.5155209.5234932.9872062.4563739.7207413.0966843.2404562.751974
311.5995861.3966342.7064330.0000000.93532111.2141400.6581610.50700311.3919500.4392520.9664090.500744
410.7427702.0842592.5155200.9353210.00000010.3568111.5930830.45436510.5306361.3065511.9007500.504926
50.38605011.6072779.52349311.21414010.3568110.00000011.81302210.7151180.21134711.63633112.13242810.861026
612.1978581.1172492.9872060.6581611.59308311.8130220.0000001.15504311.9934430.4395580.3203951.143226
711.1007261.6609452.4563730.5070030.45436510.7151181.1550430.00000010.8920230.9216151.4693450.297166
80.24928111.7971559.72074111.39195010.5306360.21134711.99344310.8920230.00000011.81290612.31306511.035120
912.0219811.4885433.0966840.4392521.30655111.6363310.4395580.92161511.8129060.0000000.6583870.812305
1012.5171981.2080883.2404560.9664091.90075012.1324280.3203951.46934512.3130650.6583870.0000001.435090
1111.2469621.8376542.7519740.5007440.50492610.8610261.1432260.29716611.0351200.8123051.4350900.000000

Find the shortest route. With that distance matrix, we are ready to find the shortest path. Here is the code to compute the shortest path.

starting_point = 2 #@param {type:"integer"}
cur_index = starting_point

seq = [cur_index]
while len(seq) < len(list(df_distance_matrix.keys())):
    nearest_clusters = list(df_distance_matrix[cur_index].sort_values().index)
    for cluster_id in nearest_clusters:
        if cluster_id != cur_index and cluster_id not in seq:
            seq.append(cluster_id)
            cur_index = cluster_id
            break

replace_group_to_day = {}

for i in range(0, len(seq)):
    replace_group_to_day[seq[i]] = i

print(' -> '.join(str(x) for x in seq))

places['days'] = places['cluster']
places['days'].replace(replace_group_to_day, inplace=True)
places['days'] += 1

Initially, I was using the travelling salesman algorithm, but I find that the code’s a little overkill and overcomplicated, so I wrote my own instead. This is the result based on the shortest path algorithm, a sequence from cluster to cluster.

2 -> 1 -> 6 -> 10 -> 9 -> 3 -> 11 -> 7 -> 4 -> 5 -> 8 -> 0

Show the recommended itinerary. Now we are ready to plot our markers on Google Map. It has recommended us to go from Athens, Santorini, and Crete. Then to Amalfi, Ravello, Sorrento and Naples. If you are running this on Colab, this map is interactive.

Start with Athens, Santorini, and then Crete. To Amalfi, Ravello, Sorrento and
Naples.Start with Athens, Santorini, and then Crete. To Amalfi, Ravello, Sorrento and
Naples.Start with Athens, Santorini, and then Crete. To Amalfi, Ravello, Sorrento and
Naples.

Start with Athens, Santorini, and then Crete. To Amalfi, Ravello, Sorrento and Naples.

Start with Athens, Santorini, and then Crete. To Amalfi, Ravello, Sorrento and
Naples.Start with Athens, Santorini, and then Crete. To Amalfi, Ravello, Sorrento and
Naples.

Start with Athens, Santorini, and then Crete. To Amalfi, Ravello, Sorrento and Naples.

If you prefer to see it in tabular form, we can display it with Pandas.

pd.set_option(‘display.max_rows’, None)
places.sort_values(by=[‘days’])
Oia, Santorini, Greece [photo by

Oia, Santorini, Greece [photo by Clement Lim]

What can be improved?

This algorithm does not take the number of attractions in one region into consideration. For instance, we absolutely didn’t want to explore everything in Athens in one day! Neither is just one day at Santorini enough.

We need a type of clustering algorithm that constraint on the maximum number of points in a cluster. Such that, every cluster should have about the same number of locations. If a cluster is becoming too dense, it will split the cluster into two or more clusters.

But if you are travelling in one city, the result can be promising. This is the generated itinerary for New York City. Feel free to download my itinerary and try it for yourself.

New York City [photo by

New York City [photo by Jingles]


Resources

Do you want to try this for your next vacation? Here’s the code. You’re welcome. 😉

Not sure where to visit in Greece or Amalfi? Go ahead and use our Greece x Amalfi itinerary.

Not sure where to visit in New York City?

Thanks for reading. 😃
Hope you enjoyed reading this article as much as I did preparing it.