Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kforeman
Created December 13, 2017 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kforeman/39a9595bf2b40df82e81aa531ea855a2 to your computer and use it in GitHub Desktop.
Save kforeman/39a9595bf2b40df82e81aa531ea855a2 to your computer and use it in GitHub Desktop.
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