Skip to content

Instantly share code, notes, and snippets.

@djlacombe
Created December 7, 2018 20:37
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 djlacombe/a0d3070ddfc408c9b39cbcbbb07984c3 to your computer and use it in GitHub Desktop.
Save djlacombe/a0d3070ddfc408c9b39cbcbbb07984c3 to your computer and use it in GitHub Desktop.
Optim.jl Maximum Likelihood Normal Linear Model Update
{
"cells": [
{
"outputs": [],
"cell_type": "markdown",
"source": [
"# Maximum Likelihood Estimation in Julia: The Normal Linear Model\n",
"\n",
"The following tutorial will introduce maximum likelihood estimation in Julia for\n",
"the normal linear model.\n",
"\n",
"The normal linear model (sometimes referred to as the OLS model) is the workhorse of\n",
"regression modeling and is utilized across a number of diverse fields.\n",
"In this tutorial, we will utilize simulated data to\n",
"demonstrate how Julia can be used to recover the parameters of interest.\n",
"\n",
"The first order of business is to use the `Optim` package to Julia and also include the `NLSolversBase` routine:"
],
"metadata": {}
},
{
"outputs": [],
"cell_type": "code",
"source": [
"using Optim\n",
"using NLSolversBase"
],
"metadata": {},
"execution_count": 1
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"The first item that needs to be addressed is the data generating process or DGP.\n",
"The following code will produce data from a nomral linear model:"
],
"metadata": {}
},
{
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "500-element Array{Float64,1}:\n -0.894852\n 2.87039 \n 5.20335 \n 0.77645 \n 11.3088 \n 3.02123 \n 8.2348 \n 7.55828 \n -2.27908 \n 2.6151 \n ⋮ \n 2.43145 \n 5.30706 \n 3.91946 \n 4.33118 \n 6.8804 \n 3.07067 \n -2.54393 \n 2.38168 \n 8.67772 "
},
"metadata": {},
"execution_count": 2
}
],
"cell_type": "code",
"source": [
"n = 500 # Number of observations\n",
"nvar = 2 # Number of variables\n",
"β = ones(nvar) * 3.0 # True coefficients\n",
"x = [ones(n) randn(n, nvar - 1)] # X matrix of explanatory variables plus constant\n",
"ε = randn(n) * 0.5 # Error variance\n",
"y = x * β + ε # Generate Data"
],
"metadata": {},
"execution_count": 2
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"In the above example, we have 500 observations, 2 explanatory variables plus an intercept,\n",
"an error variance equal to 0.5, coefficients equal to 3.0, and all of these are subject to change by the user.\n",
"Since we know the true value of these parameters, we should obtain these values when we maximize the likelihood function.\n",
"\n",
"The next step in our tutorial is to define a Julia function for the likelihood function. The following function defines the likelihood\n",
"function for the normal linear model:"
],
"metadata": {}
},
{
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "Log_Likelihood (generic function with 1 method)"
},
"metadata": {},
"execution_count": 3
}
],
"cell_type": "code",
"source": [
"function Log_Likelihood(X, Y, β, log_σ)\n",
" σ = exp(log_σ)\n",
" llike = -n/2*log(2π) - n/2* log(σ^2) - (sum((Y - X * β).^2) / (2σ^2))\n",
" llike = -llike\n",
"end"
],
"metadata": {},
"execution_count": 3
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"The log likelihood function accepts 4 inputs: the matrix of explanatory variables (X), the dependent variable (Y),\n",
"the β's, and the error varicance. Note that we exponentiate the error variance in the second line of the code because the\n",
"error variance cannot be negative and we want to avoid this situation when maximizing the likelihood.\n",
"\n",
"The next step in our tutorial is to optimize our function. We first use the `TwiceDifferentiable` command in order to obtain\n",
"the Hessian matrix later on, which will be used to help form t-statistics:"
],
"metadata": {}
},
{
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "NLSolversBase.TwiceDifferentiable{Float64,Array{Float64,1},Array{Float64,2},Array{Float64,1}}(##1103.#3, Optim.#23, Optim.#24, Optim.#25, 0.0, [0.0, 0.0, 0.0], [NaN NaN NaN; NaN NaN NaN; NaN NaN NaN], [NaN, NaN, NaN], [NaN, NaN, NaN], [NaN, NaN, NaN], [0], [0], [0])"
},
"metadata": {},
"execution_count": 4
}
],
"cell_type": "code",
"source": [
"func = TwiceDifferentiable(vars -> Log_Likelihood(x, y, vars[1:nvar], vars[nvar + 1]), ones(nvar+1); autodiff=:forward)"
],
"metadata": {},
"execution_count": 4
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"The above statment accepts 4 inputs: the x matrix, the dependent variable y, and a vector of β's and the error variance.\n",
"The `vars[1:nvar]` is how we pass the vector of β's and the `vars[nvar + 1]` is how we pass the error variance. You can think\n",
"of this as a vector of parameters with the first 2 being β's and the last one is the error variance.\n",
"\n",
"The `ones(nvar+1)` are the starting values for the parameters and the `autodiff=:forward` command performs forward mode\n",
"automatic differentiation.\n",
"\n",
"The actual optimization of the likelihood function is accomplished with the following command:"
],
"metadata": {}
},
{
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "Results of Optimization Algorithm\n * Algorithm: Newton's Method\n * Starting Point: [1.0,1.0,1.0]\n * Minimizer: [3.008774716457104,3.025712457290841, ...]\n * Minimum: 3.739709e+02\n * Iterations: 8\n * Convergence: true\n * |x - x'| ≤ 1.0e-32: false \n |x - x'| = 1.41e-10 \n * |f(x) - f(x')| ≤ 1.0e-32 |f(x)|: false\n |f(x) - f(x')| = 1.52e-16 |f(x)|\n * |g(x)| ≤ 1.0e-08: true \n |g(x)| = 4.15e-13 \n * Stopped by an increasing objective: false\n * Reached Maximum Number of Iterations: false\n * Objective Calls: 32\n * Gradient Calls: 32\n * Hessian Calls: 8"
},
"metadata": {},
"execution_count": 5
}
],
"cell_type": "code",
"source": [
"opt = optimize(func, ones(nvar+1))"
],
"metadata": {},
"execution_count": 5
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"The first input to the command is the function we wish to optimize and the second input are the starting values.\n",
"\n",
"After a brief period of time, you should see output of the optimization routine, with the parameter\n",
"estimates being very close to our simulated values."
],
"metadata": {}
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"The optimization routine stores several quantities and we can obtain the maximim likelihood estimates with\n",
"the following command:"
],
"metadata": {}
},
{
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "3-element Array{Float64,1}:\n 3.00877 \n 3.02571 \n -0.670997"
},
"metadata": {},
"execution_count": 6
}
],
"cell_type": "code",
"source": [
"parameters = Optim.minimizer(opt)"
],
"metadata": {},
"execution_count": 6
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"Since we paramaterized our likelihood to use the exponentiated value, we need to exponentiate it\n",
"to get back to our original log scale:"
],
"metadata": {}
},
{
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "0.5111987657484192"
},
"metadata": {},
"execution_count": 7
}
],
"cell_type": "code",
"source": [
"parameters[nvar+1] = exp(parameters[nvar+1])"
],
"metadata": {},
"execution_count": 7
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"In order to obtain the correct Hessian matrix, we have to \"push\" the actual parameter values\n",
"that maximizes the likelihood function since the `TwiceDifferentiable` command uses the next to last\n",
"values to calculate the Hessian:"
],
"metadata": {}
},
{
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "3×3 Array{Float64,2}:\n 179.866 -4.0883 4.71271e-14\n -4.0883 187.31 -7.80393e-14\n 4.71271e-14 -7.80393e-14 94.0065 "
},
"metadata": {},
"execution_count": 8
}
],
"cell_type": "code",
"source": [
"numerical_hessian = hessian!(func,parameters)"
],
"metadata": {},
"execution_count": 8
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"We can now invert our Hessian matrix to obtain the variance-covariance matrix:"
],
"metadata": {}
},
{
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "3×3 Array{Float64,2}:\n 0.00556246 0.000121409 -2.68777e-18\n 0.000121409 0.00534141 4.37329e-18\n -2.68777e-18 4.37329e-18 0.0106376 "
},
"metadata": {},
"execution_count": 9
}
],
"cell_type": "code",
"source": [
"var_cov_matrix = inv(numerical_hessian)"
],
"metadata": {},
"execution_count": 9
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"In this example, we are only interested in the statistical significance of the coefficient estimates\n",
"so we obtain those with the following command:"
],
"metadata": {}
},
{
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "2-element Array{Float64,1}:\n 3.00877\n 3.02571"
},
"metadata": {},
"execution_count": 10
}
],
"cell_type": "code",
"source": [
"β = parameters[1:nvar]"
],
"metadata": {},
"execution_count": 10
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"We now need to obtain those elements of the variance-covariance matrix needed to obtain our\n",
"t-statistics, and we can do this with the following commands:"
],
"metadata": {}
},
{
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "2-element Array{Float64,1}:\n 0.00556246\n 0.00534141"
},
"metadata": {},
"execution_count": 11
}
],
"cell_type": "code",
"source": [
"temp = diag(var_cov_matrix)\n",
"temp1 = temp[1:nvar]"
],
"metadata": {},
"execution_count": 11
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"The t-statistics are formed by dividing element-by-element the coefficients by their standard errors,\n",
"or the square root of the diagonal elements of the variance-covariance matrix:"
],
"metadata": {}
},
{
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "2-element Array{Float64,1}:\n 40.3419\n 41.4 "
},
"metadata": {},
"execution_count": 12
}
],
"cell_type": "code",
"source": [
"t_stats = β./sqrt.(temp1)"
],
"metadata": {},
"execution_count": 12
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"From here, one may examine other statistics of interest using the output from the optimization routine."
],
"metadata": {}
},
{
"outputs": [],
"cell_type": "markdown",
"source": [
"*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*"
],
"metadata": {}
}
],
"nbformat_minor": 3,
"metadata": {
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "0.6.2"
},
"kernelspec": {
"name": "julia-0.6",
"display_name": "Julia 0.6.2",
"language": "julia"
}
},
"nbformat": 4
}
using Optim
using NLSolversBase
using ForwardDiff
using LinearAlgebra
n = 500 # Number of observations
nvar = 2 # Number of variables
β = ones(nvar) * 3.0 # True coefficients
x = [ones(n) randn(n, nvar - 1)] # X matrix of explanatory variables plus constant
ε = randn(n) * 0.5 # Error variance
y = x * β + ε # Generate Data
function Log_Likelihood(X, Y, β, log_σ)
σ = exp(log_σ)
llike = -n/2*log(2π) - n/2* log(σ^2) - (sum((Y - X * β).^2) / (2σ^2))
llike = -llike
end
func = TwiceDifferentiable(vars -> Log_Likelihood(x, y, vars[1:nvar], vars[nvar + 1]), ones(nvar+1); autodiff=:forward)
opt = optimize(func, ones(nvar+1))
parameters = Optim.minimizer(opt)
parameters[nvar+1] = exp(parameters[nvar+1])
numerical_hessian = NLSolversBase.hessian!(func,parameters)
temporary = vars -> Log_Likelihood(x, y, vars[1:nvar], vars[nvar + 1])
numerical_hessian2 = ForwardDiff.hessian(temporary, parameters)
var_cov_matrix = inv(numerical_hessian)
var_cov_matrix = inv(numerical_hessian2)
β = parameters[1:nvar]
temp = diag(var_cov_matrix)
temp1 = temp[1:nvar]
t_stats = β./sqrt.(temp1)
```@meta
EditURL = "https://github.com/TRAVIS_REPO_SLUG/blob/master/../../Desktop/Julia SAR Maximum Likelihood/Maximum Likehood Tutorial/maxlikenlm.jl"
```
# Maximum Likelihood Estimation in Julia: The Normal Linear Model
The following tutorial will introduce maximum likelihood estimation in Julia for
the normal linear model.
The normal linear model (sometimes referred to as the OLS model) is the workhorse of
regression modeling and is utilized across a number of diverse fields.
In this tutorial, we will utilize simulated data to
demonstrate how Julia can be used to recover the parameters of interest.
The first order of business is to use the `Optim` package to Julia and also include the `NLSolversBase` routine:
```@example maxlikenlm
using Optim
using NLSolversBase
```
!!! Tip
Add Optim and NLopt with the following command at the Julia command prompt:
Pkg.add("Optim") and Pkg.add("NLopt")
The first item that needs to be addressed is the data generating process or DGP.
The following code will produce data from a nomral linear model:
```@example maxlikenlm
n = 500 # Number of observations
nvar = 2 # Number of variables
β = ones(nvar) * 3.0 # True coefficients
x = [ones(n) randn(n, nvar - 1)] # X matrix of explanatory variables plus constant
ε = randn(n) * 0.5 # Error variance
y = x * β + ε # Generate Data
```
In the above example, we have 500 observations, 2 explanatory variables plus an intercept,
an error variance equal to 0.5, coefficients equal to 3.0, and all of these are subject to change by the user.
Since we know the true value of these parameters, we should obtain these values when we maximize the likelihood function.
The next step in our tutorial is to define a Julia function for the likelihood function. The following function defines the likelihood
function for the normal linear model:
```@example maxlikenlm
function Log_Likelihood(X, Y, β, log_σ)
σ = exp(log_σ)
llike = -n/2*log(2π) - n/2* log(σ^2) - (sum((Y - X * β).^2) / (2σ^2))
llike = -llike
end
```
The log likelihood function accepts 4 inputs: the matrix of explanatory variables (X), the dependent variable (Y),
the β's, and the error varicance. Note that we exponentiate the error variance in the second line of the code because the
error variance cannot be negative and we want to avoid this situation when maximizing the likelihood.
The next step in our tutorial is to optimize our function. We first use the `TwiceDifferentiable` command in order to obtain
the Hessian matrix later on, which will be used to help form t-statistics:
```@example maxlikenlm
func = TwiceDifferentiable(vars -> Log_Likelihood(x, y, vars[1:nvar], vars[nvar + 1]), ones(nvar+1); autodiff=:forward)
```
The above statment accepts 4 inputs: the x matrix, the dependent variable y, and a vector of β's and the error variance.
The `vars[1:nvar]` is how we pass the vector of β's and the `vars[nvar + 1]` is how we pass the error variance. You can think
of this as a vector of parameters with the first 2 being β's and the last one is the error variance.
The `ones(nvar+1)` are the starting values for the parameters and the `autodiff=:forward` command performs forward mode
automatic differentiation.
The actual optimization of the likelihood function is accomplished with the following command:
```@example maxlikenlm
opt = optimize(func, ones(nvar+1))
```
The first input to the command is the function we wish to optimize and the second input are the starting values.
After a brief period of time, you should see output of the optimization routine, with the parameter
estimates being very close to our simulated values.
The optimization routine stores several quantities and we can obtain the maximim likelihood estimates with
the following command:
```@example maxlikenlm
parameters = Optim.minimizer(opt)
```
!!! Note
Fieldmes for all of the quantities can be obtained with the following command:
fieldnames(opt)
Since we paramaterized our likelihood to use the exponentiated value, we need to exponentiate it
to get back to our original log scale:
```@example maxlikenlm
parameters[nvar+1] = exp(parameters[nvar+1])
```
In order to obtain the correct Hessian matrix, we have to "push" the actual parameter values
that maximizes the likelihood function since the `TwiceDifferentiable` command uses the next to last
values to calculate the Hessian:
```@example maxlikenlm
numerical_hessian = hessian!(func,parameters)
```
We can now invert our Hessian matrix to obtain the variance-covariance matrix:
```@example maxlikenlm
var_cov_matrix = inv(numerical_hessian)
```
In this example, we are only interested in the statistical significance of the coefficient estimates
so we obtain those with the following command:
```@example maxlikenlm
β = parameters[1:nvar]
```
We now need to obtain those elements of the variance-covariance matrix needed to obtain our
t-statistics, and we can do this with the following commands:
```@example maxlikenlm
temp = diag(var_cov_matrix)
temp1 = temp[1:nvar]
```
The t-statistics are formed by dividing element-by-element the coefficients by their standard errors,
or the square root of the diagonal elements of the variance-covariance matrix:
```@example maxlikenlm
t_stats = β./sqrt.(temp1)
```
From here, one may examine other statistics of interest using the output from the optimization routine.
*This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
using Optim
using NLSolversBase
using ForwardDiff
using LinearAlgebra
n = 500 # Number of observations
nvar = 2 # Number of variables
β = ones(nvar) * 3.0 # True coefficients
x = [ones(n) randn(n, nvar - 1)] # X matrix of explanatory variables plus constant
ε = randn(n) * 0.5 # Error variance
y = x * β + ε # Generate Data
function Log_Likelihood(X, Y, β, log_σ)
σ = exp(log_σ)
llike = -n/2*log(2π) - n/2* log(σ^2) - (sum((Y - X * β).^2) / (2σ^2))
llike = -llike
end
func = TwiceDifferentiable(vars -> Log_Likelihood(x, y, vars[1:nvar], vars[nvar + 1]), ones(nvar+1); autodiff=:forward)
opt = optimize(func, ones(nvar+1))
parameters = Optim.minimizer(opt)
parameters[nvar+1] = exp(parameters[nvar+1])
numerical_hessian = NLSolversBase.hessian!(func,parameters)
temporary = vars -> Log_Likelihood(x, y, vars[1:nvar], vars[nvar + 1])
numerical_hessian2 = ForwardDiff.hessian(temporary, parameters)
var_cov_matrix = inv(numerical_hessian)
var_cov_matrix = inv(numerical_hessian2)
β = parameters[1:nvar]
temp = diag(var_cov_matrix)
temp1 = temp[1:nvar]
t_stats = β./sqrt.(temp1)
EditURL = "https://github.com/TRAVIS_REPO_SLUG/blob/master/../../Desktop/Julia SAR Maximum Likelihood/Maximum Likehood Tutorial/maxlikenlm.jl"

Maximum Likelihood Estimation in Julia: The Normal Linear Model

The following tutorial will introduce maximum likelihood estimation in Julia for the normal linear model.

The normal linear model (sometimes referred to as the OLS model) is the workhorse of regression modeling and is utilized across a number of diverse fields. In this tutorial, we will utilize simulated data to demonstrate how Julia can be used to recover the parameters of interest.

The first order of business is to use the Optim package to Julia and also include the NLSolversBase routine:

using Optim
using NLSolversBase

!!! Tip Add Optim and NLopt with the following command at the Julia command prompt: Pkg.add("Optim") and Pkg.add("NLopt")

The first item that needs to be addressed is the data generating process or DGP. The following code will produce data from a nomral linear model:

n = 500                             # Number of observations
nvar = 2                            # Number of variables
β = ones(nvar) * 3.0                # True coefficients
x = [ones(n) randn(n, nvar - 1)]    # X matrix of explanatory variables plus constant
ε = randn(n) * 0.5                  # Error variance
y = x * β + ε                       # Generate Data

In the above example, we have 500 observations, 2 explanatory variables plus an intercept, an error variance equal to 0.5, coefficients equal to 3.0, and all of these are subject to change by the user. Since we know the true value of these parameters, we should obtain these values when we maximize the likelihood function.

The next step in our tutorial is to define a Julia function for the likelihood function. The following function defines the likelihood function for the normal linear model:

function Log_Likelihood(X, Y, β, log_σ)
    σ = exp(log_σ)
    llike = -n/2*log(2π) - n/2* log(σ^2) - (sum((Y - X * β).^2) / (2σ^2))
    llike = -llike
end

The log likelihood function accepts 4 inputs: the matrix of explanatory variables (X), the dependent variable (Y), the β's, and the error varicance. Note that we exponentiate the error variance in the second line of the code because the error variance cannot be negative and we want to avoid this situation when maximizing the likelihood.

The next step in our tutorial is to optimize our function. We first use the TwiceDifferentiable command in order to obtain the Hessian matrix later on, which will be used to help form t-statistics:

func = TwiceDifferentiable(vars -> Log_Likelihood(x, y, vars[1:nvar], vars[nvar + 1]), ones(nvar+1); autodiff=:forward)

The above statment accepts 4 inputs: the x matrix, the dependent variable y, and a vector of β's and the error variance. The vars[1:nvar] is how we pass the vector of β's and the vars[nvar + 1] is how we pass the error variance. You can think of this as a vector of parameters with the first 2 being β's and the last one is the error variance.

The ones(nvar+1) are the starting values for the parameters and the autodiff=:forward command performs forward mode automatic differentiation.

The actual optimization of the likelihood function is accomplished with the following command:

opt = optimize(func, ones(nvar+1))

The first input to the command is the function we wish to optimize and the second input are the starting values.

After a brief period of time, you should see output of the optimization routine, with the parameter estimates being very close to our simulated values.

The optimization routine stores several quantities and we can obtain the maximim likelihood estimates with the following command:

parameters = Optim.minimizer(opt)

!!! Note Fieldmes for all of the quantities can be obtained with the following command: fieldnames(opt)

Since we paramaterized our likelihood to use the exponentiated value, we need to exponentiate it to get back to our original log scale:

parameters[nvar+1] = exp(parameters[nvar+1])

In order to obtain the correct Hessian matrix, we have to "push" the actual parameter values that maximizes the likelihood function since the TwiceDifferentiable command uses the next to last values to calculate the Hessian:

numerical_hessian = hessian!(func,parameters)

We can now invert our Hessian matrix to obtain the variance-covariance matrix:

var_cov_matrix = inv(numerical_hessian)

In this example, we are only interested in the statistical significance of the coefficient estimates so we obtain those with the following command:

β = parameters[1:nvar]

We now need to obtain those elements of the variance-covariance matrix needed to obtain our t-statistics, and we can do this with the following commands:

temp = diag(var_cov_matrix)
temp1 = temp[1:nvar]

The t-statistics are formed by dividing element-by-element the coefficients by their standard errors, or the square root of the diagonal elements of the variance-covariance matrix:

t_stats = β./sqrt.(temp1)

From here, one may examine other statistics of interest using the output from the optimization routine.

This page was generated using Literate.jl.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment