Looking at the Keeling Curve with GPs in PyMC3

Sat 12 August 2017

This post discusses modeling the CO2 measurments at Mauna Loa using Gaussian processes in PyMC3.

The code for this is being developed and isn't merged into PyMC3 master yet

The Keeling Curve

In the late 1950's Charles Keeling invented a accurate way to measure atmospheric CO\(_2\) concentration and began taking regular measurements at the Mauna Loa observatory. Today, measurements are continuously recorded. Check out last hours measurement result here.

Mauna Loa observatory

Not much was known about how fossil fuel burning influences the climate in the late 1950s. The first couple years of data collection showed that CO\(_2\) levels rose and fell following summer and winter, tracking the growth and decay of vegetation in the northern hemisphere. As multiple years passed, the steady upward trend increasingly grew into focus. With over 70 years of collected data, the Keeling curve is one of the most important climate indicators.

The history behind these measurements and their influence on climatology today and other interesting reading:

  • http://scrippsco2.ucsd.edu/history_legacy/early_keeling_curve#
  • https://scripps.ucsd.edu/programs/keelingcurve/2016/05/23/why-has-a-drop-in-global-co2-emissions-not-caused-co2-levels-in-the-atmosphere-to-stabilize/#more-1412
  • http://cdiac.ornl.gov/

Let's load in the data, tidy it up, and have a look. The raw data set is located here. This notebook uses the Bokeh package for plots that benefit from interactivity.

Preparing the data

import sys
sys.path.insert(0, "/home/bill/pymc3/")
import pymc3 as pm

import matplotlib.pyplot as plt
%matplotlib inline

import pandas as pd
import numpy as np
import theano.tensor as tt
data_monthly = pd.read_csv(pm.get_data("monthly_in_situ_co2_mlo.csv"), header=56)

# - replace -99.99 with NaN
data_monthly.replace(to_replace=-99.99, value=np.nan, inplace=True)

# fix column names
cols = ["year", "month", "--", "--", "CO2", "seasonaly_adjusted", "fit",
        "seasonally_adjusted_fit", "CO2_filled", "seasonally_adjusted_filled"]
data_monthly.columns = cols
cols.remove("--"); cols.remove("--")
data_monthly = data_monthly[cols]

# drop rows with nan
data_monthly.dropna(inplace=True)

# fix time index
data_monthly["day"] = 15
data_monthly.index = pd.to_datetime(data_monthly[["year", "month", "day"]])
cols.remove("year"); cols.remove("month")
data_monthly = data_monthly[cols]

data_monthly.head(5)
CO2 seasonaly_adjusted fit seasonally_adjusted_fit CO2_filled seasonally_adjusted_filled
1958-03-15 315.69 314.43 316.18 314.90 315.69 314.43
1958-04-15 317.46 315.15 317.30 314.98 317.46 315.15
1958-05-15 317.50 314.73 317.84 315.06 317.50 314.73
1958-07-15 315.86 315.17 315.87 315.22 315.86 315.17
1958-08-15 314.93 316.17 314.01 315.29 314.93 316.17
# function to convert datetimes to numbers that are useful to algorithms
#   this will be useful later when doing prediction

def dates_to_idx(timelist):
    reference_time = pd.to_datetime('1958-03-15')
    t = (timelist - reference_time) / pd.Timedelta(1, "Y")
    return np.asarray(t)

t = dates_to_idx(data_monthly.index)

# normalize CO2 levels
y = data_monthly["CO2"].values
first_co2 = y[0]
std_co2 = np.std(y)
y_n = (y - first_co2) / std_co2

data_monthly = data_monthly.assign(t = t)
data_monthly = data_monthly.assign(y_n = y_n)

This data might be familiar to you, since it was used as an example in the Gaussian Processes for Machine Learning book by Rasmussen & Williams. The version of the data set they use starts in the late 1950's, but stops at the end of 2003. So that our PyMC3 example is somewhat comparable to their example, we use the stretch of data from before 2004 as the "training" set. The data from 2004 to current we'll use to test our predictions.

# split into training and test set
sep_idx = data_monthly.index.searchsorted(pd.to_datetime("2003-12-15"))
data_prior = data_monthly.iloc[:sep_idx+1, :]
data_after = data_monthly.iloc[sep_idx:, :]
# make plot
from bokeh.plotting import figure, show
from bokeh.models import BoxAnnotation, Span, Label, Legend
from bokeh.io import output_notebook


output_notebook()
p = figure(x_axis_type='datetime', title='Monthly CO2 Readings from Mauna Loa',
           plot_width=700, plot_height=400)
p.yaxis.axis_label = 'CO2 [ppm]'
p.xaxis.axis_label = 'Date'
predict_region = BoxAnnotation(left=pd.to_datetime("2003-12-15"), 
                               fill_alpha=0.1, fill_color="firebrick")
p.add_layout(predict_region)
ppm400 = Span(location=400,
              dimension='width', line_color='red',
              line_dash='dashed', line_width=2)
p.add_layout(ppm400)

p.line(data_monthly.index, data_monthly['CO2'], 
       line_width=2, line_color="black", alpha=0.5)
p.circle(data_monthly.index, data_monthly['CO2'], 
         line_color="black", alpha=0.1, size=2)

train_label = Label(x=100, y=165, x_units='screen', y_units='screen',
                    text='Training Set', render_mode='css', border_line_alpha=0.0,
                    background_fill_alpha=0.0)
test_label  = Label(x=585, y=80, x_units='screen', y_units='screen',
                    text='Test Set', render_mode='css', border_line_alpha=0.0,
                    background_fill_alpha=0.0)

p.add_layout(train_label)
p.add_layout(test_label)
show(p)
Loading BokehJS ...

Bokeh plots are interactive, so panning and zooming can be done with the sidebar on the right hand side. The seasonal rise and fall is plainly apparent, as is the upward trend. Here is a link to an plots of this curve at different time scales, and in the context of historical ice core data.

The 400 ppm level is highlighted with a dashed line. In addition to fitting a descriptive model, our goal will be to predict the first month the 400 ppm threshold is crossed, which was May, 2013. In the data set above, the CO\(_2\) average reading for May, 2013 was about 399.98, close enough to be our correct target date.

Additive GPs ...

The GP implementation in PyMC3 is constructed so that it is easy to define additive GPs and sample from individual GP components.

Consider two independent GP distributed functions, \(f_1(x) \sim \mathcal{GP}\left(m_1(x),\, k_1(x, x')\right)\) and \(f_2(x) \sim \mathcal{GP}\left( m_2(x),\, k_2(x, x')\right)\). The joint distribution of \(f_1\), \(f_1^*\), \(f_2\), \(f_2^*\), \(f_1 + f_2\) and \(f_1^* + f_2^*\) is

$$ \begin{bmatrix} f_1 \\ f_1^* \\ f_2 \\ f_2^* \\ f_1 + f_2 \\ f_1^* + f_2^* \end{bmatrix} \sim \text{N}\left( \begin{bmatrix} m_1 \\ m_1^* \\ m_2 \\ m_2^* \\ m_1 + m_2 \\ m_1^* + m_2^* \\ \end{bmatrix} \,,\, \begin{bmatrix} K_1 & K_1^* & 0 & 0 & K_1 & K_1^* \\ K_1^{*^T} & K_1^{**} & 0 & 0 & K_1^* & K_1^{**} \\ 0 & 0 & K_2 & K_2^* & K_2 & K_2^{*} \\ 0 & 0 & K_2^{*^T} & K_2^{**} & K_2^{*} & K_2^{**} \\ K_1 & K_1^{*} & K_2 & K_2^{*} & K_1 + K_2 & K_1^{*} + K_2^{*} \\ K_1^{*^T} & K_1^{**} & K_2^{*^T} & K_2^{**} & K_1^{*^T}+K_2^{*^T} & K_1^{**}+K_2^{**} \end{bmatrix} \right) \,. $$

Using the joint distribution to obtain the conditional distribution of \(f_1^*\) with the contribution due to \(f_1 + f_2\) factored out, we get

$$ f_1^* \mid f_1 + f_2 \sim \text{N}\left( m_1^* + K_1^{*^T}(K_1 + K_2)^{-1}\left[f_1 + f_2 - m_1 - m_2\right] \,,\, K_1^{**} - K_1^{*^T}(K_1 + K_2)^{-1}K_1^* \right) \,. $$

This formula gives the uncertainty for a GP component after marginalizing over the contributions from other components. For more information, check out David Duvenaud's PhD thesis.

... in PyMC3

The GPs in PyMC3 keeps track of these marginals automatically. The following code sketch shows how to define the conditional distribution of \(f_2^*\). We use gp.Latent in the example, but the same works for gp.Marginal. The first block fits the GP prior. We denote \(f_1 + f_2\) as just \(f\) for brevity.

with pm.Model() as model:
    gp1 = pm.gp.Latent(mean_func1, cov_func1)
    gp2 = pm.gp.Latent(mean_func2, cov_func2)

    # gp represents f1 + f2.  
    gp = gp1 + gp2

    f = gp.prior("f", n_points, x)

    trace = pm.sample(1000)

The second block produces conditional distributions, including \(f_2^* \mid f_1 + f_2\). Notice that extra arguments are required for conditionals of \(f1\) and \(f2\), but not \(f\). This is because those arguments are cached when calling .prior.

with model:
    # f_1^* | f_1 + f_2. Note that f = f1 + f2.
    f1_star = gp1.conditional("f1_star", n_star, X_star, gp=gp) 

    # f_2^* | f_1 + f_2
    f2_star = gp2.conditional("f2_star", n_star, X_star, gp=gp) 

    # f_1^* + f_2^* | f_1 + f_2.  X, f aren't required.
    f_star = gp.conditional("f_star", n_star, X_star)

f1_star, f2_star, and f_star are just PyMC3 random variables that can be either sampled from or incorporated into larger models.

Modeling the Keeling Curve using GPs

As a starting point, we use the GP model described in Rasmussen & Williams. Instead of using flat priors on covariance function hyperparameters and then maximizing the marginal likelihood like is done in the textbook, we place somewhat informative priors on the hyperparameters and use the NUTS sampler for inference. We use the gp.Marginal since Gaussian noise is assumed.

The R+W model is a sum of three GPs for the signal, and one GP for the noise.

  1. A long term smooth rising trend represented by an exponentiated quadratic kernel.
  2. A periodic term that decays away from exact periodicity. This is represented by the product of a Periodic covariance function and an exponentiated quadratic.
  3. Small and medium term irregularities with a rational quadratic kernel.
  4. The noise is modeled as the sum of an Exponential and a white noise kernel

The prior on CO\(_2\) as a function of time is,

$$ f(t) \sim \mathcal{GP}_{\text{slow}}(0,\, k_1(t, t')) + \mathcal{GP}_{\text{med}}(0,\, k_2(t, t')) + \mathcal{GP}_{\text{per}}(0,\, k_3(t, t')) + \mathcal{GP}_{\text{noise}}(0,\, k_n(t, t')) $$

Hyperparameter priors

We use fairly uninformative priors for the scale hyperparameters of the covariance functions, and informative Gamma parameters for lengthscales. The PDFs used for the lengthscale priors is shown below:

x = np.linspace(0, 150, 5000)
priors = [
    ("â„“_pdecay",  pm.Gamma.dist(alpha=10, beta=0.075)),
    ("â„“_psmooth", pm.Gamma.dist(alpha=4,  beta=3)),
    ("period",    pm.Normal.dist(mu=1.0,  sd=0.05)),
    ("â„“_med",     pm.Gamma.dist(alpha=2,  beta=0.75)),
    ("α",         pm.Gamma.dist(alpha=5,  beta=2)),
    ("â„“_trend",   pm.Gamma.dist(alpha=4,  beta=0.1)),
    ("â„“_noise",   pm.Gamma.dist(alpha=2,  beta=4))]

from bokeh.palettes import brewer
colors = brewer['Paired'][7]

output_notebook()
p = figure(title='Lengthscale and period priors',
           plot_width=700, plot_height=400)
p.yaxis.axis_label = 'Probability'
p.xaxis.axis_label = 'Years'

for i, prior in enumerate(priors):
    p.line(x, np.exp(prior[1].logp(x).eval()), legend=prior[0], 
           line_width=3, line_color=colors[i])
show(p)
Loading BokehJS ...
  • â„“_pdecay: The periodic decay. The smaller this parameter is, the faster the periodicity goes away. I doubt that the seasonality of the CO\(_2\) will be going away any time soon (hopefully), and there's no evidence for that in the data. Most of the prior mass is from 60 to >140 years.

  • â„“_psmooth: The smoothness of the periodic component. It controls how "sinusoidal" the periodicity is. The plot of the data shows that seasonality is not an exact sine wave, but its not terribly different from one. We use a Gamma whose mode is at one, and doesn't have too large of a variance, with most of the prior mass from around 0.5 and 2.

  • period: The period. We put a very strong prior on \(p\), the period that is centered at one. R+W fix \(p=1\), since the period is annual.

  • â„“_med: This is the lengthscale for the short to medium long variations. This prior has most of its mass below 6 years.

  • α: This is the shape parameter. This prior is centered at 3, since we're expecting there to be some more variation than could be explained by an exponentiated quadratic.

  • â„“_trend: The lengthscale of the long term trend. It has a wide prior with mass on a decade scale. Most of the mass is between 10 to 60 years.

  • â„“_noise: The lengthscale of the noise covariance. This noise should be very rapid, in the scale of several months to at most a year or two.

We know beforehand which GP components should have a larger magnitude, so we try to include this information in the scale parameters.

x = np.linspace(0, 4, 5000)
priors = [
    ("η_per",   pm.HalfCauchy.dist(beta=2)),
    ("η_med",   pm.HalfCauchy.dist(beta=0.5)),
    ("η_trend", pm.HalfCauchy.dist(beta=1)),
    ("σ",       pm.HalfNormal.dist(sd=0.25)),
    ("η_noise", pm.HalfNormal.dist(sd=0.5))]

from bokeh.palettes import brewer
colors = brewer['Paired'][5]

output_notebook()
p = figure(title='Scale priors',
           plot_width=700, plot_height=400)
p.yaxis.axis_label = 'Probability'
p.xaxis.axis_label = 'Years'

for i, prior in enumerate(priors):
    p.line(x, np.exp(prior[1].logp(x).eval()), legend=prior[0], 
           line_width=3, line_color=colors[i])
show(p)
Loading BokehJS ...

For all of the scale priors we use distributions that shrink the scale towards zero. The seasonal component and the long term trend have the least mass near zero, since they are the largest influences in the data.

  • η_per: Scale of the periodic or seasonal component.
  • η_med: Scale of the short to medium term component.
  • η_trend: Scale of the long term trend.
  • σ: Scale of the white noise.
  • η_noise: Scale of correlated, short term noise.

The model in PyMC3

Below is the actual model. Each of the three component GPs is constructed separately. Since we are doing MAP, we use Marginal GPs and lastly call the .marginal_likelihood method to specify the marginal posterior.

# pull out normalized data
t = data_prior["t"].values[:,None]
y = data_prior["y_n"].values
 with pm.Model() as model:
    # yearly periodic component x long term trend
    η_per = pm.HalfCauchy("η_per", beta=2, testval=1.0)
    â„“_pdecay = pm.Gamma("â„“_pdecay", alpha=10, beta=0.075)
    period  = pm.Normal("period", mu=1, sd=0.05)
    â„“_psmooth = pm.Gamma("â„“_psmooth ", alpha=4, beta=3)
    cov_seasonal = η_per**2 * pm.gp.cov.Periodic(1, ℓ_psmooth, period) \
                            * pm.gp.cov.Matern52(1, â„“_pdecay)
    gp_seasonal = pm.gp.Marginal(cov_func=cov_seasonal)

    # small/medium term irregularities
    η_med = pm.HalfCauchy("η_med", beta=0.5, testval=0.1)
    â„“_med = pm.Gamma("â„“_med", alpha=2, beta=0.75)
    α = pm.Gamma("α", alpha=5, beta=2) 
    cov_medium = η_med**2 * pm.gp.cov.RatQuad(1, ℓ_med, α)
    gp_medium = pm.gp.Marginal(cov_func=cov_medium)

    # long term trend
    η_trend = pm.HalfCauchy("η_trend", beta=1, testval=2.0)
    â„“_trend = pm.Gamma("â„“_trend", alpha=4, beta=0.1)
    cov_trend = η_trend**2 * pm.gp.cov.ExpQuad(1, ℓ_trend)

    # positive trend
    gp_trend = pm.gp.Marginal(cov_func=cov_trend)   

    # noise model
    η_noise = pm.HalfNormal("η_noise", sd=0.5, testval=0.05)
    â„“_noise = pm.Gamma("â„“_noise", alpha=2, beta=4)
    σ = pm.HalfNormal("σ",  sd=0.25, testval=0.05)
    cov_noise = η_noise**2 * pm.gp.cov.Matern52(1, ℓ_noise) +\
                pm.gp.cov.WhiteNoise(σ)

    gp = gp_seasonal + gp_medium + gp_trend

    y_ = gp.marginal_likelihood("y", X=t, y=y, noise=cov_noise)
    mp = pm.find_MAP()
lp = 1,660.3, ||grad|| = 0.000188:   0%|          | 91/50000 [00:42<7:20:44,  1.89it/s]
# display the results, dont show transformed parameter values
sorted([name+":"+str(mp[name]) for name in mp.keys() if not name.endswith("_")])
['period:0.9997258448670243',
 'α:2.337426188393657',
 'η_med:0.0240978960754937',
 'η_noise:0.007745112721675894',
 'η_per:0.12931787564550073',
 'η_trend:2.068506718807813',
 'σ:0.006983204369562765',
 'â„“_med:1.1529874637194588',
 'â„“_noise:0.172727746926997',
 'â„“_pdecay:142.05923683759502',
 'â„“_psmooth :0.8048036561052917',
 'â„“_trend:56.516529265101425']

At first glance the results look reasonable. The period is about 1 year. The lengthscale that determines how fast the seasonality varies is 144.35 years. This means that given the data, we wouldn't expect such strong periodicity to vanish until centuries have passed. The trend lengthscale is also long, about 56 years.

Examining the fit

The code below looks at the fit of the total GP, and each component individually. The total fit and its \(2\sigma\) uncertainty is shown in red.

# predict at a 15 day granularity
dates = pd.date_range(start='3/15/1958', end="12/15/2003", freq="15D")
tnew = dates_to_idx(dates)[:,None]

print("Predicting with gp ...")
mu, var = gp.predict(tnew, point=mp, diag=True)
mean_pred = mu*std_co2 + first_co2
var_pred  = var*std_co2**2

# make dataframe to store fit results
fit = pd.DataFrame({"t": tnew.flatten(), 
                    "mu_total": mean_pred, 
                    "sd_total": np.sqrt(var_pred)},
                   index=dates)

print("Predicting with gp_trend ...")
mu, var = gp_trend.predict(tnew, point=mp, given=gp, diag=True)
fit = fit.assign(mu_trend = mu*std_co2 + first_co2, 
                 sd_trend = np.sqrt(var*std_co2**2))

print("Predicting with gp_medium ...")
# medium component
mu, var = gp_medium.predict(tnew, point=mp, given=gp, diag=True)
fit = fit.assign(mu_medium = mu*std_co2 + first_co2, 
                 sd_medium = np.sqrt(var*std_co2**2))

print("Predicting with gp_seasonal ...")
mu, var = gp_seasonal.predict(tnew, point=mp, given=gp, diag=True)
fit = fit.assign(mu_seasonal = mu*std_co2 + first_co2, 
                 sd_seasonal = np.sqrt(var*std_co2**2))
print("Done")
Predicting with gp ...
Predicting with gp_trend ...
Predicting with gp_medium ...
Predicting with gp_seasonal ...
Done
## make plot
p = figure(title="Fit to the Mauna Loa Data",
           x_axis_type='datetime', plot_width=700, plot_height=400)
p.yaxis.axis_label = 'CO2 [ppm]'
p.xaxis.axis_label = 'Date'

# plot mean and 2σ region of total prediction
upper = fit.mu_total + 2*fit.sd_total
lower = fit.mu_total - 2*fit.sd_total
band_x = np.append(fit.index.values, fit.index.values[::-1])
band_y = np.append(lower, upper[::-1])

# total fit
p.line(fit.index, fit.mu_total, 
       line_width=1, line_color="firebrick", legend="Total fit")
p.patch(band_x, band_y, 
        color="firebrick", alpha=0.6, line_color="white")

# trend
p.line(fit.index, fit.mu_trend, 
       line_width=1, line_color="blue", legend="Long term trend")

# medium
p.line(fit.index, fit.mu_medium, 
       line_width=1, line_color="green", legend="Medium range variation")

# seasonal
p.line(fit.index, fit.mu_seasonal, 
       line_width=1, line_color="orange", legend="Seasonal process")

# true value
p.circle(data_prior.index, data_prior['CO2'], 
         color="black", legend="Observed data")
p.legend.location = "top_left"
show(p)

The fit matches the observed data very well. The trend, seasonality, and short/medium term effects also are cleanly separated out. Looking closer at the seasonality, it appears to be widening as time goes on. Lets plot a couple years and take a look:

# plot several years

p = figure(title="Several years of the seasonal component",
           plot_width=700, plot_height=400)
p.yaxis.axis_label = 'Δ CO2 [ppm]'
p.xaxis.axis_label = 'Month'

from bokeh.palettes import brewer
colors = brewer['Paired'][5]
years = ["1960", "1970", "1980", "1990", "2000"]

for i, year in enumerate(years):
    dates = pd.date_range(start="1/1/"+year, end="12/31/"+year, freq="10D")
    tnew = dates_to_idx(dates)[:,None]

    print("Predicting year", year)
    mu, var = gp_seasonal.predict(tnew, point=mp, given=gp, diag=True)
    mu_pred = mu*std_co2

    # plot mean
    t = np.asarray((dates - dates[0])/pd.Timedelta(1, "M")) + 1
    p.line(t, mu_pred, 
           line_width=1, line_color=colors[i], legend=year)

p.legend.location = "bottom_left"
show(p)
Predicting year 1960
Predicting year 1970
Predicting year 1980
Predicting year 1990
Predicting year 2000

This plot makes it clear that there is a broadening over time. So it would seem that as there is more CO\(_2\) in the atmosphere, the absorbtion/release cycle due to the growth and decay of vegetation in the northern hemisphere becomes more slightly more pronounced.

Prediction

How well do our forecasts look? Clearly the observed data trends up and the seasonal effect is very pronounced. Does our GP model capture this well enough to make reasonable extrapolations? Our "training" set went up until the end of 2003, so we are going to predict from January 2014 out to the end of 2017.

Although there isn't any particular significance to this event other than it being a nice round number, our side goal was to see how well we could predict the date when the 400 ppm mark is first crossed. This event first occurred during May, 2013 and there were a few news articles about other significant milestones.

dates = pd.date_range(start="11/15/2003", end="12/15/2020", freq="10D")
tnew = dates_to_idx(dates)[:,None]

print("Sampling gp predictions ...")
mu_pred, cov_pred = gp.predict(tnew, point=mp)

# draw samples, and rescale
n_samples = 20000
samples = pm.MvNormal.dist(mu=mu_pred, cov=cov_pred).random(size=n_samples)
samples = samples * std_co2 + first_co2
Sampling gp predictions ...
### make plot
p = figure(x_axis_type='datetime', plot_width=700, plot_height=300)
p.yaxis.axis_label = 'CO2 [ppm]'
p.xaxis.axis_label = 'Date'

### plot mean and 2σ region of total prediction
# scale mean and var
mu_pred_sc = mu_pred * std_co2 + first_co2
sd_pred_sc = np.sqrt(np.diag(cov_pred) * std_co2**2 )

upper = mu_pred_sc + 2*sd_pred_sc
lower = mu_pred_sc - 2*sd_pred_sc
band_x = np.append(dates, dates[::-1])
band_y = np.append(lower, upper[::-1])

p.line(dates, mu_pred_sc, 
       line_width=2, line_color="firebrick", legend="Total fit")
p.patch(band_x, band_y, 
        color="firebrick", alpha=0.6, line_color="white")

# some predictions
idx = np.random.randint(0, samples.shape[0], 10)
p.multi_line([dates]*len(idx), [samples[i,:] for i in idx],
             color="firebrick", alpha=0.5, line_width=0.5)
# true value
p.line(data_after.index, data_after['CO2'], 
       line_width=2, line_color="black", legend="Observed data")

ppm400 = Span(location=400,
              dimension='width', line_color='black',
              line_dash='dashed', line_width=1)
p.add_layout(ppm400)
p.legend.location = "bottom_right"
show(p)

The mean prediction and the \(2\sigma\) uncertainty is in red. A couple samples from the marginal posterior are also shown on there. It looks like our model was a little optimistic about how much CO2 is being released. The first time the \(2\sigma\) uncertainty crosses the 400 ppm threshold is in May 2015, two years late.

One reason this is occuring is because our GP prior had zero mean. This means we encoded prior information that says that the function should go to zero as we move away from our observed data. This assumption probably isn't justified. It's also possible that the CO\(_2\) trend is increasing faster than linearly -- important knowledge for accurate predictions. Another possibility is the MAP estimate. Without looking at the full posterior, the uncertainty in our estimates is underestimated. How badly is unknown.

The following code looks at each of the posterior samples, and collects the date when a measurement higher than 400 ppm is predicted. One of the great things about Bayesian approaches is that samples from the posterior can be used to create any arbitrary statistic.

from collections import Counter
def cross400(preds, dates, start=pd.to_datetime("2003-12-15")):
    """ loop over each prediction, finding first entry that is greater than 400 """
    times = Counter()
    times[start] = 0
    N = preds.shape[0]
    for i in range(N):
        p = preds[i,:]
        idx = np.searchsorted(p, 400, side='left')
        if idx >= len(dates):  # prediction never actually crosses 400
            times["never"] += 1
        else: #it does cross 400, when?
            times[dates[idx]] += 1
    never = times.pop('never', 0)
    def resampler(x):
        if len(x) == 0:
            return 0
        else:
            return x
    times = pd.Series(times).resample("D").apply(resampler)
    return times, never

Lets look at the posterior probability by year:

print("First time 400 ppm of CO2 hit: May, 2013") 
times, never = cross400(samples, dates)
for year in range(2003,2021):
    val = times[str(year)].sum()
    print(str(year)+": ", val/float(n_samples))
print("Never, or later than 2020:", never/float(n_samples))
First time 400 ppm of CO2 hit: May, 2013
2003:  0.0
2004:  0.0
2005:  0.0
2006:  0.0
2007:  0.0
2008:  0.0
2009:  0.0
2010:  0.0
2011:  0.0
2012:  0.0
2013:  0.0
2014:  0.0
2015:  0.00025
2016:  0.00535
2017:  0.06865
2018:  0.1855
2019:  0.19525
2020:  0.2988
Never, or later than 2020: 0.2462

Having a zero mean GP prior is causing the prediction to be pretty far off. Some possibilities for fixing this is to use a constant mean function, whose value could maybe be assigned the historical, or pre-industrial revolution, CO\(_2\) average. This may not be the best indicator for future CO\(_2\) levels though.

Also, using only historical CO\(_2\) data may not be the best predictor. In addition to looking at the underlying behavior of what determines CO\(_2\) levels using a GP fit, we could also incorporate other information, such as the amount of CO\(_2\) that is released by fossil fuel burning.

Next, we'll see about using PyMC3's GP functionality to improve the model, look at full posteriors, and incorporate other sources of data on drivers of CO\(_2\) levels.