In [1]:
import sys
sys.path.append('../..')
import PyMB
In [2]:
m = PyMB.model(name='linreg')
See the TMB tutorial for more information on writing custom models
In [3]:
linreg_code = '''
#include <TMB.hpp>
template<class Type>
Type objective_function<Type>::operator() (){
// DATA
DATA_VECTOR(Y);
DATA_VECTOR(x);
// PARAMETERS
PARAMETER(alpha);
PARAMETER(Beta);
PARAMETER(logSigma);
// MODEL
vector<Type> Y_hat = alpha + Beta*x;
REPORT(Y_hat);
Type nll = -sum(dnorm(Y, Y_hat, exp(logSigma), true));
return nll;
}
'''
See additional compiler options such as setting the R and TMB library directories via help(PyMB.model.compile)
In [4]:
m.compile(codestr=linreg_code)
In [5]:
import numpy as np
m.data['x'] = np.arange(10)
m.data['Y'] = m.data['x'] + 0.5 + np.random.rand(10)
In [6]:
m.init['alpha'] = 0.
m.init['Beta'] = 0.
m.init['logSigma'] = 0.
The model likelihood will be integrated wrt the random parameters. See here for more information.
In [7]:
m.random = ['alpha', 'Beta']
In [8]:
m.optimize()
In [9]:
print(m.report('Y_hat'))
In [10]:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
df = pd.DataFrame({ k: v['draws'][0] for k,v in m.parameters.iteritems() })
g = sns.PairGrid(df, diag_sharey=False)
g.map_lower(sns.kdeplot, cmap='Blues_d')
g.map_upper(plt.scatter)
g.map_diag(sns.kdeplot, lw=3)