Explore and create ML datasets

In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.

Learning Objectives

  • Access and explore a public BigQuery dataset on NYC Taxi Cab rides
  • Visualize your dataset using the Seaborn library
  • Inspect and clean-up the dataset for future ML model training
  • Create a benchmark to judge future ML model performance off of

Each learning objective will correspond to a #TODO in the student lab notebook -- try to complete that notebook first before reviewing this solution notebook.

Let's start off with the Python imports that we need.


In [ ]:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst

In [ ]:
!pip install tensorflow==2.1 --user

Please ignore any compatibility warnings and errors Make sure to restart your kernel to ensure this change has taken place.


In [28]:
from google.cloud import bigquery
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import shutil

Extract sample data from BigQuery

The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.

Let's write a SQL query to pick up interesting fields from the dataset. It's a good idea to get the timestamp in a predictable format.


In [29]:
%%bigquery
  SELECT
    FORMAT_TIMESTAMP("%Y-%m-%d %H:%M:%S %Z", pickup_datetime) AS pickup_datetime,
    pickup_longitude, pickup_latitude, dropoff_longitude,
    dropoff_latitude, passenger_count, trip_distance, tolls_amount, 
    fare_amount, total_amount 
  FROM `nyc-tlc.yellow.trips`
  LIMIT 10


Out[29]:
pickup_datetime pickup_longitude pickup_latitude dropoff_longitude dropoff_latitude passenger_count trip_distance tolls_amount fare_amount total_amount
0 2010-02-23 21:59:00 UTC -73.991735 40.749720 -74.036432 40.721977 2 4.76 0.0 0.0 0.0
1 2010-02-11 15:34:00 UTC -73.814107 40.783290 -73.814107 40.783290 1 0.00 0.0 0.0 0.0
2 2010-02-15 16:32:26 UTC -73.805962 40.660588 -73.790219 40.643711 1 1.70 0.0 0.0 0.0
3 2015-01-11 00:45:11 UTC -73.937401 40.758141 -73.937416 40.758152 1 0.00 0.0 0.0 0.0
4 2015-03-03 07:05:03 UTC 0.000000 0.000000 -73.937386 40.758125 1 0.00 0.0 0.0 0.0
5 2010-02-20 10:49:49 UTC -73.972535 40.742314 -73.973257 40.744575 1 0.20 0.0 0.0 0.0
6 2015-01-30 12:31:51 UTC -73.937531 40.758083 -73.937531 40.758102 1 0.00 0.0 0.0 0.0
7 2010-02-05 19:41:58 UTC -73.994528 40.755783 -73.782418 40.648799 4 20.40 0.0 0.0 0.0
8 2015-02-21 13:52:50 UTC -73.937576 40.758129 -73.937599 40.758129 1 0.00 0.0 0.0 0.0
9 2010-02-02 17:42:18 UTC -73.961086 40.779176 -73.961455 40.779421 1 0.30 0.0 0.0 0.0

Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this.

We will also store the BigQuery result in a Pandas dataframe named "trips"


In [30]:
%%bigquery trips
  SELECT
    FORMAT_TIMESTAMP("%Y-%m-%d %H:%M:%S %Z", pickup_datetime) AS pickup_datetime,
    pickup_longitude, pickup_latitude, 
    dropoff_longitude, dropoff_latitude,
    passenger_count,
    trip_distance,
    tolls_amount,
    fare_amount,
    total_amount
  FROM
    `nyc-tlc.yellow.trips`
  WHERE
    ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 100000)) = 1

In [31]:
print(len(trips))


10789

In [32]:
# We can slice Pandas dataframes as if they were arrays
trips[:10]


Out[32]:
pickup_datetime pickup_longitude pickup_latitude dropoff_longitude dropoff_latitude passenger_count trip_distance tolls_amount fare_amount total_amount
0 2012-03-30 18:28:20 UTC -73.976148 40.776154 -74.010156 40.715113 1 5.70 0.00 17.3 18.80
1 2013-08-21 23:14:38 UTC -73.783667 40.648622 -73.918375 40.700288 2 10.30 0.00 32.0 37.00
2 2011-06-04 02:52:10 UTC -73.984681 40.769893 -74.007312 40.705326 1 5.30 0.00 15.3 16.30
3 2014-05-20 23:09:00 UTC -73.995203 40.727307 -73.948775 40.813487 1 10.31 0.00 33.5 38.00
4 2013-12-21 06:21:00 UTC -73.949725 40.827642 -74.005040 40.721567 6 8.71 0.00 27.0 30.50
5 2011-12-15 23:27:26 UTC -73.862671 40.768860 -73.983170 40.696372 1 10.00 0.00 22.5 27.00
6 2015-02-17 21:29:49 UTC -73.976730 40.754822 -73.946434 40.725193 2 7.12 0.00 24.0 30.36
7 2014-10-28 06:59:59 UTC -73.953121 40.791453 -73.974214 40.739858 1 4.70 0.00 19.5 25.00
8 2014-10-06 15:16:00 UTC -73.980130 40.760910 -73.861730 40.768330 2 11.47 5.33 36.5 47.33
9 2014-12-08 21:50:00 UTC -73.870867 40.773782 -74.003297 40.708215 2 11.81 0.00 33.5 37.50

Exploring data

Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering.


In [33]:
ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips)
ax.figure.set_size_inches(10, 8)


Hmm ... do you see something wrong with the data that needs addressing?

It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).

Note the extra WHERE clauses.


In [34]:
%%bigquery trips
  SELECT
    FORMAT_TIMESTAMP("%Y-%m-%d %H:%M:%S %Z", pickup_datetime) AS pickup_datetime,
    pickup_longitude, pickup_latitude, 
    dropoff_longitude, dropoff_latitude,
    passenger_count,
    trip_distance,
    tolls_amount,
    fare_amount,
    total_amount
  FROM
    `nyc-tlc.yellow.trips`
  WHERE
    ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 100000)) = 1
    AND trip_distance > 0 AND fare_amount >= 2.5

In [35]:
print(len(trips))


10716

In [36]:
ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips)
ax.figure.set_size_inches(10, 8)


What's up with the streaks around 45 dollars and 50 dollars? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.

Let's also examine whether the toll amount is captured in the total amount.


In [37]:
tollrides = trips[trips['tolls_amount'] > 0]
tollrides[tollrides['pickup_datetime'] == '2012-02-27 09:19:10 UTC']


Out[37]:
pickup_datetime pickup_longitude pickup_latitude dropoff_longitude dropoff_latitude passenger_count trip_distance tolls_amount fare_amount total_amount
47 2012-02-27 09:19:10 UTC -73.874431 40.774011 -73.983967 40.744082 1 11.6 4.8 27.7 38.0

Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.

Let's also look at the distribution of values within the columns.


In [38]:
trips.describe()


Out[38]:
pickup_longitude pickup_latitude dropoff_longitude dropoff_latitude passenger_count trip_distance tolls_amount fare_amount total_amount
count 10716.000000 10716.000000 10716.000000 10716.000000 10716.000000 10716.000000 10716.000000 10716.000000 10716.000000
mean -72.602192 40.002372 -72.594838 40.002052 1.650056 2.856395 0.226428 11.109446 13.217078
std 9.982373 5.474670 10.004324 5.474648 1.283577 3.322024 1.135934 9.137710 10.953156
min -74.258183 0.000000 -74.260472 0.000000 0.000000 0.010000 0.000000 2.500000 2.500000
25% -73.992153 40.735936 -73.991566 40.734310 1.000000 1.040000 0.000000 6.000000 7.300000
50% -73.981851 40.753264 -73.980373 40.752956 1.000000 1.770000 0.000000 8.500000 10.000000
75% -73.967400 40.767340 -73.964142 40.767510 2.000000 3.160000 0.000000 12.500000 14.600000
max 0.000000 41.366138 0.000000 41.366138 6.000000 42.800000 16.000000 179.000000 179.000000

Hmm ... The min, max of longitude look strange.

Finally, let's actually look at the start and end of a few of the trips.


In [39]:
def showrides(df, numlines):
  lats = []
  lons = []
  for iter, row in df[:numlines].iterrows():
    lons.append(row['pickup_longitude'])
    lons.append(row['dropoff_longitude'])
    lons.append(None)
    lats.append(row['pickup_latitude'])
    lats.append(row['dropoff_latitude'])
    lats.append(None)

  sns.set_style("darkgrid")
  plt.figure(figsize=(10,8))
  plt.plot(lons, lats)

showrides(trips, 10)



In [40]:
showrides(tollrides, 10)


As you'd expect, rides that involve a toll are longer than the typical ride.

Quality control and other preprocessing

We need to do some clean-up of the data:

  1. New York city longitudes are around -74 and latitudes are around 41.
  2. We shouldn't have zero passengers.
  3. Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.
  4. Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML dataset
  5. Discard the timestamp

We could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data.

This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic.


In [41]:
def preprocess(trips_in):
  trips = trips_in.copy(deep=True)
  trips.fare_amount = trips.fare_amount + trips.tolls_amount
  del trips['tolls_amount']
  del trips['total_amount']
  del trips['trip_distance'] # we won't know this in advance!

  qc = np.all([\
             trips['pickup_longitude'] > -78, \
             trips['pickup_longitude'] < -70, \
             trips['dropoff_longitude'] > -78, \
             trips['dropoff_longitude'] < -70, \
             trips['pickup_latitude'] > 37, \
             trips['pickup_latitude'] < 45, \
             trips['dropoff_latitude'] > 37, \
             trips['dropoff_latitude'] < 45, \
             trips['passenger_count'] > 0,
            ], axis=0)
  return trips[qc]

tripsqc = preprocess(trips)
tripsqc.describe()


Out[41]:
pickup_longitude pickup_latitude dropoff_longitude dropoff_latitude passenger_count fare_amount
count 10476.000000 10476.000000 10476.000000 10476.000000 10476.000000 10476.000000
mean -73.975206 40.751526 -73.974373 40.751199 1.653303 11.349003
std 0.038547 0.029187 0.039086 0.033147 1.278827 9.878630
min -74.258183 40.452290 -74.260472 40.417750 1.000000 2.500000
25% -73.992336 40.737600 -73.991739 40.735904 1.000000 6.000000
50% -73.982090 40.754020 -73.980780 40.753597 1.000000 8.500000
75% -73.968517 40.767774 -73.965851 40.767921 2.000000 12.500000
max -73.137393 41.366138 -73.137393 41.366138 6.000000 179.000000

The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.

Let's move on to creating the ML datasets.

Create ML datasets

Let's split the QCed data randomly into training, validation and test sets. Note that this is not the entire data. We have 1 billion taxicab rides. This is just splitting the 10,000 rides to show you how it's done on smaller datasets. In reality, we'll have to do it on all 1 billion rides and this won't scale.


In [42]:
shuffled = tripsqc.sample(frac=1)
trainsize = int(len(shuffled['fare_amount']) * 0.70)
validsize = int(len(shuffled['fare_amount']) * 0.15)

df_train = shuffled.iloc[:trainsize, :]
df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :]
df_test = shuffled.iloc[(trainsize+validsize):, :]

In [43]:
df_train.head(n=1)


Out[43]:
pickup_datetime pickup_longitude pickup_latitude dropoff_longitude dropoff_latitude passenger_count fare_amount
4865 2014-10-06 15:16:00 UTC -73.9814 40.780672 -73.970012 40.799602 1 9.5

In [44]:
df_train.describe()


Out[44]:
pickup_longitude pickup_latitude dropoff_longitude dropoff_latitude passenger_count fare_amount
count 7333.000000 7333.000000 7333.000000 7333.000000 7333.000000 7333.000000
mean -73.974856 40.751604 -73.974029 40.750912 1.659212 11.426602
std 0.039251 0.029251 0.039930 0.033525 1.288317 10.012522
min -74.258183 40.452290 -74.260472 40.417750 1.000000 2.500000
25% -73.992120 40.737924 -73.991730 40.735762 1.000000 6.000000
50% -73.982015 40.754162 -73.980750 40.753592 1.000000 8.500000
75% -73.968244 40.767812 -73.965692 40.767822 2.000000 12.500000
max -73.137393 41.366138 -73.137393 41.366138 6.000000 179.000000

In [45]:
df_valid.describe()


Out[45]:
pickup_longitude pickup_latitude dropoff_longitude dropoff_latitude passenger_count fare_amount
count 1571.000000 1571.000000 1571.000000 1571.000000 1571.000000 1571.000000
mean -73.977397 40.751450 -73.975086 40.751184 1.648631 11.017944
std 0.031180 0.026329 0.036422 0.030365 1.247684 9.217517
min -74.116582 40.633522 -74.181462 40.561076 1.000000 2.500000
25% -73.992930 40.737249 -73.991771 40.735172 1.000000 6.000000
50% -73.982255 40.754492 -73.980992 40.753299 1.000000 8.500000
75% -73.969642 40.767392 -73.967381 40.767741 2.000000 12.100000
max -73.776767 40.933269 -73.714585 41.001380 6.000000 90.500000

In [46]:
df_test.describe()


Out[46]:
pickup_longitude pickup_latitude dropoff_longitude dropoff_latitude passenger_count fare_amount
count 1572.000000 1572.000000 1572.000000 1572.000000 1572.000000 1572.000000
mean -73.974651 40.751236 -73.975268 40.752549 1.630407 11.317875
std 0.041714 0.031528 0.037650 0.034015 1.265582 9.887354
min -74.038562 40.608573 -74.182480 40.605517 1.000000 2.500000
25% -73.992822 40.736044 -73.991702 40.737089 1.000000 6.000000
50% -73.982298 40.753030 -73.980733 40.754484 1.000000 8.500000
75% -73.968611 40.767864 -73.965267 40.768526 2.000000 12.500000
max -73.137393 41.366138 -73.137393 41.366138 6.000000 99.300000

Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) just to verify our code works, before we run it on all the data.


In [47]:
def to_csv(df, filename):
  outdf = df.copy(deep=False)
  outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key
  # reorder columns so that target is first column
  cols = outdf.columns.tolist()
  cols.remove('fare_amount')
  cols.insert(0, 'fare_amount')
  print (cols)  # new order of columns
  outdf = outdf[cols]
  outdf.to_csv(filename, header=False, index_label=False, index=False)

to_csv(df_train, 'taxi-train.csv')
to_csv(df_valid, 'taxi-valid.csv')
to_csv(df_test, 'taxi-test.csv')


['fare_amount', 'pickup_datetime', 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude', 'passenger_count', 'key']
['fare_amount', 'pickup_datetime', 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude', 'passenger_count', 'key']
['fare_amount', 'pickup_datetime', 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude', 'passenger_count', 'key']

In [48]:
!head -10 taxi-valid.csv


6.9,2011-12-03 10:28:00 UTC,-73.992277,40.745895,-73.997132,40.726232,2,0
8.5,2012-06-14 22:23:53 UTC,-74.00638,40.739418,-74.000155,40.720655,1,1
5.0,2013-12-21 06:21:00 UTC,-73.95411,40.787162,-73.952025,40.798075,6,2
16.5,2013-10-12 12:59:44 UTC,-73.978163,40.75266,-74.009883,40.710913,1,3
8.1,2011-11-05 20:20:05 UTC,-73.986664,40.761251,-73.980885,40.744487,1,4
7.3,2011-12-03 10:28:00 UTC,-73.997885,40.765302,-73.973202,40.76458,1,5
4.5,2013-07-18 21:49:17 UTC,-73.995649,40.764538,-73.989312,40.768182,2,6
8.2,2009-01-08 22:16:40 UTC,-73.995762,40.724454,-73.979795,40.713878,1,7
17.3,2009-12-05 20:07:32 UTC,-73.97509,40.787592,-73.974379,40.731952,1,8
4.9,2012-07-05 14:18:00 UTC,-73.972698,40.780875,-73.966913,40.772645,5,9

Verify that datasets exist


In [49]:
!ls -l *.csv


-rw-r--r-- 1 jupyter jupyter 122870 Sep 13 19:18 taxi-test.csv
-rw-r--r-- 1 jupyter jupyter 580202 Sep 13 19:18 taxi-train.csv
-rw-r--r-- 1 jupyter jupyter 122687 Sep 13 19:18 taxi-valid.csv

We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data.


In [50]:
%%bash
head taxi-train.csv


9.5,2014-10-06 15:16:00 UTC,-73.9814,40.780672,-73.970012,40.799602,1,0
5.0,2012-11-19 17:41:00 UTC,-73.97256,40.793927,-73.975763,40.784652,5,1
6.9,2012-07-05 14:18:00 UTC,-73.975315,40.777245,-73.968052,40.762517,2,2
52.0,2013-08-18 17:30:08 UTC,-73.976114,40.740104,-73.782237,40.644236,1,3
6.5,2012-07-19 06:27:00 UTC,-73.99207,40.75016,-73.972102,40.763067,1,4
8.0,2012-12-17 13:03:38 UTC,-73.95209,40.766813,-73.970533,40.76401,1,5
4.5,2014-03-14 19:56:26 UTC,-73.990244,40.734194,-73.986982,40.729678,1,6
10.1,2011-12-08 20:47:17 UTC,-73.98583,40.71929,-73.966385,40.756398,1,7
8.5,2013-03-07 14:23:46 UTC,-73.974455,40.741944,-73.993271,40.736473,1,8
32.8,2012-11-19 17:41:00 UTC,-73.873167,40.774062,-73.985252,40.744807,2,9

Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them.

Benchmark

Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.

My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model.


In [51]:
def distance_between(lat1, lon1, lat2, lon2):
  # haversine formula to compute distance "as the crow flies".  Taxis can't fly of course.
  dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344
  return dist

def estimate_distance(df):
  return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon'])

def compute_rmse(actual, predicted):
  return np.sqrt(np.mean((actual-predicted)**2))

def print_rmse(df, rate, name):
  print ("{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name))

FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers']
TARGET = 'fare_amount'
columns = list([TARGET])
columns.append('pickup_datetime')
columns.extend(FEATURES) # in CSV, target is the first column, after the features
columns.append('key')
df_train = pd.read_csv('taxi-train.csv', header=None, names=columns)
df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns)
df_test = pd.read_csv('taxi-test.csv', header=None, names=columns)
rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean()
print ("Rate = ${0}/km".format(rate))
print_rmse(df_train, rate, 'Train')
print_rmse(df_valid, rate, 'Valid') 
print_rmse(df_test, rate, 'Test')


Rate = $2.596836025212977/km
Train RMSE = 8.2334605029378
Valid RMSE = 5.689335555737727
Test RMSE = 5.9889551857647625

Benchmark on same dataset

The RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs:


In [52]:
validation_query = """
SELECT
  (tolls_amount + fare_amount) AS fare_amount,
  pickup_datetime,
  pickup_longitude AS pickuplon,
  pickup_latitude AS pickuplat,
  dropoff_longitude AS dropofflon,
  dropoff_latitude AS dropofflat,
  passenger_count*1.0 AS passengers,
  'unused' AS key
FROM `nyc-tlc.yellow.trips`
WHERE ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 10000)) = 2
AND
  trip_distance > 0
  AND fare_amount >= 2.5
  AND pickup_longitude > -78
  AND pickup_longitude < -70
  AND dropoff_longitude > -78
  AND dropoff_longitude < -70
  AND pickup_latitude > 37
  AND pickup_latitude < 45
  AND dropoff_latitude > 37
  AND dropoff_latitude < 45
  AND passenger_count > 0
  """

client = bigquery.Client()
df_valid = client.query(validation_query).to_dataframe()
print_rmse(df_valid, 2.59988, 'Final Validation Set')


Final Validation Set RMSE = 8.135336354024826

The simple distance-based rule gives us a RMSE of $8.14. We have to beat this, of course, but you will find that simple rules of thumb like this can be surprisingly difficult to beat.

Let's be ambitious, though, and make our goal to build ML models that have a RMSE of less than $6 on the test set.

Copyright 2020 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.