Created
December 13, 2017 06:26
-
-
Save kforeman/39a9595bf2b40df82e81aa531ea855a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import PyMB | |
# create an empty model | |
m = PyMB.model(name='linreg') | |
# code for a simple linear regression | |
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; | |
} | |
''' | |
# compile the model using defaults | |
m.compile(codestr=linreg_code) | |
# simulate data | |
m.data['x'] = np.arange(10) | |
m.data['Y'] = m.data['x'] + 0.5 + np.random.rand(10) | |
# set initial parameter values | |
m.init['alpha'] = 0. | |
m.init['Beta'] = 0. | |
m.init['logSigma'] = 0. | |
# set random parameters | |
m.random = ['alpha', 'Beta'] | |
# fit the model | |
m.optimize() | |
print(m.report('Y_hat')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment