<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-18535412</id><updated>2024-08-28T17:53:15.026-07:00</updated><category term="big data"/><category term="2-player"/><category term="glm-speedglm-glmnet comparison"/><category term="glm"/><category term="regression"/><category term="Dixon and Cole"/><category term="algorithms"/><category term="Elo"/><category term="MARSS"/><category term="R"/><category term="speed tests"/><category term="R packages"/><category term="Rcpp"/><category term="RcppArmadillo"/><category term="bayesian"/><category term="fbRanks"/><category term="glmnet"/><category term="interaction strengths"/><category term="lasso regression"/><category term="logistic regression"/><category term="multi-player"/><category term="poisson regression"/><category term="refs of interest"/><category term="sparse matrices"/><category term="unit testing"/><title type='text'>parsimonious pursuits</title><subtitle type='html'>The &lt;a href=&quot;http://en.wikipedia.org/wiki/Open_notebook_science&quot;&gt;open notebook&lt;/a&gt; of E. E. Holmes</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>42</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-18535412.post-5641725909454431773</id><published>2019-02-01T12:27:00.000-08:00</published><updated>2019-02-04T12:27:37.339-08:00</updated><title type='text'>Native R versus tensorflow for matrix math speed comparison</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;a href=&quot;https://www.dummies.com/web-design-development/other-web-software/create-vector-matrix-operations-tensorflow/&quot;&gt;https://www.dummies.com/web-design-development/other-web-software/create-vector-matrix-operations-tensorflow/&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
Out of curiosity, I coded up a simple speed comparison of a matrix multiplication problem in native R versus tf$matmul in the tensorflow package in R. &amp;nbsp;This was on my laptop and tensorflow is meant to allow distributed computing on multiple CPU/GPU, so this isn&#39;t the right sort of application for tensorFlow. &amp;nbsp;Nonetheless, tensorflow have tensor multiplication functions which would make some of the MARSS EM calculations more compact, avoiding for loops.&lt;br /&gt;
&lt;br /&gt;
For this test, I had a 30x60x900 matrix. &amp;nbsp;I do the following tests&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;X[j,,] %*% t(X[j,,]) and sum across 1st dim&lt;/li&gt;
&lt;li&gt;X[,,j] %*% t(X[,,j]) and sum across 3rd dim&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
The second test requires 2 calls to tf$transpose which slows things down quite a bit, but matches the way I have arrays stored in MARSS (with time in 3rd dim). &amp;nbsp;The 2 calls to transpose can be avoided by using tf$einsum but that doesn&#39;t seem to give any speed gains.&lt;br /&gt;
&lt;br /&gt;
Test 1 tensorflow is faster 2x. &amp;nbsp;So not much gain. &amp;nbsp;Note it is only faster for big matrices. &amp;nbsp;Much slower for small matrices.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;br /&gt;
Unit: milliseconds&lt;br /&gt;
&amp;nbsp; &amp;nbsp; expr &amp;nbsp; &amp;nbsp; &amp;nbsp;min &amp;nbsp; &amp;nbsp; &amp;nbsp; lq &amp;nbsp; &amp;nbsp; mean &amp;nbsp; median &amp;nbsp; &amp;nbsp; &amp;nbsp; uq &amp;nbsp; &amp;nbsp; &amp;nbsp; max neval&lt;br /&gt;
&amp;nbsp; funy() 36.75568 43.13249 48.92774 46.30748 &amp;nbsp;51.9293 &amp;nbsp;70.86605 &amp;nbsp; 100&lt;br /&gt;
&amp;nbsp;funx(X) 79.40066 86.42067 97.32483 95.05786 103.7837 229.00092 &amp;nbsp; 100&lt;/div&gt;
&lt;br /&gt;
Test 2 tensorflow is slower 2x due to the extra tf$transpose call. &amp;nbsp;However this depends on the size of the 3rd dimension. &amp;nbsp;When I changed it so that the array was n^2 x 2n x n, tensorflow code was faster.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;br /&gt;
Unit: milliseconds&lt;br /&gt;
&amp;nbsp; &amp;nbsp; expr &amp;nbsp; &amp;nbsp; &amp;nbsp;min &amp;nbsp; &amp;nbsp; &amp;nbsp; lq &amp;nbsp; &amp;nbsp; mean &amp;nbsp; median &amp;nbsp; &amp;nbsp; &amp;nbsp; uq &amp;nbsp; &amp;nbsp; &amp;nbsp;max neval&lt;br /&gt;
&amp;nbsp; funy() 73.45847 80.07081 85.67677 86.22445 91.47107 97.61655 &amp;nbsp; &amp;nbsp;10&lt;br /&gt;
&amp;nbsp;funx(X) 42.00226 43.86015 46.94928 46.94643 48.94002 55.19185 &amp;nbsp; &amp;nbsp;10&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Code is below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;br /&gt;
# This takes a 3D array, multiplies and sums up along 1st dimension&lt;br /&gt;
&lt;br /&gt;
library(tensorflow)&lt;br /&gt;
&lt;br /&gt;
x &amp;lt;- tf$placeholder(&quot;float&quot;, shape=shape(NULL,NULL,NULL))&lt;br /&gt;
y = tf$matmul(x,tf$transpose(x, perm=c(0L,2L,1L)))&lt;br /&gt;
z &amp;lt;- tf$reduce_sum(y, c(0L))&lt;br /&gt;
&lt;br /&gt;
# write comparison funcs&lt;br /&gt;
&lt;br /&gt;
funx&amp;lt;-function(x){&lt;br /&gt;
&amp;nbsp; tmp &amp;lt;- tcrossprod(x[1,,])&lt;br /&gt;
&amp;nbsp; for(i in 2:dim(x)[1]){&lt;br /&gt;
&amp;nbsp; &amp;nbsp; tmp &amp;lt;- tcrossprod(x[i,,])+tmp&lt;br /&gt;
&amp;nbsp; }&lt;br /&gt;
&amp;nbsp; tmp&lt;br /&gt;
&amp;nbsp; }&lt;br /&gt;
funy&amp;lt;-function(){ sess$run(z, feed_dict = dict(x = X)) }&lt;br /&gt;
&lt;br /&gt;
n &amp;lt;-30&lt;br /&gt;
X = array(rnorm(n+2*n+3*n),dim=c(n, 2*n, n^2))&lt;br /&gt;
tmp &amp;lt;- sess$run(z, feed_dict = dict(x = X))&lt;br /&gt;
&lt;br /&gt;
mx &amp;lt;- microbenchmark( funy(), funx(X))&lt;br /&gt;
autoplot(mx)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
######&lt;br /&gt;
&lt;br /&gt;
# This takes a 3D array, multiplies and sums up along 3rd dimension&lt;br /&gt;
&lt;br /&gt;
library(tensorflow)&lt;br /&gt;
&lt;br /&gt;
x &amp;lt;- tf$placeholder(&quot;float&quot;, shape=shape(NULL,NULL,NULL))&lt;br /&gt;
y = tf$matmul(tf$transpose(x, perm=c(2L,0L,1L)),tf$transpose(x, perm=c(2L,1L,0L)))&lt;br /&gt;
# note you can write this more succinctly with einsum but it doesn&#39;t speed things up&lt;br /&gt;
# y =&amp;nbsp;tf$einsum(&#39;ijl,kjl-&amp;gt;ikl&#39;, x, x)&lt;br /&gt;
z &amp;lt;- tf$reduce_sum(y, c(0L))&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
# write comparison funcs&lt;br /&gt;
&lt;br /&gt;
funx&amp;lt;-function(x){&lt;br /&gt;
&amp;nbsp; tmp &amp;lt;- tcrossprod(x[,,1])&lt;br /&gt;
&amp;nbsp; for(i in 2:dim(x)[3]){&lt;br /&gt;
&amp;nbsp; &amp;nbsp; tmp &amp;lt;- tcrossprod(x[,,i])+tmp&lt;br /&gt;
&amp;nbsp; }&lt;br /&gt;
&amp;nbsp; tmp&lt;br /&gt;
}&lt;br /&gt;
funy&amp;lt;-function(){ sess$run(z, feed_dict = dict(x = X)) }&lt;br /&gt;
&lt;br /&gt;
n &amp;lt;-30&lt;br /&gt;
X = array(rnorm(n+2*n+3*n),dim=c(n, 2*n, n^2))&lt;br /&gt;
tmp &amp;lt;- sess$run(z, feed_dict = dict(x = X))&lt;br /&gt;
&lt;br /&gt;
mx &amp;lt;- microbenchmark( funy(), funx(X), times=10)&lt;br /&gt;
autoplot(mx)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/5641725909454431773'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/5641725909454431773'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2019/02/native-r-versus-tensorflow-for-matrix.html' title='Native R versus tensorflow for matrix math speed comparison'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-3514016489059462689</id><published>2017-05-31T17:19:00.000-07:00</published><updated>2017-12-06T16:40:27.780-08:00</updated><title type='text'>Notes on computing the Fisher Information matrix for MARSS models. Part IV Recursion in Harvey 1989</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;script type=&quot;text/x-mathjax-config&quot;&gt;
  MathJax.Hub.Config({ TeX: { equationNumbers: {autoNumber: &quot;AMS&quot;} } });
&lt;/script&gt;
&lt;script src=&#39;https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&#39; type=&#39;text/javascript&#39;&gt;
&lt;/script&gt;
&lt;i&gt;MathJax and blogger can be iffy.  Try reloading if the equations don&#39;t show up.&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;

Notes on computing the Fisher Information matrix for MARSS models &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2016/05/notes-on-computing-fisher-information.html&quot;&gt;Part I Background&lt;/a&gt;, &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2016/05/notes-on-computing-fisher-information_19.html&quot;&gt;Part II Louis 1982&lt;/a&gt;,  &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2016/06/notes-on-computing-fisher-information.html&quot;&gt;Part III Overview of Harvey 1989&lt;/a&gt;.  &lt;br /&gt;&lt;br /&gt;

Part III Introduced the approach of Harvey (1989) for computing the expected and observed Fisher Information matrices by using the prediction error form of the log-likelihood function.  Here I show the Harvey (1989) recursion on page 143 for computing the derivatives in his equations.  

&lt;h2&gt;Derivatives needed for the 2nd derivative of the conditional log-likelihood&lt;/h2&gt;

Equations 3.4.66 and 3.4.69 in Harvey (1989) have first and second derivatives of \(v_t\) and \(F_t\) with respect to \( \theta_i \) and \(\theta_j\). These in turn involve derivatives of the parameter matrices and of \(\tilde{x}_{t|t}\) and \(\tilde{V}_{t|t}\).  Harvey shows all the first derivatives, and it is easy to compute the second derivatives by taking the derivatives of the first. 
&lt;br /&gt;&lt;br /&gt;
The basic idea of the recursion is simple, if a bit tedious.  
&lt;ul&gt;
&lt;li&gt;First we set up matrices for all the first derivatives of the parameters.&lt;/li&gt;  
&lt;li&gt;Then starting from t=1 and working forward, we will do the recursion (described below) for all \(\theta_i\) and we store the first derivatives of \(v_t\), \(F_t\), \(\tilde{x}_{t|t}\) and \(\tilde{V}_{t|t}\) with respect to \(\theta_i\).&lt;/li&gt;
&lt;li&gt;Then we go through the parameter vector a second time, to get all the second derivatives with respect to \(\theta_i\) and \(\theta_j\).&lt;/li&gt;
&lt;li&gt;We input the first and second derivatives of \(v_t\) and \(F_t\) into equations 3.4.66 and 3.4.69 to get the observed Fisher Information at time t and add to the Fisher Information from the previous time step. The Fisher Information matrix is symmetric, so we can use an outer loop from \(\theta_1\) to \(\theta_p\) (\(p\) is the number of parameters) and an inner loop from \(\theta_i\) to \(\theta_p\).  That will be \(p(p-1)/2\) loops for each time step.
&lt;/ul&gt;
The end result with be the observed Fisher Information matrix using equation 3.4.66 and using 3.4.69.

&lt;h2&gt;Outline of the loops in the recursion&lt;/h2&gt;

This is a forward recursion starting at t=1.  We will save the previous time step&#39;s \( \partial v_t / \theta_i \) and \( \partial F_t / \theta_i \).  That will be p x 2 (n x 1) vectors and n x 2 (n x n) matrices. We do not need to store all the previous time steps since this is a one-pass recursion unlike the Kalman smoother, which is forward-backward.

&lt;br /&gt;&lt;br /&gt;
Set-up&lt;br/&gt;
Number of parameters = p.&lt;br/&gt;
Create Iijt and oIijt which are p x p matrices.&lt;br/&gt;
Create dvit which is a  n x p matrix. n Innovations and p \(\theta_i\).&lt;br/&gt;
Create d2vijt which is a  n x p x p array. n Innovations and p \(\theta_i\).&lt;br/&gt;
Create dFit which is a  n x n x p array. n x n Sigma matrix and p \(\theta_i\).&lt;br/&gt;
Create d2Fijt which is a  n x n x p x p array. n x n Sigma matrix and p \(\theta_i\).&lt;br/&gt;

&lt;br/&gt;&lt;br/&gt;
Outer loop from t=1 to t=T.&lt;br/&gt;
Inner loop over all MARSS parameters: x0, V0, Z, a, R, B, u, Q. This is par$Z, e.g., and is a vector of the estimated parameters elements in Z.&lt;br/&gt;
Inner loop over parameters in parameter matrix, so, e.g. over the rows in the column vector par$Z.&lt;br/&gt;
Keep track of what parameter element I am on via p counter.&lt;br/&gt;



&lt;h3&gt;The form of the parameter derivatives&lt;/h3&gt;

Within the recursion, we have terms like, \( \partial M/\partial \theta_i\), where M means some parameter matrix.
We can write M as \( vec(M)=f+D\theta_m \), where \(\theta_m\) is the vector of parameters that appear in M.  This  is the way that matrices are written in Holmes (2010).  So
\begin{equation} 
\begin{bmatrix}2a+c&amp;b\\b&amp;a+1\end{bmatrix}
\end{equation}
is written in vec form as
\begin{equation} 
\begin{bmatrix}0\\0\\0\\1\end{bmatrix}+\begin{bmatrix}2&amp;0&amp;1\\ 0&amp;1&amp;0\\ 0&amp;1&amp;0\\ 1&amp;0&amp;0 \end{bmatrix}\begin{bmatrix}a\\b\\c\end{bmatrix}
\end{equation}
The derivative of this with respect to \( \theta_i=a\) is
\begin{equation} \label{dpar}
\begin{bmatrix}0\\0\\0\\1\end{bmatrix}+\begin{bmatrix}2&amp;0&amp;1\\ 0&amp;1&amp;0\\ 0&amp;1&amp;0\\ 1&amp;0&amp;0 \end{bmatrix}\begin{bmatrix}1\\0\\0\end{bmatrix}
\end{equation}
So in MARSS, \( \partial M/\partial \theta_i\) would be 
&lt;pre&gt;
dthetai=matrix(0,ip,1); dthetai[i,]=1 #set up the d theta_i bit.
dM=unvec(f+D%*%dthetai,dim(M)) #only needed if M is matrix
&lt;/pre&gt;
The reason is that MARSS allows any linear constraint of the form \(\alpha+\beta a + \beta_2 b\), etc.  The vec form allows me to work with a generic linear constraint without having to know the exact form of that constraint.  The model and parameters are all specified in vec form with f, D, and p matrices (lower case = column vector).
&lt;br /&gt;&lt;br /&gt;
The second derivative of a parameter matrix with respect to \( \theta_j \) is always 0 since \ref{dpar} has no parameters in it, only constants.

&lt;h3&gt;Derivatives of the innovations and variance of innovations&lt;/h3&gt;

Equation 3.4.71b in Harvey shows \( \partial v_t / \partial \theta_i\). Store result in dvit[,p].
\begin{equation}
\frac{\partial v_t}{\partial \theta_i}= -Z_t \frac{\partial \tilde{x}_{t|t-1}}{\partial \theta_i}- \frac{Z_t}{\partial \theta_i}\tilde{x}_{t|t-1}- \frac{\partial a_t}{\partial \theta_i}
\end{equation}
\(\tilde{x}_{t|t-1}\) is the one-step ahead prediction covariance output from the Kalman filter, and in MARSSkf is xtt1[,t].
Next, use equation 3.4.73, to get \( \partial F_t / \partial \theta_i\). Store result in dFit[,,p].
\begin{equation}
\frac{\partial F_t}{\partial \theta_i}= 
 \frac{\partial Z_t}{\partial \theta_i} \tilde{V}_{t|t-1} Z_t^\top + 
Z_t \frac{\partial \tilde{V}_{t|t-1}}{\partial \theta_i} Z_t^\top +
Z_t \tilde{V}_{t|t-1} \frac{\partial Z_t^\top}{\partial \theta_i} + \frac{\partial (H_t R_t H_t^\top)}{\partial \theta_i}
\end{equation}
\(\tilde{V}_{t|t-1}\) is the one-step ahead prediction covariance output from the Kalman filter, and in MARSSkf is denoted Vtt1[,,t].

&lt;h3&gt;Recursion for derivatives of states and variance of states&lt;/h3&gt;

&lt;hr&gt;If t=1&lt;hr&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Case 1&lt;/b&gt;. \(\pi=x_0\) is treated as a parameter and \(V_0 = 0\).  For any \(\theta_i\) that is not in \(\pi\), \(Z\) or \(a\),  \(\partial v_1/\partial \theta_i\ = 0\).  For any \(\theta_i\) that is not in  \(Z\) or \(R\),  \(\partial F_1/\partial \theta_i\ = 0\) (a n x n matrix of zeros).  
&lt;br/&gt;&lt;br/&gt;
From equation 3.4.73a:
\begin{equation} 
\frac{\partial \tilde{x}_{1|0}}{\partial\theta_i } = \frac{\partial B_1}{\partial \theta_i} \pi + B_1 \frac{\partial \pi}{\partial \theta_i} + \frac{\partial u_t}{\partial \theta_i}
\end{equation}
From equation 3.4.73b and using  \(V_0 = 0\): 
\begin{equation} 
\frac{\partial \tilde{V}_{1|0}}{\partial\theta_i } = \frac{\partial B_1}{\partial \theta_i} V_0 B_1^\top + B_1 \frac{\partial V_0}{\partial \theta_i} B_1^\top + B_1 V_0 \frac{\partial B_1^\top}{\partial \theta_i} + \frac{\partial (G_t Q_t G_t^\top)}{\partial \theta_i} = \frac{\partial (G_t Q_t G_t^\top)}{\partial \theta_i}
\end{equation}
&lt;/li&gt;
&lt;br/&gt;&lt;br/&gt;
&lt;li&gt;&lt;b&gt;Case 2&lt;/b&gt;. \(\pi=x_{1|0}\) is treated as a parameter and \(V_{1|0}=0\). 
\[ \frac{\partial \tilde{x}_{1|0}}{\partial \theta_i}=\frac{\partial \pi}{\partial \theta_i}
 \text{ and }
 \partial V_{1|0}/\partial\theta_i = 0 \]. 
&lt;/li&gt;
&lt;br/&gt;&lt;br/&gt;
&lt;li&gt;&lt;b&gt;Case 3&lt;/b&gt;. \( x_0\) is specified by a  fixed prior.  \(x_0=\pi\) and \(V_0=\Lambda\). The derivatives of these are 0, because they are fixed.
&lt;br/&gt;&lt;br/&gt;
From equation 3.4.73a  and using  \(x_0 = \pi\) and \(\partial \pi/\partial \theta_i = 0\):
\begin{equation} 
\frac{\partial \tilde{x}_{1|0}}{\partial\theta_i } = \frac{\partial B_1}{\partial \theta_i} \pi + B_1 \frac{\partial \pi}{\partial \theta_i} + \frac{\partial u_t}{\partial \theta_i}=\frac{\partial B_1}{\partial \theta_i} \pi + \frac{\partial u_t}{\partial \theta_i}
\end{equation}
From equation 3.4.73b and using  \(V_0 = \Lambda\) and \(\partial \Lambda/\partial \theta_i = 0\): 
\begin{equation} 
\frac{\partial \tilde{V}_{1|0}}{\partial\theta_i } = \frac{\partial B_1}{\partial \theta_i} V_0 B_1^\top + B_1 \frac{\partial V_0}{\partial \theta_i} B_1^\top + B_1 V_0 \frac{\partial B_1^\top}{\partial \theta_i} + \frac{\partial (G_t Q_t G_t^\top)}{\partial \theta_i} = \frac{\partial B_1}{\partial \theta_i} \Lambda B_1^\top +  B_1 \Lambda \frac{\partial B_1^\top}{\partial \theta_i} + \frac{\partial (G_t Q_t G_t^\top)}{\partial \theta_i}
\end{equation}
&lt;/li&gt;
&lt;br/&gt;&lt;br/&gt;
&lt;li&gt;&lt;b&gt;Case 4&lt;/b&gt;. \(x_{1|0}\) is specified by a fixed prior. \(x_{1|0}=\pi\) and \(V_{1|0} = \Lambda\).  \(\partial V_{1|0}/\partial\theta_i = 0\) and  \(\partial x_{1|0}/\partial\theta_i = 0\).
&lt;/li&gt;
&lt;br/&gt;&lt;br/&gt;
&lt;li&gt;&lt;b&gt;Case 5&lt;/b&gt;. Estimate \( V_0\) or \( V_{1|0}\).  That is unstable (per Harvey 1989, somewhere).  I don&#39;t allow that in the MARSS package.
&lt;/li&gt;
&lt;/ul&gt;
&lt;br/&gt;&lt;br/&gt;
When coding this recursion, I will loop though the MARSS parameters (x0, V, Z, a, R, B, u, Q) and within that loop, loop through the individual parameters within the parameter vector.  So say Q is diagonal and unequal.  It has m variance parameters, and I&#39;ll loop through each.
&lt;br/&gt;&lt;br/&gt;
Now we have \(\frac{\partial \tilde{x}_{1|0}}{\partial \theta_i}\) and \(\frac{\partial \tilde{V}_{1|0}}{\partial \theta_i}\) for \(t=1\) and we can proceed.
&lt;hr&gt;If t&gt;1&lt;hr&gt;

The derivative of \(\tilde{x}_{t|t-1}\) is (3.4.73a in Harvey)
\begin{equation} 
\frac{\partial \tilde{x}_{t|t-1}}{\partial\theta_i } = \frac{\partial B_t}{\partial \theta_i} \tilde{x}_{t-1|t-1} + B_t \frac{\partial \tilde{x}_{t-1|t-1}}{\partial \theta_i} + \frac{\partial u_t}{\partial \theta_i}
\end{equation}
Then we take the derivative of this to get the second partial derivative.
\begin{align} 
\frac{\partial^2 \tilde{x}_{t|t-1}}{\partial\theta_i \partial\theta_j} = 
\frac{\partial^2 B_t}{\partial\theta_i \partial\theta_j} \tilde{x}_{t-1|t-1} +
 \frac{\partial B_t}{\partial \theta_i}\frac{\partial \tilde{x}_{t-1|t-1}}{\partial \theta_j} +
 \frac{\partial B_t}{\partial \theta_j} \frac{\partial \tilde{x}_{t-1|t-1}}{\partial \theta_i} + 
 B_t \frac{\partial^2 \tilde{x}_{t-1|t-1}}{\partial\theta_i \partial\theta_j} + 
\frac{\partial^2 u_t}{\partial\theta_i \partial\theta_j}\\
= \frac{\partial B_t}{\partial \theta_i}\frac{\partial \tilde{x}_{t-1|t-1}}{\partial \theta_j} +
 \frac{\partial B_t}{\partial \theta_j} \frac{\partial \tilde{x}_{t-1|t-1}}{\partial \theta_i} + 
 B_t \frac{\partial^2 \tilde{x}_{t-1|t-1}}{\partial\theta_i \partial\theta_j}
\end{align}
In the equations, \(\tilde{x}_{t|t}\) is output by the Kalman filter.  In MARSSkf, it is called xtt[,t]. \(\tilde{x}_{t-1|t-1}\) would be called xtt[,t-1]. The derivatives of \(\tilde{x}_{t-1|t-1}\) is from the next part of the recursion (below).
&lt;/br&gt;&lt;/br&gt;
The derivative of \(\tilde{V}_{t|t-1}\) is (3.4.73b in Harvey)
\begin{equation} \label{derivVtt1}
\frac{\partial \tilde{V}_{t|t-1}}{\partial\theta_i } =
 \frac{\partial B_t}{\partial \theta_i} \tilde{V}_{t-1|t-1} B_t^\top + B_t \frac{\partial \tilde{V}_{t-1|t-1}}{\partial \theta_i} B_t^\top + B_t \tilde{V}_{t-1|t-1} \frac{\partial B_t^\top}{\partial \theta_i} + \frac{\partial (G_t Q_t G_t^\top)}{\partial \theta_i} 
\end{equation}
The second derivative of \(\tilde{V}_{t|t-1}\) is obtained by taking the derivative of \ref{derivVtt1} and eliminating any second derivatives of parameters:
\begin{align} 
\frac{\partial^2 \tilde{V}_{t|t-1}}{\partial\theta_i \partial\theta_j} =
\frac{\partial B_t}{\partial \theta_i} \frac{\tilde{V}_{t-1|t-1}}{\partial\theta_j} B_t^\top + 
\frac{\partial B_t}{\partial \theta_i} \tilde{V}_{t-1|t-1} \frac{\partial B_t^\top}{\partial \theta_j} + 
\frac{\partial B_t}{\partial \theta_j} \frac{\partial \tilde{V}_{t-1|t-1}}{\partial \theta_i} B_t^\top + 
B_t \frac{\partial^2 \tilde{V}_{t-1|t-1}}{\partial\theta_i \partial\theta_j} B_t^\top + \\
B_t \frac{\partial \tilde{V}_{t-1|t-1}}{\partial \theta_i} \frac{\partial B_t^\top}{\partial \theta_j} + 
\frac{\partial B_t}{\partial \theta_j} \tilde{V}_{t-1|t-1} \frac{\partial B_t^\top}{\partial \theta_i} + 
B_t \frac{\tilde{V}_{t-1|t-1}}{\partial\theta_j} \frac{\partial B_t^\top}{\partial \theta_i}
\end{align}
In the derivatives, \(\tilde{V}_{t|t}\) is output by the Kalman filter.  In MARSSkf, it is called Vtt[,t]. \(\tilde{V}_{t-1|t-1}\) would be called Vtt[,t-1].  The derivatives of \(\tilde{V}_{t-1|t-1}\) is from the rest of the recursion (below).
&lt;hr&gt;
Rest of the recursion equations are the same for all t.

From equation 3.4.74a:
\begin{equation} 
\frac{\partial \tilde{x}_{t|t}}{\partial\theta_i } = \frac{\partial \tilde{x}_{t|t-1}}{\partial \theta_i} + \frac{\partial \tilde{V}_{t|t-1}}{\partial \theta_i} Z_t^\top F_t^{-1}v_t + 
\tilde{V}_{t|t-1} \frac{\partial Z_t^\top}{\partial \theta_i} F_t^{-1}v_t - 
\tilde{V}_{t|t-1} Z_t^\top F_t^{-1}\frac{\partial F_t}{\partial \theta_i}F_t^{-1}v_t
+ \tilde{V}_{t|t-1} Z_t^\top F_t^{-1}\frac{\partial v_t}{\partial \theta_i}
\end{equation}
\(\tilde{V}_{t|t-1}\) is output by the Kalman filter.  In MARSSkf, it is called Vtt1[,t]. \(v_t\) are the innovations.  In MARSSkf, they are called Innov[,t].
&lt;br/&gt;&lt;br/&gt;
From equation 3.4.74b:
\begin{equation} 
\begin{split} 
\frac{\partial \tilde{V}_{t|t}}{\partial\theta_i } = &amp;
\frac{\partial \tilde{V}_{t|t-1}}{\partial \theta_i} - 
\frac{\partial \tilde{V}_{t|t-1}}{\partial \theta_i} Z_t^\top F_t^{-1}Z_t \tilde{V}_{t|t-1} -
\tilde{V}_{t|t-1} \frac{\partial Z_t^\top}{\partial \theta_i} F_t^{-1}Z_t \tilde{V}_{t|t-1} + 
\tilde{V}_{t|t-1} Z_t^\top F_t^{-1}\frac{\partial F_t}{\partial \theta_i}F_t^{-1}Z_t \tilde{V}_{t|t-1} - \\
&amp;\tilde{V}_{t|t-1} Z_t^\top F_t^{-1}\frac{\partial Z_t}{\partial \theta_i} \tilde{V}_{t|t-1} -
\tilde{V}_{t|t-1} Z_t^\top F_t^{-1}Z_t \frac{\partial \tilde{V}_{t|t-1}}{\partial \theta_i}
\end{split}
\end{equation}
Repeat for next element in parameter matrix.&lt;br/&gt;
Repeat for parameter matrix.&lt;br/&gt;&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Loop over i = 1 to p.&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Loop over j = i to p.&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Compute \(I_{ij}(\theta)\) and add to previous time step. This is equation 3.4.69 with expectation dropped.  Store in Iij[i,j] and Iij[j,i].
\begin{equation}
I_{ij}(\theta)_t = I_{ji}(\theta)_t = \frac{1}{2}\left[ tr\left[ F_t^{-1}\frac{\partial F_t}{\partial \theta_i}F_t^{-1}\frac{\partial F_t}{\partial \theta_j}\right]\right] + \left(\frac{\partial v_t}{\partial \theta_i}\right)^\top F_t^{-1}\frac{\partial v_t}{\partial \theta_j}
\end{equation}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Add on to previous one:
\[ I_{ij}(\theta) = I_{ij}(\theta) + I_{ij}(\theta)_t \]
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Repeat for next j.&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Repeat for next i.&lt;br/&gt;&lt;br/&gt;
Repeat for next t. &lt;br/&gt;&lt;br/&gt;
At the end, \( I_{ij}(\theta) \) is the observed Fisher Information Matrix.
&lt;br/&gt;&lt;br/&gt;
Note that \(Q\) and \(R\) do not appear in \(\partial v_t/\partial \theta_i\), but all the other parameters do appear. So the second term in \(I_{ij}(\theta) \) is always zero between \(Q\) and \(R\) and any other parameters.  In the second term, \(u\) and \(a\) do not appear, but every other terms do appear.  So the first term in \(I_{ij}(\theta) \) is always zero between \(u\) and \(a\) and any other parameters. This means that there is always zero covariance between  \(u\) or \(a\) and \(Q\) or \(R\). But this will not be the case between \(Q\) or \(R\)  and \(B\) or \(Z\).
&lt;br/&gt;&lt;br/&gt;
Part of the motivation of implementing the Harvey (1989) recursion is that currently in MARSS, I use a numerical estimate of the Fisher Information matrix by using one of R&#39;s functions to return the Hessian.  But it often returns errors.  I might improve it if I constrained it.  If I am only estimating \(u\), \(a\), \(Q\) and \(R\), I could do a two-step process. Get the Hessian holding the variances at the MLEs and then repeat with \(u\) and \(a\) at the MLEs.
&lt;/div&gt;

</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/3514016489059462689/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/3514016489059462689' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3514016489059462689'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3514016489059462689'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2017/05/notes-on-computing-fisher-information.html' title='Notes on computing the Fisher Information matrix for MARSS models. Part IV Recursion in Harvey 1989'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-4568668766381382037</id><published>2016-06-01T16:07:00.002-07:00</published><updated>2017-06-13T13:49:51.364-07:00</updated><title type='text'>Notes on computing the Fisher Information matrix for MARSS models. Part III Overview of Harvey 1989</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;script type=&quot;text/x-mathjax-config&quot;&gt;
  MathJax.Hub.Config({ TeX: { equationNumbers: {autoNumber: &quot;AMS&quot;} } });
&lt;/script&gt;
&lt;script src=&#39;https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&#39; type=&#39;text/javascript&#39;&gt;
&lt;/script&gt;
&lt;i&gt;MathJax and blogger can be iffy.  Try reloading if the equations don&#39;t show up.&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;

Notes on computing the Fisher Information matrix for MARSS models &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2016/05/notes-on-computing-fisher-information.html&quot;&gt;Part I Background&lt;/a&gt;, &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2016/05/notes-on-computing-fisher-information_19.html&quot;&gt;Part II Louis 1982&lt;/a&gt; &lt;br /&gt;&lt;br /&gt;

Part II discussed the approach by Louis 1982 which uses the full-data likelihood and the first derivative of that that is part of the M-step of the EM algorithm.  The conclusion of part II was that that approach is doable but computationally expensive because it scales with \(T^2\) at least.

&lt;br /&gt;&lt;br /&gt;
Here I will review the more common approach (Harvey 1989, pages 140-142, section 3.4.5 Information matrix) which uses the prediction error form of the likelihood function to calculate the observed Fisher Information \( \mathcal{I}(\hat{\theta},y) \).  A related paper is Cavanaugh and Shumway (1996), which presents an approach for calculating the &lt;i&gt;expected&lt;/i&gt; Fisher Information.

&lt;h2&gt;Harvey 1989 recursion for the expected and observed Fisher Information matrix&lt;/h2&gt;
Harvey (1989), pages 140-142, shows how to write the Hessian of the log-likelihood function using the prediction error form of the likelihood.  The prediction error form is: 
\begin{equation}\label{peformlogL}
\log L = \sum_{t=1}^T l_t = \sum_{t=1}^T p(y_t|y_1^{t-1})
\end{equation}
The Hessian of the log-likelihood can then be written as
\begin{equation}\label{hessian}
 \frac{\partial^2 \log L}{\partial\theta_i \partial\theta_j}=\sum{\frac{\partial^2 l_t}{\partial\theta_i \partial\theta_j}}
\end{equation}
and this can be written in terms of derivatives of the innovations \(v_t\) and the variance of the innovations \(F_t\).  This is shown in Equation 3.4.66 in Harvey (1989).  There are a couple differences between the equation below and 3.4.66 in Harvey.  First, 3.4.66 has a typo; the \([I - F_t v_t v_t^\top]\) should be within the trace (as below).  Second, I have written out the derivative with respect to \(\theta_j\) that appears in the first trace term.
\begin{equation}\label{liket}
\begin{gathered}
\frac{\partial^2 l_t}{\partial\theta_i \partial\theta_j} =  \frac{1}{2} tr\left[ \left[ F_t^{-1}\frac{\partial F_t}{\partial \theta_j} F_t^{-1} \frac{\partial F_t}{\partial \theta_i} - F_t^{-1}\frac{\partial^2 F_t}{\partial\theta_i \partial\theta_j} \right] \left[I - F_t^{-1}v_t v_t^\top\right] \right] - \\
\frac{1}{2}tr\left[ F_t^{-1}\frac{\partial F_t}{\partial \theta_i}F_t^{-1}\frac{\partial F_t}{\partial \theta_j}F_t^{-1}v_t v_t^\top\right] + \\
\frac{1}{2}tr\left[ F_t^{-1}\frac{\partial F_t}{\partial \theta_i}F_t^{-1}\left[ \frac{\partial v_t}{\partial \theta_j}v_t^\top + v_t\frac{\partial v_t^\top}{\partial \theta_j}\right]\right] - \\
\frac{\partial^2 v_t^\top}{\partial\theta_i \partial\theta_j}F_t^{-1}v_t + 
\frac{\partial v_t^\top}{\partial \theta_i} F_t^{-1}\frac{\partial F_t}{\partial \theta_j} F_t^{-1} v_t -
\frac{\partial v_t^\top}{\partial \theta_i} F_t^{-1} \frac{\partial v_t}{\partial \theta_j}
\end{gathered}
\end{equation}

The Fisher Information matrix is the negative of the expected value (over all possible data) of \ref{hessian}:
\begin{equation}\label{FisherInformation2}
 I(\theta) = -E\left[ \frac{\partial^2 \log L}{\partial\theta_i \partial\theta_j} \right]
\end{equation}
Thus for the Fisher Information matrix, we take the expectation (over all possible data) of the sum (over t) of Equation 3 (3.4.66 in Harvey 1989).  On pages 141-142, Harvey shows that the expected value of Equation 3 can be simplified and the i,j element of the Fisher Information matrix can be written as (Equation 3.4.69 in Harvey 1989):
\begin{equation}\label{Iij}
I_{ij}(\theta) = \frac{1}{2}\sum_t \left[ tr\left[ F_t^{-1}\frac{\partial F_t}{\partial \theta_i}F_t^{-1}\frac{\partial F_t}{\partial \theta_j}\right]\right] + E\left[\sum_t\left(\frac{\partial v_t}{\partial \theta_i}\right)^\top F_t^{-1}\frac{\partial v_t}{\partial \theta_j}\right]
\end{equation}

Equation \ref{Iij} (3.4.69 in Harvey 1989) is the Fisher Information and is evaluated at the true parameter values \( \theta \).  We do not know  \( \theta \) and instead we estimate the Fisher Information using our estimates of  \( \theta \).  The two estimates of \( I(\theta) \) that are used are called the expected and observed Fisher Information matrices.  The expected Fisher Information is
\begin{equation}\label{expectedFisherInformation2}
 I(\hat{\theta}) = -E\left[ \frac{\partial^2 \log L}{\partial\theta_i \partial\theta_j} \right] |_{\theta=\hat{\theta}} =
-E\left[ \sum{\frac{\partial^2 l_t}{\partial\theta_i \partial\theta_j}} \right] |_{\theta=\hat{\theta}}
\end{equation}
and the observed Fisher Information is
\begin{equation}\label{observedFisherInformation2}
\mathcal{I}(\hat{\theta},y) = - \frac{\partial^2 \log L}{\partial\theta_i \partial\theta_j} |_{\theta=\hat{\theta}} =
- \sum{\frac{\partial^2 l_t}{\partial\theta_i \partial\theta_j}} |_{\theta=\hat{\theta}}
\end{equation}
The \( |_{\theta=\hat{\theta}} \) means &#39;evaluated at&#39;.  \( l_t \) is a function of \( \theta \).  We take the derivative of that function and then evaluate that derivative at \( \theta = \hat{\theta} \).  The expectation (which is an integral) is over that possible values of the data \( y \) which are generated from the model with \( \theta \).
&lt;br /&gt;&lt;br /&gt;
The observed Fisher Information drops the expectation and the expected Fisher Information does not.  The expectation is taken over all possible data, and we have only one observed data set.  On first blush, it may seem that it is impossible to compute the expectation and that we must always use the observed Fisher Information.  However, for some models, one can write down the expectations analytically. One could simulate from the MLEs to get the expectations---this is the idea behind bootstrapping.  In a bootstrapping approach one uses the MLE to generate data. This is an approximation since what we would like is to simulate data from the true parameters. The mean and variance of data generated from the MLEs versus data generated the true parameters often have nice asymptotic properties.  
&lt;br /&gt;&lt;br /&gt;
However it is common to use the observed Fisher Information matrix.  This is what one is using when one uses the Hessian of the log-likelihood function evaluated at the MLEs.  To get an analytical equation for the observed Fisher Information matrix, we use Equation 3 for \( l_t \) and take the sum to get the Hessian of the log-likelihood function (\ref{hessian}).  This is the same Hessian that you can get numerically.  In R, you can use the fdHess function in the nmle package or the optim function.

&lt;h3&gt;Partially observed, partially expected Fisher Information matrix&lt;/h3&gt;

Equation \ref{Iij} (Equation 3.4.69 in Harvey) is a simplification the expected value of the sum of equation 3.  The simplification occurs because a number of terms in equation 3 drop out or cancel out when you take the expectation (see bottom of page 141 in Harvey 1989).  The only terms that remain are those shown in equation \ref{Iij}.  Harvey (1989) does not say how to compute the expectation in equation \ref{Iij} (which is his 3.4.69).  Cavanaugh and Shumway (1996) do not say how to compute it either and suggest that it is infeasible (page 1 in paragraph after their equation 1).  Instead they say that you can drop the expectation in equation \ref{Iij} and get the observed Fisher Information:
\begin{equation}\label{obsIij}
\mathcal{I}_{ij}(\theta) = \frac{1}{2}\sum_t \left[ tr\left[ F_t^{-1}\frac{\partial F_t}{\partial \theta_i}F_t^{-1}\frac{\partial F_t}{\partial \theta_j}\right]\right] + \sum_t\left(\frac{\partial v_t}{\partial \theta_i}\right)^\top F_t^{-1}\frac{\partial v_t}{\partial \theta_j}
\end{equation}
This however is halfway between the expected Fisher Information matrix and the observation Fisher Information matrix
because equation \ref{Iij} is what you get &lt;i&gt;after&lt;/i&gt; doing the expectation and dropping some of the terms in equation 3.  If you compare what you get from equation \ref{obsIij} and what you get from a numerical estimate of the Hessian of the log-likelihood function at the MLE, you will see that they are different.  The variance of the former is less than the variance of the latter.  This is what you expect since the former has had the expectation applied to some terms in equation 3 (Harvey&#39;s 3.4.66).
&lt;br /&gt;&lt;br /&gt;
This does not mean that equation \ref{obsIij} should not be used, but rather that if you compare it to the output from a numerically computed Hessian, they will not be the same.

In &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2017/05/notes-on-computing-fisher-information.html&quot;&gt;Part IV&lt;/a&gt;, I show Harvey&#39;s recursion for computing the first derivatives of \(v_t\) and \(F_t\) needed in equations 3 and \ref{Iij}.  I extend this recursion to get the second derivative also.  Once we have all these, we can use equation \ref{observedFisherInformation2} with equation 3 to compute the observed Fisher Information matrix and use equation \ref{Iij} to compute the &quot;observed/expected&quot; Fisher Information.

&lt;h3&gt;Writing Equation 3 in vec form&lt;/h3&gt;
We can compute the Hessian of the log-likelihood by using a for loop of i from 1 to p with an inner for loop for j from i to p.  The Hessian is symmetric so the inner loop only needs to go from i to p.  However, we can also write the Hessian for time step t in a single line without any for loops using the Jacobian matrices for our derivatives. With the t subscripts of F and v dropped:
\begin{equation}
\begin{gathered}
\frac{1}{2} J_F^\top ( F^{-1} \otimes F^{-1}) J_F 
- J_F^\top ( F^{-1}vv^\top F^{-1} \otimes F^{-1} ) J_F
-\frac{1}{2} ( I_p \otimes [ F^{-1} - F^{-1} v_t v_t^\top F^{-1} ] ) \mathcal{J}_F + \\
\frac{1}{2} J_F^\top [3 F^{-1}v \otimes F^{-1} + F^{-1} \otimes F^{-1}v] J_v
- \mathcal{J_v}^\top (I_p \otimes F^{-1} v)
- J_v^\top  F^{-1} J_v
\end{gathered}
\end{equation}
This may or may not be faster but it is more concise.  Go to &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2017/05/notes-on-computing-fisher-information.html&quot;&gt;Part IV&lt;/a&gt; to see how to compute these Jacobians using Harvey&#39;s recursion.

&lt;h3&gt;Derivation of the observed Fisher Information matrix (equation 9)&lt;/h3&gt;

Note, I am going to drop the t subscript on F and v because things are going to get cluttered; \( v_1 \) will refer to the 1st element of the \( n \times 1\) column vector v and \( F_{11} \) is the (1,1) element of the matrix F.  There has to be a loop to go through all the \( F_t \) and \( v_t \) for t=1 to T.

&lt;h4&gt;Terms 1 and 2 of equation 3&lt;/h4&gt;
The first term of equation 3 is
\begin{equation}
\begin{gathered}
\frac{1}{2} tr\left[ \left[ F^{-1}\frac{\partial F}{\partial \theta_j} F^{-1} \frac{\partial F}{\partial \theta_i} - \frac{1}{2} F^{-1}\frac{\partial^2 F}{\partial\theta_i \partial\theta_j} \right] \left[I - F^{-1}v v^\top\right] \right] = \\
\frac{1}{2} tr\left[ F^{-1}\frac{\partial F}{\partial \theta_j} F^{-1} \frac{\partial F}{\partial \theta_i}\left[I - F_t^{-1}v v^\top\right]\right] - 
\frac{1}{2} tr\left[ F^{-1}\frac{\partial^2 F}{\partial\theta_i \partial\theta_j} \left[ I - F^{-1}v v^\top \right]  \right] = \\
\frac{1}{2} tr\left[ F^{-1}\frac{\partial F}{\partial \theta_j} F^{-1} \frac{\partial F}{\partial \theta_i} \right] -
\frac{1}{2} tr\left[ F^{-1}\frac{\partial F}{\partial \theta_j} F^{-1} \frac{\partial F}{\partial \theta_i}F^{-1}v v^\top \right] -
\frac{1}{2} tr\left[ F^{-1}\frac{\partial^2 F}{\partial\theta_i \partial\theta_j} \left[I - F^{-1}v v^\top\right]\right] 
\end{gathered}
\end{equation}
The second term of equation 3 is
\begin{equation}
- \frac{1}{2} tr\left[ F_t^{-1}\frac{\partial F_t}{\partial \theta_i} F_t^{-1} \frac{\partial F_t}{\partial \theta_j}F_t^{-1}v_t v_t^\top \right]
\end{equation}
All the matrices within the traces above are symmetric. The trace of products of symmetric matrices is permutation invariant.  That means that if A, B, C, and D are symmetric matrices, \( tr(ABCD) = tr(ACBD) = tr(ACDB) \), etc.  Thus the second term can be rearranged to match the middle term in the first term.
Terms 1 + 2 of equation 3 can thus be written as
\begin{equation}\label{term12eqn3}
\frac{1}{2}tr\left[ F_t^{-1}\frac{\partial F_t}{\partial \theta_j} F_t^{-1} \frac{\partial F_t}{\partial \theta_i} \right] 
- tr\left[ F_t^{-1}\frac{\partial F_t}{\partial \theta_j} F_t^{-1} \frac{\partial F_t}{\partial \theta_i}F_t^{-1}v_t v_t^\top \right]
- \frac{1}{2} tr\left[ F_t^{-1}\frac{\partial^2 F_t}{\partial\theta_i \partial\theta_j} \left[I - F_t^{-1}v_t v_t^\top\right]\right]
\end{equation}

We can write the first trace of equation \ref{term12eqn3} as a vector product using the relation \( tr(A^\top B) = vec(A)^\top vec(B) \).  Note that the matrices in the traces in equation \ref{term12eqn3} are symmetric.  If A is symmetric, \( A^\top = A \) and \( tr(AB) = vec(A)^\top vec(B) \).  
\begin{equation}
\begin{gathered}
tr\left[  F^{-1}\frac{\partial F}{\partial \theta_j} F^{-1} \frac{\partial F}{\partial \theta_i} \right] = 
vec\left( F^{-1}\frac{\partial F}{\partial \theta_j} F^{-1}  \right)^\top vec\left(  \frac{\partial F}{\partial \theta_i} \right) = \\
\left( ( F^{-1} \otimes F^{-1} )  vec\left( \frac{\partial F}{\partial \theta_j} \right) \right)^\top vec\left(  \frac{\partial F}{\partial \theta_i} \right) = \\
vec\left( \frac{\partial F}{\partial \theta_j} \right)^\top ( F^{-1} \otimes F^{-1}) vec\left(  \frac{\partial F}{\partial \theta_i} \right)
\end{gathered}
\end{equation}
That is for the i,j element.  This matrix is symmetric so it is also the j,i element.  The derivative of \( vec(F) \) with respect to \( \theta \) (as opposed to the j-th element of \( \theta \)) is the Jacobian matrix of \( vec(F) \).
\begin{equation}\label{JF}
J_F = 
\begin{bmatrix}\frac{\partial vec(F)}{\theta_1} &amp; \frac{\partial vec(F)}{\theta_2} &amp; \dots &amp; \frac{\partial vec(F)}{\theta_p}\end{bmatrix} = 
\begin{bmatrix}
\frac{\partial F_{11}}{\theta_1} &amp; \frac{\partial F_{11}}{\theta_2} &amp; \dots &amp; \frac{\partial F_{11}}{\theta_p}\\
\frac{\partial F_{21}}{\theta_1} &amp; \frac{\partial F_{21}}{\theta_2} &amp; \dots &amp; \frac{\partial F_{21}}{\theta_p}\\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots \\
\frac{\partial F_{nn}}{\theta_1} &amp; \frac{\partial F_{nn}}{\theta_2} &amp; \dots &amp; \frac{\partial F_{nn}}{\theta_p}
\end{bmatrix}
\end{equation}
The full matrix for the first part of equation \ref{term12eqn3} is then
\begin{equation}
\frac{1}{2} J_F^\top ( F^{-1} \otimes F^{-1}) J_F
\end{equation}
&lt;br&gt;&lt;br&gt;
The middle trace of equation \ref{term12eqn3} is similar to the first and we end up with:
\begin{equation}
\begin{gathered}
vec\left( \frac{\partial F}{\partial \theta_j} \right)^\top ( F^{-1} \otimes F^{-1}) vec\left(  \frac{\partial F}{\partial \theta_i} F^{-1}vv^\top \right) = \\
vec\left( \frac{\partial F}{\partial \theta_j} \right)^\top ( F^{-1} \otimes F^{-1}) ( vv^\top F^{-1} \otimes I_n) vec\left(  \frac{\partial F}{\partial \theta_i}  \right) = \\
vec\left( \frac{\partial F}{\partial \theta_j} \right)^\top ( F^{-1}vv^\top F^{-1} \otimes F^{-1}) vec\left(  \frac{\partial F}{\partial \theta_i}  \right)
\end{gathered}
\end{equation}
We can write this in terms of the Jacobian of vec(F):
\begin{equation}
J_F^\top ( F^{-1}vv^\top F^{-1} \otimes F^{-1} ) J_F
\end{equation}
&lt;br&gt;&lt;br&gt;
The third part of equation \ref{term12eqn3} involves the second derivatives \( \partial^2 F/\partial\theta_i \partial\theta_j \). 
\begin{equation}
\begin{gathered}
tr\left[  F^{-1} \frac{\partial^2 F}{\partial\theta_i \partial\theta_j} [I - F^{-1}v v^\top ]  \right] = 
tr\left[  [I - F^{-1}v v^\top ] F^{-1} \frac{\partial^2 F}{\partial\theta_i \partial\theta_j}  \right] = \\
vec\left( F^{-1} - F^{-1}v v^\top F^{-1} \right)^\top vec\left(  \frac{\partial^2 F}{\partial\theta_i \partial\theta_j} \right) = \\
vec\left( F^{-1} - F^{-1}v v^\top F^{-1} \right)^\top \frac{\partial vec( \partial F/\partial\theta_i )}{\partial\theta_j}
\end{gathered}
\end{equation}
Again this is the i,j term.  The term on the bottom line on the right is the \( (\theta_i,\theta_j) \) term of the Jacobian of the vec of the Jacobian of F:
\begin{equation}
\mathcal{J}_F = 
\begin{bmatrix}\frac{\partial vec(J_F)}{\partial\theta_1} &amp; \frac{\partial vec(J_F)}{\partial\theta_2} &amp; \dots &amp; \frac{\partial vec(J_F)}{\partial\theta_p}\end{bmatrix} = 
\begin{bmatrix}
\frac{\partial F_{11}}{\theta_1\theta_1} &amp; \frac{\partial F_{11}}{\theta_1\theta_2} &amp; \dots &amp; \frac{\partial F_{11}}{\theta_1\theta_p}\\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots \\
\frac{\partial F_{nn}}{\theta_1\theta_1} &amp; \frac{\partial F_{nn}}{\theta_1\theta_2} &amp; \dots &amp; \frac{\partial F_{nn}}{\theta_1\theta_p}\\
\frac{\partial F_{11}}{\theta_2\theta_1} &amp; \frac{\partial F_{11}}{\theta_2\theta_2} &amp; \dots &amp; \frac{\partial F_{11}}{\theta_2\theta_p}\\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots \\
\frac{\partial F_{nn}}{\theta_2\theta_1} &amp; \frac{\partial F_{nn}}{\theta_2\theta_2} &amp; \dots &amp; \frac{\partial F_{nn}}{\theta_2\theta_p}\\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots \\
\frac{\partial F_{11}}{\theta_p\theta_1} &amp; \frac{\partial F_{11}}{\theta_p\theta_2} &amp; \dots &amp; \frac{\partial F_{11}}{\theta_p\theta_p}\\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots \\
\frac{\partial F_{nn}}{\theta_p\theta_1} &amp; \frac{\partial F_{nn}}{\theta_p\theta_2} &amp; \dots &amp; \frac{\partial F_{nn}}{\theta_p\theta_p}\\
\end{bmatrix}
\end{equation}
&lt;br&gt;&lt;br&gt;
The full matrix for the second part of term 1 + 2 in Equation 3 is then
\begin{equation}
 ( I_p \otimes [ F^{-1} - F^{-1} v v^\top F^{-1} ] ) \mathcal{J}_F
\end{equation}
The subscript on the \( I \) indicates the size of the identity matrix.  In this case, it is a \( p \times p \) matrix.

&lt;h4&gt;Term 3 of equation 3&lt;/h4&gt;
With the t subscripts dropped, the 3rd term of equation 3 is                                         
\begin{equation}\label{term3eqn3}
\frac{1}{2} tr\left[ F^{-1}\frac{\partial F}{\partial \theta_i}F^{-1} \left( \frac{\partial v}{\partial \theta_j}v^\top + v\frac{\partial v^\top}{\partial \theta_j}\right) \right]
\end{equation}
Using the same procedure as for the above terms, we can write this in terms of vecs. If \(b\) and \(a\) are \(1 \times n\) column vectors,
\begin{equation}
vec(ab^\top) = (b \otimes I_n)vec(a) = (b \otimes I_n)a = (I_n \otimes a)vec(b) = (I_n \otimes a)b
\end{equation}
Thus,
\begin{equation}
\begin{gathered}
vec\left( \frac{\partial v}{\partial \theta_j}v^\top\right) = (v \otimes I_n)\frac{\partial v}{\partial \theta_j} \\
vec\left( v (\partial v/\partial \theta_j)^\top \right) = (I_n \otimes v)\frac{\partial v}{\partial \theta_j}
\end{gathered}
\end{equation}
and
\begin{equation}
vec\left( \frac{\partial v}{\partial \theta_j}v^\top + v(\partial v/\partial \theta_j)^\top \right)  = (v \otimes I_n + I_n \otimes v)\frac{\partial v}{\partial \theta_j} 
\end{equation}
When A is symmetric, \( tr(AB) = vec(A)^\top vec(B) \).  Thus term 3 of equation 3 can be written as
\begin{equation}
\begin{gathered}
\frac{1}{2} tr\left[ F^{-1}\frac{\partial F}{\partial \theta_i}F^{-1} \left( \frac{\partial v}{\partial \theta_j}v^\top + v\frac{\partial v^\top}{\partial \theta_j}\right) \right] 
= vec\left( \frac{\partial F}{\partial \theta_i} \right)^\top (F^{-1} \otimes F^{-1}) (v \otimes I_n + I_n \otimes v)\frac{\partial v}{\partial \theta_j} \\
vec\left( \frac{\partial F}{\partial \theta_i} \right)^\top (F^{-1}v \otimes F^{-1} + F^{-1} \otimes F^{-1}v) \frac{\partial v}{\partial \theta_j}
\end{gathered}
\end{equation}
This is the i,j term of the Fisher Information matrix from term 3 in equation 3.  To get all terms, we use the Jacobian of vec(F) as above and the Jacobian of v:
\begin{equation}
\frac{1}{2} J_F^\top (F^{-1} \otimes F^{-1}) (v \otimes I_n + I_n \otimes v) J_v =
\frac{1}{2} J_F^\top [F^{-1} v \otimes F^{-1} + F^{-1} \otimes F^{-1}v] J_v
\end{equation}
where \( J_F \) is defined in equation \ref{JF} and \( J_v \) is
\begin{equation}\label{Jv}
J_v = 
\begin{bmatrix}
\frac{\partial v_{1}}{\theta_1} &amp; \frac{\partial v_{1}}{\theta_2} &amp; \dots &amp; \frac{\partial v_{1}}{\theta_p}\\
\frac{\partial v_{2}}{\theta_1} &amp; \frac{\partial v_{2}}{\theta_2} &amp; \dots &amp; \frac{\partial v_{2}}{\theta_p}\\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots \\
\frac{\partial v_{n}}{\theta_1} &amp; \frac{\partial v_{n}}{\theta_2} &amp; \dots &amp; \frac{\partial v_{n}}{\theta_p}
\end{bmatrix}
\end{equation}

&lt;h4&gt;Term 4 of equation 3&lt;/h4&gt;
The 4th term of equation 3 is
\begin{equation}\label{term4eqn3}
- \frac{\partial^2 v^\top}{\partial\theta_i \partial\theta_j}F^{-1}v
\end{equation}
This is for the i,j term of the Fisher Information matrix.  An equation for all terms can be written as a junction of the 
the Jacobian of \( vec(J_v) \):
\begin{equation}
\mathcal{J}_v = 
\begin{bmatrix}\frac{\partial vec(J_v)}{\partial\theta_1} &amp; \frac{\partial vec(J_v)}{\partial\theta_2} &amp; \dots &amp; \frac{\partial vec(J_v)}{\partial\theta_p}\end{bmatrix} = 
\begin{bmatrix}
\frac{\partial v_{1}}{\theta_1\theta_1} &amp; \frac{\partial v_{1}}{\theta_1\theta_2} &amp; \dots &amp; \frac{\partial v_{1}}{\theta_1\theta_p}\\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots \\
\frac{\partial v_{n}}{\theta_1\theta_1} &amp; \frac{\partial v_{n}}{\theta_1\theta_2} &amp; \dots &amp; \frac{\partial v_{n}}{\theta_1\theta_p}\\
\frac{\partial v_{1}}{\theta_2\theta_1} &amp; \frac{\partial v_{1}}{\theta_2\theta_2} &amp; \dots &amp; \frac{\partial v_{1}}{\theta_2\theta_p}\\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots \\
\frac{\partial v_{n}}{\theta_2\theta_1} &amp; \frac{\partial v_{n}}{\theta_2\theta_2} &amp; \dots &amp; \frac{\partial v_{n}}{\theta_2\theta_p}\\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots \\
\frac{\partial v_{1}}{\theta_p\theta_1} &amp; \frac{\partial v_{1}}{\theta_p\theta_2} &amp; \dots &amp; \frac{\partial v_{1}}{\theta_p\theta_p}\\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots \\
\frac{\partial v_{n}}{\theta_p\theta_1} &amp; \frac{\partial v_{n}}{\theta_p\theta_2} &amp; \dots &amp; \frac{\partial v_{n}}{\theta_p\theta_p}\\
\end{bmatrix}
\end{equation}
The right of equation \ref{term4eqn3}, \( F^{-1}v \)  is a \(n \times 1\) matrix.  We need to write this as the \(np \times p\) matrix:
\begin{equation}
\begin{bmatrix}
F^{-1}v &amp; 0_{n \times 1} &amp; \dots &amp; 0_{n \times 1}\\
0_{n \times 1} &amp; F^{-1}v &amp; \dots &amp; 0_{n \times 1}\\
\vdots &amp; \vdots &amp; \vdots &amp; \vdots\\
0_{n \times 1} &amp; 0_{n \times 1} &amp; \dots &amp; F^{-1}v
\end{bmatrix} = I_p \otimes F^{-1}v
\end{equation}
Thus the full matrix for the i,j terms in the Fisher Information matrix from term 4 of equation 3 is
\begin{equation}
- \mathcal{J_v}^\top (I_p \otimes F^{-1}v)
\end{equation}

&lt;h4&gt;Term 5 of equation 3&lt;/h4&gt;
Term 5 is 
\begin{equation}\label{term5eqn3}
\frac{\partial v^\top}{\partial \theta_i} F^{-1}\frac{\partial F}{\partial \theta_j} F^{-1} v
\end{equation}
This is a scalar and thus its vec is equal to itself.  We can rewrite equation \ref{term5eqn3} using the following relation:
\begin{equation}
vec(a^\top ABC c ) = (c^\top \otimes a^\top) vec (ABC) = a^\top (c^\top \otimes I_n) vec(ABC) = c^\top (a^\top \otimes I_n) (C^\top \otimes A) vec(B) =
c^\top (a^\top C^\top \otimes A) vec(B)
\end{equation}
Thus equation \ref{term5eqn3} is
\begin{equation}
\frac{\partial v^\top}{\partial \theta_i} F^{-1}\frac{\partial F}{\partial \theta_j} F^{-1} v =
\frac{\partial v^\top}{\partial \theta_i}  (v^\top \otimes I_n) (F^{-1} \otimes F^{-1}) vec\left( \frac{\partial F}{\partial \theta_j} \right)
\end{equation}
This is for the i,j term of the Fisher Information matrix.  For the full matrix, we use the Jacobian of v (equation \ref{Jv}) and the Jacobian of vec(F) (equation \ref{JF}):
J_v^\top  (v^\top \otimes I_n) (F^{-1} \otimes F^{-1}) J_F = J_v^\top (v^\top F^{-1} \otimes F^{-1}) J_F
\end{equation}

&lt;h4&gt;Term 6 of equation 3&lt;/h4&gt;
Term 6 is 
\begin{equation}\label{term6eqn3}
- \frac{\partial v^\top}{\partial \theta_i} F^{-1} \frac{\partial v}{\partial \theta_j}
\end{equation}
This is for the i,j term of the Fisher Information matrix and we can write it immediately as the full matrix in terms of the Jacobian of v:
\begin{equation}
\frac{\partial v^\top}{\partial \theta_i} F^{-1}\frac{\partial F}{\partial \theta_j} F^{-1} v =
J_v^\top  F^{-1} J_v
\end{equation}

&lt;h4&gt;Putting all the terms together&lt;/h4&gt;
Putting all the terms together, we have the full observed Fisher Information matrix:
\begin{equation}
\begin{gathered}
\frac{1}{2} J_F^\top ( F^{-1} \otimes F^{-1}) J_F 
- J_F^\top ( F^{-1}vv^\top F^{-1} \otimes F^{-1} ) J_F
-\frac{1}{2} ( I_p \otimes [ F^{-1} - F^{-1} v_t v_t^\top F^{-1} ] ) \mathcal{J}_F + \\
\frac{1}{2} J_F^\top [F^{-1}v \otimes F^{-1} + F^{-1} \otimes F^{-1}v] J_v
- \mathcal{J_v}^\top (I_p \otimes F^{-1}v)
+ J_v^\top (v^\top F^{-1} \otimes F^{-1}) J_F
- J_v^\top  F^{-1} J_v
\end{gathered}
\end{equation}
We can simplify this a little by noting that all terms are symmetric matrices and the transpose or a symmetric matrix is equal to itself.
\begin{equation}
J_v^\top (v^\top F^{-1} \otimes F^{-1}) J_F = J_F^\top (F^{-1} v \otimes F^{-1}) J_v
\end{equation}
Thus the full observed Fisher Information matrix is
\begin{equation}
\begin{gathered}
\frac{1}{2} J_F^\top ( F^{-1} \otimes F^{-1}) J_F 
- J_F^\top ( F^{-1}vv^\top F^{-1} \otimes F^{-1} ) J_F
-\frac{1}{2} ( I_p \otimes [ F^{-1} - F^{-1} v_t v_t^\top F^{-1} ] ) \mathcal{J}_F + \\
\frac{1}{2} J_F^\top [3 F^{-1}v \otimes F^{-1} + F^{-1} \otimes F^{-1}v] J_v
- \mathcal{J_v}^\top (I_p \otimes F^{-1} v)
- J_v^\top  F^{-1} J_v
\end{gathered}
\end{equation}


&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/4568668766381382037/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/4568668766381382037' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/4568668766381382037'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/4568668766381382037'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2016/06/notes-on-computing-fisher-information.html' title='Notes on computing the Fisher Information matrix for MARSS models. Part III Overview of Harvey 1989'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-7006244654917436404</id><published>2016-05-19T20:48:00.000-07:00</published><updated>2017-05-31T11:09:56.893-07:00</updated><title type='text'>Notes on computing the Fisher Information matrix for MARSS models. Part II Louis 1982</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;script type=&quot;text/x-mathjax-config&quot;&gt;
  MathJax.Hub.Config({ TeX: { equationNumbers: {autoNumber: &quot;AMS&quot;} } });
&lt;/script&gt;
&lt;script src=&#39;https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&#39; type=&#39;text/javascript&#39;&gt;
&lt;/script&gt;
&lt;i&gt;MathJax and blogger can be iffy.  Try reloading if the equations don&#39;t show up.&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;

Part II.  Background on Fisher Information is in &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2016/05/notes-on-computing-fisher-information.html&quot;&gt;Part I&lt;/a&gt;. &lt;br /&gt;&lt;br /&gt;

So how do we compute \( I(\hat{\theta}) \) or \( \mathcal{I}(\hat{\theta},y) \) (in Part I)?  In particular, can we use the analytical derivatives of the full log-likelihood that are part of the EM algorithm?  Many researchers have worked on this idea. My notes here were influenced by this blog post &lt;a href=&quot;http://statisticalrecipes.blogspot.com/2012/03/em-algorithm-and-confidence-intervals.html&quot;&gt;EM Algorithm: Confidence Intervals &lt;/a&gt;on the same topic, which got me started.  
This blog post is mainly a discussion of the result by Louis (1982) on calculation of the Fisher Information matrix from the &#39;score&#39; function that one takes the derivative of in the M-step of the EM algorithm.
&lt;/br&gt;&lt;/br&gt;
The &#39;score&#39; function used in the EM algorithm for a MARSS model is
\begin{equation} 
Q(\theta | \theta_j) = E_{X|y,\theta_j } [\log f_{XY}(X,y|\theta) ]
\end{equation} 
It is the expected value taken over the hidden random variable \( X \) of the full data log-likelihood at \( Y=y \) [3]; full means it is a function of all the random variables in the model,  which includes the hidden or latent variables.
\( x, y \) is the full &#39;data&#39;, the left side of the \( x \) state equation and the \( y \) observation equation.  We take the expectation of this full data likelihood conditioned on the observed data \( y \) and \( \theta_j \) which is the value of \( \theta \) at the j-th iteration of the EM algorithm. Although \( Q(\theta | \theta_j) \) looks a bit hairy, actually the full-data likelihood may be very easy to write down and considerably easier than the data likelihood \( f(y|\theta) \).  The hard part is often the expectation step, however for MARSS models the Kalman filter-smoother algorithm computes the expectations involving \( X \) and Holmes (2010) shows how to compute the expectations involving \( Y \), which comes up when there are missing values in the dataset (missing time steps, say).  
&lt;/br&gt;&lt;/br&gt;
In the M-step of the EM algorithm, we take the derivative of \( Q(\theta | \theta_j) \) with respect to \( \theta \) and solve for the \( \theta \) where
\[ \frac{\partial Q(\theta | \theta_j ) }{\partial \theta} = 0. \]
It would be nice if one could use the following to compute the observed Fisher Information 
\[  - \frac{\partial^2 Q(\theta | \hat{\theta}) }{\partial \theta^2 } \right|_{\theta = \hat{\theta} } \]
\( Q(\theta | \hat{\theta}) \) is our score function at the end of the EM algorithm, when \( \theta = \hat{\theta} \).  \( Q \) is a function of \( \theta \), the model parameters, and will have terms like \( E(X|Y=y, \hat{\theta}) \), the expected value of \( X \) conditioned on \( Y=y \) and the MLE.  Those are the expectations coming out of the Kalman filter-smoother.  We take the second derivative of \( Q \) with respect to \( \theta \).  That is straight-forward for the MARSS equations.  You take the first derivative of \( Q \) with respect to \( \theta \), which you already have from the update or M-step equations, and take the derivative of that with respect to \( \theta \).
&lt;br /&gt;&lt;br /&gt;
Conceptually, this
\[  - \left.\frac{\partial^2 Q(\theta | \hat{\theta}) }{\partial \theta^2 } \right|_{\theta = \hat{\theta} } = \left.\frac{\partial^2 E_{X|y,\hat{\theta} } [\log f(X,y|\theta) ] }{\partial \theta^2 } \right|_{\theta = \hat{\theta} } \]
looks a bit like the observed Fisher Information:
\begin{equation}\label{obsFI}
\mathcal{I}(\hat{\theta},y) = - \left.\frac{\partial^2\log f(y|\theta)}{\partial \theta^2} \right|_{\theta=\hat{\theta}}
\end{equation}
except that instead of the data likelihood \( f(y|\theta) \), we use the expected likelihood \( E_{X|y,\hat{\theta} } [\log f_{XY}(X,y|\theta) ] \).  The expected likelihood is the full likelihood with the \( X \) and \( XX^\top \) random variables replaced by their expected values assuming \( \theta = \hat{\theta} \) and \( Y=y \). The problem is that \( E_{X|y,\theta } [\log f(X,y|\theta) ] \) is a function of \( \theta \) and by fixing it at \( \hat{\theta}\) we are not accounting for the uncertainty in that expectation.  What we need is something like
&lt;br \&gt;&lt;br \&gt;
Information with X fixed at expected value - Information on expected value of X
&lt;br \&gt;&lt;br \&gt;
so we account for the fact that we have over-estimated the information from the data by treating the hidden random variable as fixed. The same issue arises when we compute confidence intervals using the estimate of the variance without accounting for the fact that this is an estimate and thus has uncertainty.
Louis (1982) and Oakes (1999) are concerned with how to do this correction or adjustment. 
&lt;br /&gt;
&lt;h2&gt;Louis 1982 approach&lt;/h2&gt;
The following is equations 3.1, 3.2 and 3.3 in Louis (1982) translated to the MARSS case.  In the MARSS model, we have two random variables, \( X(t) \) and \( Y(t) \). The joint distribution of \( \{X(t), Y(t) \} \)  conditioned on \( X(t-1) \) is multivariate normal.  Our full data set includes all time steps, \( \{X, Y \} \).
&lt;br /&gt;&lt;br /&gt;
Let&#39;s call the full state at time t \( \{x ,y\} \), the value of the \( X \) and \( Y \) at all times t. The full state can be an unconditional random variable, \( \{X,Y\} \) or a conditional random variable \( \{X,y\} \) (conditioned on \(Y=y\).
Page 227 near top of Louis 1982 becomes
\begin{equation} 
\lambda(x,y,\theta) = \log\{ f_{XY}(x,y|\theta) \} \label{lambdaz}
\end{equation}
\begin{equation}  
\lambda^*(y,\theta) = \log\{ f_Y(y|\theta) \} = \log \int_X f_{XY}(x,y|\theta)dx \label{lambday}
\end{equation}
\( f(.|\theta) \) is the probability distribution of the random variable conditioned on \(\theta\). \( \lambda \) is the full likelihood; &#39;full&#39; means is includes both \( x \) and \( y \).  \( \lambda^* \) is the likelihood of \( y \) alone.  It is defined by the marginal distribution of \( y \) [1]; the integral over \( X \) on the right side of \ref{lambday}.  For a MARSS model, the data likelihood can be written easily as a function of the Kalman filter recursions (which is why you can write a recursion for the information matrix based on derivatives of \( \lambda^* \); see Part III).
&lt;br /&gt;&lt;br /&gt;
Next equation down.  Louis doesn&#39;t say this and his notation is not totally clear, but the expectation right above section 3 (and in his eqn 3.1) is a conditional expectation. This is critical to know to follow his derivation of equation 3.1 in the appendix. \( \theta_j \) is his \( \theta(0) \); it is the value of \( \theta \) at the last EM iteration.

\begin{equation}\label{expLL}
E_{X|y,\theta_j}[ \lambda( X, y, \theta)] = \int_X \lambda( X, y, \theta) f_{X|Y}(x|Y=y, \theta_j) dx 
\end{equation}
My &#39;expectation&#39; notation is a little different than Louis&#39;.  The subscript on the E shows what is being integrated *(\(X\) ) and what are the conditionals.  

The term \( f_{X|Y}(x|Y=y, \theta_j) \) is the probability of \( x \) conditioned on \( Y=y \) and \( \theta=\theta_j \).  The subscript on \(f\) indicates that we are using the probability distribution of \(x\) conditioned on \(Y=y\).
For the EM algorithm, we need to distinguish between \( \theta \) and \( \theta_j \) because we maximize with respect to \( \theta \) not \( \theta_j \).  If we just need the expectation at \( \theta \), no maximization step, then we just use \( \theta \) in \( f(.|\theta) \) and the subscript on E.
&lt;br /&gt;&lt;br /&gt;
Before moving on with the derivation, notice that in \ref{expLL}, we fix \( y \), the data.  We are not treating that as a random variable.  We could certainly treat \( E_{\theta_j}[ \lambda( \{X, y\}, \theta)] \) as some function \(g(y) \) and consider the random variable \( g(Y) \).  But Louis (1982) will not go that route.  \( y \) is fixed.  Thus we are talking about the &lt;em&gt;observed&lt;/em&gt; Fisher Information rather than the &lt;em&gt;expected&lt;/em&gt; Fisher Information.  The latter would take an expectation over the possible \( y \) generated by our model with parameters at the MLE.
&lt;br /&gt;

&lt;h3&gt;Derivation of equation 3.1 in Louis 1982&lt;/h3&gt;

Now we can derive equation 3.1 in Louis (1982).  I am going to combine the info in Louis&#39; section 3.1 and the appendix on the derivation of 3.1.  Before proceeding, Louis is using &#39;denominator&#39; format for his matrix derivations; I normally use denominator format but I will follow his convention here.  \( \theta \) is a column vector of parameters and the likelihood \( f(.|\theta)\) is scalar.  Under &#39;denominator format&#39;, \( f^\prime(.|\theta) = df(.|\theta)/d\theta) \) will be a column vector. \( f^{\prime\prime}(.|\theta) = d^2f(.|\theta)/d\theta d\theta^\top)\) will be a matrix in Hessian format (the first \(d\theta\) goes 1 to \(n\) down columns and the second \(d\theta\) does 1 to \(n\) across rows). 
&lt;br/&gt;&lt;br/&gt;
Take the derivative of \ref{lambdaz} with respect to \( \theta \) to define \( S(z,\theta) \).
\begin{equation}
S(x,y,\theta)=\lambda^\prime(x,y,\theta)=\frac{d \log\{f_{XY}(x,y|\theta)\} }{d \theta}= 
\frac{df(x,y|\theta)/d\theta}{f(x,y|\theta)} =
\frac{f^\prime(x,y|\theta)}{f(x,y|\theta)}\label{Sz}
\end{equation}
Take the derivative of the far right side of \ref{lambday} with respect to \( \theta \) to define \( S^*(y,\theta) \).  For the last step (far right), I used \( f_Y(y|\theta) = \int_X f_{XY}(x,y|\theta)dx \), the definition of the marginal distribution [1], to change the denominator.

\begin{equation}\label{Sy}
S^*(y,\theta)=\lambda^{*\prime}(y,\theta)=\frac{ d \log \int_X f_{XY}(x,y|\theta)dx  }{d \theta} = 
\frac{ \int_X f_{XY}^\prime(x,y|\theta) dx }{ \int_X f_{XY}(x,y|\theta)dx } =
\frac{ \int_X f_{XY}^\prime(x,y|\theta) dx }{ f_Y(y|\theta) } 
\end{equation}
Now multiply the integrand in the numerator by \( f_{XY}(x,y|\theta)/f_{XY}(x,y|\theta) \).  The last step (far right) uses \ref{Sz}.
\begin{equation}\label{intfprime}
\int_X f_{XY}^\prime(x,y|\theta) dx   =
\int_X \frac{f_{XY}^\prime(x,y|\theta)f_{XY}(x,y|\theta)}{f_{XY}(x,y|\theta)} dx =
\int_X \frac{f_{XY}^\prime(x,y|\theta)}{f_{XY}(x,y|\theta)}f_{XY}(x,y|\theta) dx =
\int_X S(x,y,\theta) f_{XY}(x,y|\theta) dx 
\end{equation}
We  combine \ref{Sy} and \ref{intfprime}:
\begin{equation}\label{Sstar}
S^*(y,\theta)=
\frac{ \int_X f_{XY}^\prime(x,y|\theta) dx }{ f_Y(y|\theta) } =
\int_X S(x,y,\theta)  \frac{ f_{XY}(x,y|\theta) }{ f_Y(y|\theta) } dx =
\int_X S(x,y,\theta) f_{X|Y}(x|Y=y,\theta) dx
\end{equation}
The second to last step used the fact that \( f_Y(y|\theta) \) does not involve \( x \) thus we can bring it into the integral.  This gives us \( f_{XY}(x,y|\theta)/f_Y(y|\theta)\). This is the  probability of \( x \) conditioned on \( Y=y \) [2].
&lt;br \&gt;&lt;br \&gt;
The last step in the derivation of equation 3.1 is to recognize that the far right side of \ref{Sstar} is the conditional expectation in 3.1.  Louis does not actually write out the expectation in 3.1 and the notation is rather vague. But the expectation in equation 3.1 is the conditional expectation on the far right side of \ref{Sstar}.
\begin{equation}\label{Louise3p1}
S^*(y,\theta)=\int_X S(x,y,\theta) f_{X|Y}(x|Y=y,\theta) dx=E_{X|y,\theta} [ S(X,y,\theta) ]
\end{equation}
using my notation for a conditional expectation which slightly different than Louis&#39;.
At the MLE, \( S^*(y,\hat{\theta})=0\) since that is how the MLE is defined (it&#39;s where the derivative of the data likelihood is zero).

&lt;h3&gt;Derivation of equation 3.2 in Louis 1982&lt;/h3&gt;

The meat of Louis 1982 is equation 3.2.  The observed Fisher Information matrix \ref{obsFI} is 
\begin{equation}\label{obsFI32}
 \mathcal{I}(\theta,y) = B^*(y,\theta) = -S^\prime(x,y,\theta) = - \lambda^{*\prime\prime}(y,\theta) = 
- \frac{\partial^2\log f_Y(y|\theta)}{\partial \theta \partial \theta^\top} 
\end{equation}
The first 3 terms on the left are just show that all are notation that refers to the observed Fisher Information.  The 4th term is one of the ways we can compute the observed Fisher Information at \(  \theta \) and the far right term shows that derivative explicitly.  
&lt;br /&gt;&lt;br /&gt;

We start by taking the second derivative of \ref{lambdaz} with respect to \( \theta \) to define \( B(x,y,\theta) \). We use \( S^\prime(z,\theta) \) as written in \ref{Sz}.
\begin{equation}\label{B1}
\mathcal{I}(\theta,x,y) = B(x,y,\theta)=-\lambda^{\prime\prime}(x,y,\theta) = -S^\prime(x,y,\theta) = 
-\frac{d[f_{XY}^\prime(x,y|\theta)/f_{XY}(x,y|\theta)]}{d \theta^\top}
\end{equation}
The transpose of \(d\theta \) is because we are taking the second derivative \( d^2 l/d\theta d\theta^\top \) (the Hessian of the log-likelihood); \( d\theta d\theta \) wouldn&#39;t make sense as that that would be a column vector times a column vector.
&lt;br /&gt;&lt;br /&gt;
To do the derivative on the far right side of \ref{B1}, we first need to recognize the form of the equation.  \( f_{XY}^\prime(x,y|\theta) \) is a column vector and \( f(x,y|\theta) \) is a scalar, thus the thing we are taking the derivative of has the form \( \overrightarrow{h}(\theta)/g(\theta) \); the arrow over \(h\) is indicating that it is a (column) vector while \(g()\) is a scalar.  Using the chain rule for vector derivatives, we have
\[ \frac{ d (\overrightarrow{h}(\theta)/g(\theta))}{d \theta^\top} = \frac{d\overrightarrow{h}(\theta)}{d \theta^\top}\frac{1}{g(\theta)} - \frac{\overrightarrow{h}(\theta)}{ g(\theta)^2 }\frac{ g(\theta) }{ d \theta^\top } \]
Thus (notice I&#39;m writing the equation for the negative of \( B(x,y,\theta) \),

\begin{equation}\label{B2}
-B(x,y,\theta) = 
\frac{d(f_{XY}^\prime(x,y|\theta)/f_{XY}(x,y|\theta))}{d \theta^\top} =
\frac{f_{XY}^{\prime\prime}(x,y|\theta)}{f_{XY}(x,y|\theta)} 
- \frac{f_{XY}^\prime(x,y|\theta)f^\prime(z|\theta)^\top}{ f_{XY}(x,y|\theta)^2 }=
\frac{f_{XY}^{\prime\prime}(x,y|\theta)}{f_{XY}(x,y|\theta)} - S(x,y|\theta)S(x,y|\theta)^\top
\end{equation}

&lt;br /&gt;&lt;br /&gt;
Let&#39;s return to \ref{obsFI32} and take the derivative of \( \lambda^{*\prime}(y,\theta)\) with respect to \( \theta \) using the form shown in equation \ref{Sy}.  I have replaced the integral in the denominator by \( f_Y(y|\theta) \) and used the same chain rule used for \ref{B2}.

\begin{align}
\begin{split}
\lambda^{*\prime\prime}(y,\theta)=
d\left( \int_X f_{XY}^\prime(x,y|\theta) dx \middle/ f_Y(y|\theta) \right)/d\theta^\top = \\
\frac{\int_X f_{XY}^{\prime\prime}(x,y|\theta) dx }{f_Y(y|\theta)}-
\frac{\int_X f_{XY}^\prime(x,y|\theta)dx }{f_Y(y|\theta)} \left(\frac{\int_X f_{XY}^\prime(x,y|\theta)dx}{f_Y(y|\theta)}\right) =
\frac{\int_X f_{XY}^{\prime\prime}(x,y|\theta) dx }{f_Y(y|\theta)}-
S^*(y|\theta)S^*(y|\theta)^\top
\end{split}
\end{align}

The last substitution uses \ref{Sy}.  Thus,
\begin{equation}\label{B4}
\lambda^{*\prime\prime}(y,\theta)=
\frac{\int_X f_{XY}^{\prime\prime}(x,y|\theta) dx }{f_Y(y|\theta)}-
S^*(y|\theta)S^*(y|\theta)^\top
\end{equation}


&lt;br\&gt;
Let&#39;s look at the integral of the second derivative of \(f_{XY}(x,y|\theta)\) in \ref{B4}:

\begin{equation}\label{B5}
\left( \int_X f_{XY}^{\prime\prime}(x,y|\theta) dx \middle/ f_Y(y|\theta) \right) =
 \int_X \frac{f_{XY}^{\prime\prime}(x,y|\theta) dx}{ f_{XY}(x,y|\theta) }\frac{f_{XY}(x,y|\theta)}{ f_Y(y|\theta)} dx=
 \int_X \frac{f_{XY}^{\prime\prime}(x,y|\theta) dx}{ f_{XY}(x,y|\theta) }f_{X|Y}(x|Y=y,\theta) dx
\end{equation}

This is the conditional expectation \( E_{X|y,\theta} [ f_{XY}^{\prime\prime}(x,y|\theta) dx/f_{XY}(x,y|\theta) ] \) that we see 5 lines above the references in Louis (1982).  Using \ref{B2} we can write this in terms of \( B(x,y|\theta) \):
\begin{equation}\label{B6}
 \int_X \frac{f_{XY}^{\prime\prime}(z|\theta) dx}{ f_{XY}(x,y|\theta) } = -B(x,y|\theta)+S(x,y|\theta)S(x,y|\theta)^\top
\end{equation}

Combining \ref{B4}, \ref{B5}, and \ref{B6}, we can write the equation above the references in Louis:
\begin{equation}\label{B7}
\lambda^{*\prime\prime}(y,\theta)= E_{X|y,\theta} [ - B(X,y|\theta)+S(X,y|\theta)S(X,y|\theta)^\top]-S^*(y|\theta)S^*(y|\theta)^\top
\end{equation}
The negative of this is the observed Fisher Information (\ref{obsFI32}) which gives us equation 3.2 in Louis (1982):
\begin{equation}\label{Louismain}
\mathcal{I}(\theta,y) = E_{X|y,\theta} [ B(X,y|\theta)] - E_{X|y,\theta} [ S(X,y|\theta)S(X,y|\theta)^\top]+S^*(y|\theta)S^*(y|\theta)^\top
\end{equation}

&lt;h3&gt;Derivation of equation 3.3 in Louis 1982&lt;/h3&gt;

Louis states that  &quot;The first term in (3.2) is the conditional expected full data observed information matrix, while the last two produce the expected information for the conditional distribution of X given \(X \in R\).&quot;  His X is my  \( \{X,Y\}\) and \( X \in R \) means \( Y=y \) in my context.  He writes this in simplified form with \(X\) replaced by \(XY\): 
\[ I_Y = I_{XY} - I_{X|Y} \]
\[ \mathcal{I}(\theta,y) = E_{X|y,\theta} [\mathcal{I}(\theta,X,y)] - I_{X|Y} \]
Let&#39;s see how this is the case.
&lt;br \&gt;&lt;br \&gt;
The full data observed information matrix is 
\[ \mathcal{I}(\theta,x,y) = -\lambda^{\prime\prime}(x,y|\theta) = B(x,y,\theta)\]
This is simply the definition that Louis gives to \( B(x,y,\theta) \). We do not know \(x\) so we do not know the full data observed Information matrix.  But we have the distribution of \( x \) conditioned on our data \( y \).
\[ E_{X|y,\theta} [ B(X,y|\theta)] \]
is thus the expected full data observed information matrix conditioned on our observed data \( y \).
So this is the first part of his statement.&lt;br\&gt;&lt;br\&gt;
The second part of his statement takes a bit more effort to work out.  First we substitute \( S^*(y|\theta) \) with 
\( E_{X|y,\theta} [ S(X,y|\theta) ] \) from \ref{Louise3p1}. This gives us this:
\begin{equation}\label{ES1}
 E_{X|y,\theta} [ S(X,y|\theta)S(X,y|\theta)^\top ]-S^*(y|\theta)S^*(y|\theta)^\top =
E_{X|y,\theta} [ S(X,y|\theta)S(X,y|\theta)^\top ]-E_{X|y,\theta} [ S(X,y|\theta) ]E_{X|y,\theta} [ S(X,y|\theta)^\top ]
\end{equation}
Using the computational form of the variance, \( var(X)=E(XX)-E(X)E(X) \), we can see that \ref{ES1} is the conditional variance of \( S(X,y|\theta) \).
\[ var_{X|y,\theta}( S(X,y|\theta) ) \]
But the variance of the first derivative of \( f^\prime(X|\theta) \) is the &lt;em&gt;expected&lt;/em&gt; Fisher Information of \( X \) [4].  In this case, it is the expected Fisher Information of the hidden state \( X \), where we specify that \( X \) has the conditional distribution \( f_{X|Y} (X | Y=y,\theta) \).  Thus we have the second part of Louis&#39; statement.
&lt;br/&gt;&lt;br/&gt;

&lt;h3&gt;Relating Louis 1982 to the update equations in the MARSS EM algorithm&lt;/h3&gt;

The main result in Louis (1982) (\ref{Louismain}) can be written
\begin{equation}\label{Louismain2}
\mathcal{I}(\theta,y) = E_{X|y,\theta} [ B(X,y|\theta)] - var_{X|y,\theta} [ S(X,y|\theta) ]
\end{equation}
The M-step of the EM algorithm involves the first derivative of the log-likelihood with respect to \(\theta\), \( S(X,y|\theta) \), since it involves setting this derivative to zero:
\begin{equation} 
Q^\prime(\theta | \theta_j) = d( E_{X|y,\theta_j } [\log f_{XY}(X,y|\theta) ])/d\theta = E_{X|y,\theta_j } [\log f^\prime_{XY}(X,y|\theta) ] = E_{X|y,\theta_j } [ S(X,y|\theta) ]
\end{equation} 
With the MARSS model, \( S(X,y|\theta) \) is analytical and we can also compute \( B(X,y|\theta)\), the second derivative, analytically.  

&lt;br /&gt;&lt;br /&gt;

&#39;The difficulty arises with this term: \( var_{X|y,\theta} [ S(X,y|\theta) ] \).  The \(S(X,y|\theta)\) is a summation from \(t=1\) to \(T\) that involves \( X_t \) or \( X_t X_{t-1}^top \) for some parameters. When we do the cross-product, we will end up with terms like  \( E[ X_t X_{t+k}^\top ] \) and \( E[ X_t X_t^\top X_{t+k}X_{t+k}^\top ] \).  The latter is not a problem; all the random variables in a MARSS models are multivariate normal and the k-th central moments can be expressed in terms of the first and second moments [5], but that will still leave us with terms like \( E[ X_t X_{t+k}^\top ] \)---the smoothed covariance between \(X\) at time \(t\) and \(t+k\) conditioned on all the data (\(t=1:T\)).  
&lt;br /&gt;&lt;br /&gt;
Computing these is not hard.  These are the the n-step apart smoothed covariances. Harvey (1989), page 148, discusses how to use the Kalman filter to get the n-step ahead prediction covariances and a similar approach can be used (presumably) to get the \( V(t,t+k) \) smoothed covariances.  However this will end up being computationally expensive because we will need all of the \( t,t+k \) combinations, i.e., {1,3}, {1,4}, ..., {2,3}, {2,4}, .... etc.. That will be a lot: T + T-1 + T-2 + T-3 = 
\( T(T+1)/2 \), smoothed covariances.  
Lystig and Hughes (2012) and Duan and Fulop (2011) discuss this issue for in a related application of the approach in Louis (1982).  They suggest that you do not need to include covariances with a large time separation because the covariance goes to zero.  You just need to include enough time-steps. 

&lt;h3&gt;Conclusion&lt;/h3&gt;

I think the approach of Louis (1982) is not viable for MARSS models. The derivatives \(B(x,y|\theta)\) and \(S(x,y|\theta)\) are straight-forward (if tedious) to compute analytically following the approach in Holmes (2010).  But the computing all the n-step smoothed covariances is going to be very slow and each computation involves many matrix multiplications.  However, one could compute \( \mathcal{I}(\theta,y) \) via simulation using \ref{Louismain2}.  It is easy enough to simulate \( X\) using the MLEs and then you compute \(B(x_b,y|\theta)\) and \(S(x_b,y|\theta)\) for each where \(x_b\) is the bootstrapped \(x\) time series and \(y\) is the data.  I don&#39;t think it makes sense to do that for MARSS models since there are two recursion approaches for computing the observed and expected Fisher Information using \(f(y|\theta)\) and the Kalman filter equations (Harvey 1989, pages 140-142; Cavanaugh and Shumway 1996).
&lt;hr&gt;

&lt;h2&gt;Footnotes&lt;/h2&gt;
[1] Given a joint probability distribution of \( \{X,Y\}\), the marginal distribution of \( Y \) is \( \int_X f(X,Y) dx \).  Discussions of the estimators for MARSS models often use the property of the marginal distributions of a multivariate normal without actually stating that this property is being used.  The step in the derivation will just say, &#39;Thus&#39; with no indication of what property was just used. &lt;br \&gt;Reviewed here: http://fourier.eng.hmc.edu/e161/lectures/gaussianprocess/node7.html 
If you have a joint likelihood of some random variables, and you want the likelihood of a subset of those random variables, then you compute the marginal distribution.  i.e. you integrate over the random variables you want to get rid of:
\[ L(\theta | y) ] = \int_X L(\theta | X,Y) p(x|Y=y, \theta_j) dx |_{Y=y}  \].
So we integrate out \( X \) from the full likelihood and then set \( Y=y \) to get the likelihood we want to maximize to get the MLE \( \theta \) (if we want MLEs).
&lt;br \&gt;&lt;br \&gt;
The marginal likelihood is a little different.  The marginal likelihood is used when you want to get rid of some of the parameters, nuisance parameters.  The integral you use is different: 
\[ L(\theta_1|y) = \int_{\theta_2} p(y|\theta_1,\theta_2) p(\theta_2|\theta_1)d\theta_2 \]
This presumes that you have \( p(\theta_2|\theta_1) \).
&lt;br \&gt;&lt;br \&gt;
The expected likelihood is different yet again:  
\[ E_{X,Y|Y=y,\theta_j} [L(\theta | X,Y) ] = \int_X L(\theta | X,Y) p(x|Y=y, \theta_j) dx  \].
On the surface it looks like the equation for \( L(\theta|y) \) but it is different.  \( \theta_j \) is not \( \theta \).  It is the parameter value at which we are computing the expected value of \( X \).  Maximizing the \(  E_{X,Y|Y=y,\theta_j} [L(\theta | X,Y) ] \) will increase the likelihood but will not take you to the MLE---you have to imbed this maximization in the EM algorithm that walks up the likelihood surface.
&lt;br/&gt;&lt;br/&gt;
[2] P(A|B) = P(A \cup \B)/P(B)
&lt;br/&gt;&lt;br/&gt;
[3] I normally think about \( Y \) as being partially observed (missing values) so I also take the expectation over \( Y(2) \) conditioned on \(Y(1)\), where (1) means observed and (2) means missing.  In Holmes (2010), this is done in order to derive general EM update equations for the missing values case.  But my notation is getting hairy, so for this write-up, I&#39;m treating \(Y\) as fully observed; so no \(Y(2)\) and I&#39;ve dropped the integrals (expectations) over \( Y(2) \).
&lt;br/&gt;&lt;br/&gt;
[4] http://people.missouristate.edu/songfengzheng/Teaching/MTH541/Lecture%20notes/Fisher_info.pdf
&lt;br/&gt;&lt;br/&gt;
[5] https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Higher_moments

&lt;br /&gt;&lt;br /&gt;
&lt;h2&gt;Papers and online references&lt;/h2&gt;
Ng, Krishnan and McLachlan 2004&lt;br /&gt;
The EM algorithm.  Section 3.5 discusses standard errors approaches&lt;br /&gt;
https://www.econstor.eu/dspace/bitstream/10419/22198/1/24_tk_gm_skn.pdf&lt;br /&gt;
http://hdl.handle.net/10419/22198
&lt;br /&gt;&lt;br /&gt;
Efron and Hinkley 1978&lt;br /&gt;
(argues that the observed Fisher Information is better than expected Fisher Information in many/some cases.  The same paper argues for the likelihood ratio method for CIs)&lt;br /&gt;
Assessing the accuracy of the maximum likelihood estimator: observed versus expected Fisher Information&lt;br /&gt;
https://www.stat.tamu.edu/~suhasini/teaching613/expected_observed_information78.pdf
&lt;br /&gt;&lt;br /&gt;
Hamilton 1994&lt;br /&gt;
http://web.pdx.edu/~crkl/readings/Hamilton94.pdf
&lt;br /&gt;&lt;br /&gt;
Hamilton&#39;s exposition assumes you know the marginal distribution of a multivariate normal.  Scroll down to the bottom.&lt;br /&gt;
http://fourier.eng.hmc.edu/e161/lectures/gaussianprocess/node7.html
&lt;br /&gt;&lt;br /&gt;
Meilijson 1989&lt;br /&gt;
Fast improvement to the EM algorithm on its own terms&lt;br /&gt;
http://www.jstor.org/stable/pdf/2345847.pdf
&lt;br /&gt;&lt;br /&gt;
Oakes 1999&lt;br /&gt;
Direct calculation of the information matrix via the EM algorithm&lt;br /&gt;
http://www.jstor.org/stable/pdf/2680653.pdf?_=1463187953783
&lt;br /&gt;&lt;br /&gt;
Ho, Shumway and Ombao 2006&lt;br /&gt;
(this has a brief statement that Oakes 1999 derivatives are hard to compute.  It doesn&#39;t say why. It says nothing of Louis 1982.)&lt;br /&gt;
Chapter 7, The state-space approach to modeling dynamic processes&lt;br /&gt;
Models for Intensive Longitudinal Data&lt;br /&gt;
https://books.google.com/books?hl=en&amp;lr=&amp;id=Semo20xZ_M8C
&lt;br /&gt;&lt;br /&gt;
Louis 1982&lt;br /&gt;
(so elegant. alas, MARSS deals with time series data...)&lt;br /&gt;
Finding the observed information matrix when using the EM algorithm&lt;br /&gt;
http://www.jstor.org/stable/pdf/2345828.pdf&lt;br /&gt;
http://www.markirwin.net/stat220/Refs/louis1982.pdf
&lt;br /&gt;&lt;br /&gt;
Lystig and Hughes 2012 &lt;br /&gt;
(helped me better understand why Louis 1982 is hard for MARSS models)&lt;br /&gt;
Exact computation of the observed information matrix for hidden Markov models&lt;br /&gt;
http://www.tandfonline.com.offcampus.lib.washington.edu/doi/abs/10.1198/106186002402
&lt;br /&gt;&lt;br /&gt;
Duan and Fulop 2011&lt;br /&gt;
(also helped me better understand why Louis 1982 is hard for MARSS models)&lt;br /&gt;
A stable estimator for the information matrix under EM for dependent data&lt;br /&gt;
http://www.rmi.nus.edu.sg/DuanJC/index_files/files/EM_Variance_March%205%202007.pdf&lt;br /&gt;
http://link.springer.com/article/10.1007/s11222-009-9149-4
&lt;br /&gt;&lt;br /&gt;
Naranjo 2007  (didn&#39;t use)&lt;br /&gt;
State-space models with exogenous variables and missing data, PhD U of FL&lt;br /&gt;
http://etd.fcla.edu/UF/UFE0021568/naranjo_a.pdf
&lt;br /&gt;&lt;br /&gt;
Dempster, Laird, Rubin 1977&lt;br /&gt;
(didn&#39;t really use but looked up more info on the &#39;score&#39; function Q)&lt;br /&gt;
Maximum likelihood for incomplete data via the EM algorithm&lt;br /&gt;
http://web.mit.edu/6.435/www/Dempster77.pdf
&lt;br /&gt;&lt;br /&gt;
van Dyk, Meng and Rubin 1995&lt;br /&gt;
(this looks promising)&lt;br /&gt;
Maximum likelihood estimation via the ECM algorithm: computing the asymptotic variance&lt;br /&gt;
http://wwwf.imperial.ac.uk/~dvandyk/Research/95-sinica-secm.pdf
&lt;br /&gt;&lt;br /&gt;
Cavanaugh and Shumway 1996&lt;br /&gt;
On computing the expected Fisher Information Matrix for state-space model parameters&lt;br /&gt;
&lt;br /&gt;&lt;br /&gt;
Harvey 1989, pages 140-143, Section 3.4.5 Information matrix&lt;br /&gt;
Forecasting, structural time series models and the Kalman filter&lt;br /&gt;

&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/7006244654917436404/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/7006244654917436404' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/7006244654917436404'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/7006244654917436404'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2016/05/notes-on-computing-fisher-information_19.html' title='Notes on computing the Fisher Information matrix for MARSS models. Part II Louis 1982'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-8761044211060546023</id><published>2016-05-18T17:52:00.000-07:00</published><updated>2017-05-31T13:32:48.789-07:00</updated><title type='text'>Notes on computing the Fisher Information matrix for MARSS models.  Part I Background</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;script src=&quot;https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&quot; type=&quot;text/javascript&quot;&gt;
&lt;/script&gt;
&lt;i&gt;MathJax and blogger can be iffy.  Try reloading if the equations don&#39;t show up and then wait, like 30-60 seconds for the equations to magically appear (fingers crossed).&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
The Fisher Information is defined as
\begin{equation}\label{FisherInformation}
I(\theta) = E_{Y|\theta}\{ [\partial\log L(\theta|Y)/\partial\theta]^2 \} = \int_x [\partial\log L(\theta|y)/\partial\theta]^2 f(y|\theta)dy
\end{equation}
In words, it is the expected value (taken over all possible data) of the square of the gradient (first derivative) of the log likelihood surface at \( \theta \).  It is a measure of how much information data (from our experiment or monitoring) have about \( \theta \).  The log-likelihood surface is for a fixed set of data and the \( \theta \) vary.  The peak is at the MLE, which is not \( \theta \), so the surface has some gradient  (slope) at \( \theta \) since the peak is at the MLE not \( \theta \).  The Fisher Information is the expected value (over possible data) of those gradients (squared).

It can be shown[1] that the Fisher Information can also be written as
\[ I(\theta) = - E_{Y|\theta}\{ \partial^2\log L(\theta|Y)/\partial\theta^2 \} = -\int_y [\partial^2\log L(\theta|y)/\partial\theta^2 f(y|\theta)dy \] 
So the Fisher Information is the average (over possible data) convexity of the log-likelihood surface at \( \theta \). That doesn&#39;t quite make sense to me.  When I imagine the surface, that the convexity at a non-peak value \( \theta \) is not intuitively the information.  The gradient squared, I understand, but the convexity at a non-peak?

Note, my \( y \) should be understood to be some multi-dimensional data set (multiple sites over multiple time points, say), and is comprised of multiple samples.   Often in this case Fisher Information is written \( I_n(\theta) \) and if the data points are all independent, \( I(\theta)=\frac{1}{n} I_n(\theta) \).  However I&#39;m not using that notation. My \( I(\theta) \) is referring to the Fisher Information for a dataset not individual data points within that data set.

We do not know \( \theta \) so we need to use an estimator for the Fisher Information. A common approach is to use \( I(\hat{\theta}) \), the Fisher Information at the MLE \( \theta \) as an estimator of \( I(\theta) \) because:
\[ I(\hat{\theta}) \xrightarrow{P} I(\theta) \]
This is called the &lt;i&gt;expected&lt;/i&gt; Fisher Information and is computed at the MLE:
\begin{equation}\label{expectedFisherInformation}
I(\hat{\theta}) = - E_{Y|\hat{\theta}}\{ \partial^2\log L(\theta|Y)/\partial \theta^2 \} |_{\theta=\hat{\theta}}
\end{equation}
That \( |_{\theta=\hat{\theta}} \) at the end means that after doing the derivative with respect to \( \theta \), we replace \( \theta \) with \( \hat{\theta} \).  It would not make sense to do the substitution before since \( \hat{\theta} \) is a fixed value and so you cannot take the derivative with respect to it.
This is a viable approach if you can take the derivative of the log-likelihood with respect to \( \theta \) and can take the expectation over the data.  You could always do that expectation using simulation of course.  You just need to be able to simulate data from your model with \( \hat{\theta} \).

Another approach is to drop the expectation.  This is termed the &lt;i&gt;observed&lt;/i&gt; Fisher Information: 
\begin{equation}\label{observedFisherInformation}
\mathcal{I}(\hat{\theta},y) = - \left.\frac{\partial^2\log L(\theta|y)}{\partial \theta^2} \right|_{\theta=\hat{\theta}}
\end{equation}
where \( y \) is the one dataset we collected.  The observed Fisher Information is the curvature of the log-likelihood function around the MLE. When you estimate the variance of the MLEs from the Hessian of the log-likelihood (output from say some kind of Newton method or any other algorithm that uses the Hessian of the log-likelihood), then you are using the observed Fisher Information matrix.  Efron and Hinkley (1978) (and Fisher they say in their article) say that the observed Fisher Information is a better estimate of the variance of \( \hat{\theta} \)[2][3], while Cavanaugh and Shumway (1996) show results from MARSS models that indicate that the expected Fisher Information has lower mean squared error (though may be more biased; mean squared error measures both bias and precision).

So how do we compute \( I(\hat{\theta}) \) or \( \mathcal{I}(\hat{\theta},y) \)?  In particular, I am interested in whether I can use the analytical derivatives of the full log-likelihood that are part of the EM algorithm? &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2016/05/notes-on-computing-fisher-information_19.html&quot;&gt;Notes on computing the Fisher Information matrix for MARSS models. Part II EM&lt;/a&gt;

&lt;/div&gt;
&lt;hr /&gt;
&lt;h2&gt;
Footnotes&lt;/h2&gt;
[1] See any detailed write-up on Fisher Information.  For example page 2 of these &lt;a href=&quot;http://people.missouristate.edu/songfengzheng/Teaching/MTH541/Lecture%20notes/Fisher_info.pdf&quot;&gt;lecture notes on Fisher Information&lt;/a&gt;.&lt;br /&gt;
[2] The motivation for computing the Fisher Information is to get an estimate of the variance of \( \hat{\theta} \) for standard errors on the parameter estimates, say.  \( var(\hat{\theta}) \xrightarrow{P} \frac{1}{I(\theta)} \).&lt;br /&gt;
[3] Note I&#39;m using the notation of Cavanaugh and Shumway (1996).  Efron and Hinkley (1978) use \( \mathscr{I}(\theta) \) for  the expected Fisher Information and \( I(\theta) \) for the observed Fisher Information.  Cavanaugh and Shumway (1996) use \( I(\theta) \) for the expected Fisher Information and \( \mathcal{I}(\theta,Y) \) for the observed Fisher Information.  I use the same notation as Cavanaugh and Shumway (1996) except that they use \( I_n() \) and \( \mathcal{I}_n \) to be explicit that the data have \( n \) data points.  I drop the \( n \) since I&#39;m interested in the Fisher Information of the dataset not individual data points and if I need to use the information of the j-th data point, I would just write \( I_j() \).  The other difference is that I use \( y \) to refer to the data.   In my notation, \( Y \) is the random variable &#39;data&#39; and \( y \) is a particular realization of that random variable.  In some cases, I use  \( y(1) \).  That is when the random variable \( Y \) is only partially observed (meaning there are missing data points or time steps); \( y(1) \) is the observed portion of \( Y \).

&lt;br /&gt;
&lt;h2&gt;
References I looked at while working on this&lt;/h2&gt;
&lt;b&gt;Fisher Info Lectures&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
http://people.missouristate.edu/songfengzheng/Teaching/MTH541/Lecture%20notes/Fisher_info.pdf
http://www.math.umt.edu/patterson/Information.pdf
http://www.stat.umn.edu/geyer/old03/5102/notes/fish.pdf

I also studied the &lt;a href=&quot;https://en.wikipedia.org/wiki/Fisher_information&quot;&gt;Wikipedia Fisher Information page&lt;/a&gt;.  Cavanaugh and Shumway (1996) have a succinct summary of Fisher Information in their introduction and I adopted their notation.
 
&lt;b&gt;Papers&lt;/b&gt;
Efron and Hinkley 1978
(argues that the observed Fisher Information is better than expected Fisher Information in many/some cases.  The same paper argues for the likelihood ratio method for CIs)
Assessing the accuracy of the maximum likelihood estimator: observed versus expected Fisher Information
https://www.stat.tamu.edu/~suhasini/teaching613/expected_observed_information78.pdf

&lt;br /&gt;&lt;br /&gt;
Cavanaugh and Shumway 1996&lt;br /&gt;
On computing the expected Fisher Information Matrix for state-space model parameters&lt;br /&gt;

&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/8761044211060546023/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/8761044211060546023' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8761044211060546023'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8761044211060546023'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2016/05/notes-on-computing-fisher-information.html' title='Notes on computing the Fisher Information matrix for MARSS models.  Part I Background'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-2469073666450341410</id><published>2016-04-28T17:09:00.001-07:00</published><updated>2017-01-31T11:45:49.381-08:00</updated><title type='text'>Analysis of PhD and Baccalaureate origin of math faculty (Part I)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
I&#39;ve been pondering the educational paths of math faculty, so I decided to collect some data by visiting the faculty websites and looking at CVs.&amp;nbsp; I started with the top 20 or so schools on this ranking &lt;a href=&quot;http://www.phds.org/rankings/mathematics&quot;&gt;http://www.phds.org/rankings/mathematics&lt;/a&gt; and then added a few.&amp;nbsp; I added some schools like U of WA, U of FL and U of ID for more regional diversity.&amp;nbsp; I only collected data on PhD and undergrad institution from faculty who got their PhD in the US.&amp;nbsp; If they got their undergrad degree in another country, I noted the country.&amp;nbsp; If no undergrad institution was listed, I added with undergrad &#39;unknown&#39;.&amp;nbsp; I only included full, associate and assistant faculty.&amp;nbsp; I excluded lecturers and research faculty.&amp;nbsp; I took data from 30 institutions (below).&amp;nbsp; I was able to get PhD data on 761 faculty (656 male/105 female) and undergrad data on 577 of these (489 male/88 female).  Here where the faculty data were collected broken out by institution.  The number in parentheses is the number of faculty for which I was able to collect data.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;GEWYW5YBFEB&quot; id=&quot;rstudio_console_output&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important; word-break: break-all;&quot; tabindex=&quot;0&quot;&gt;CalTech(5), Columbia(21), Cornell(30), Harvard(23), MIT(48), NYU(43), Penn State(36), Princeton(34), Rutgers(55), Stanford(31), U Chicago(50), U of AZ(29), U of FL(33),U of ID(14), U of IL UC(36), U of MD(25), U of Mich(57), U of MN(26), U of MN Duluth(2), U of Rochester(13), U of T Austin(58), U of Utah(32), U of WA(47), U of WI(45), UC Berk(73), UC Davis(17), UC Irvine(18), UCLA(38), UPenn(14), Yale(17)&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
Here are the first set of plots.&amp;nbsp; These plots show where faculty (whose info was posted) got their PhDs 
and bachelors. &amp;nbsp;Only ca 50% of faculty post CVs so this is a sample of 
the faculty. &amp;nbsp;Only faculty, not lecturers or research faculty included. 
&amp;nbsp;But I did include assistant and associate faculty. &amp;nbsp;Note, I excluded 
faculty who got their PhD in another country. &amp;nbsp;That&#39;s about 10% (except 
at CalTech where it is about 75%).&lt;br /&gt;
&lt;br /&gt;
Plot 1 is just the &lt;b&gt;Group 1&lt;/b&gt; institutions. &amp;nbsp;&lt;b&gt;Harvard, Princeton, MIT, UC Berkeley, NYU, Stanford.&lt;/b&gt;&lt;br /&gt;
Why
 these? You&#39;ll see in plot 2. &amp;nbsp;Plot 1 shows that this group is closed. 
&amp;nbsp;Almost all faculty within this group got their PhD from institutions within 
this group. &amp;nbsp;For the bachelor degrees, about 30% got their undergrad 
degree in another country. &amp;nbsp;For 
those that got their bachelor&#39;s in the US, 40% got their bachelors from 
Group 1 and 50% got their undergrad from the Ivies+MIT+Stanford (excluding
 UC Berk).&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjws2JGc0gG0EcblqMytZjwOc1sBtqDpgu7rR7vTSvxqWC_3J6RV40Z-MwkBXdQ3Cu1wXlZ9sZSYLl51GOa8KsNtTxcBVibPaIykX_MRdTxMhJtfkRpHe_gqEQvLPeSbsb5DIzcTQ/s1600/Fig1-Closed-DPS.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;353&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjws2JGc0gG0EcblqMytZjwOc1sBtqDpgu7rR7vTSvxqWC_3J6RV40Z-MwkBXdQ3Cu1wXlZ9sZSYLl51GOa8KsNtTxcBVibPaIykX_MRdTxMhJtfkRpHe_gqEQvLPeSbsb5DIzcTQ/s640/Fig1-Closed-DPS.jpg&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
Click figure to see full size.&lt;br /&gt;
&lt;br /&gt;
Plot 2 shows just faculty from OUTSIDE Group 1. &amp;nbsp;These
 are 23 large research universities. &amp;nbsp;See the figure for the list. 
&amp;nbsp;Within this group of 23,&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;56% of faculty got their PhD from Group 1 (right 
figure). &lt;i&gt;This was how I defined Group 1&lt;/i&gt;--the schools whose PhDs showed 
up disproportionately.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;23% 
 got it from a University of XYZ (excluding UC Berkeley).&amp;nbsp; This includes Canada flagships (so U of Toronto) but excludes, say, U of Rochester.&lt;/li&gt;
&lt;li&gt;2% got it from a XYZ State 
institution (incl SUNY) &lt;/li&gt;
&lt;/ul&gt;
&amp;nbsp;Group 1 shows up disproportionately in
 the undergrad degrees too. &amp;nbsp;If the faculty got the undergrad degree in 
the US (about 60% of them), then&lt;br /&gt;
&lt;div&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;35% got their undergrad degree from a Group 1 institution&lt;/li&gt;
&lt;li&gt;35% got it from the Ivies+MIT+Stanford. However, Dartmouth is an outlier as few of its undergrads show up. &lt;/li&gt;
&lt;li&gt;16%
 got it from a University of XYZ and 7% got it from a XYZ State 
institution. &amp;nbsp;This includes Canada flagships (so U of Toronto) but excludes, say, U of Rochester.&lt;/li&gt;
&lt;li&gt;13% got it from a small liberal arts college.&amp;nbsp; 27 different LACs appear, and almost all appear only once.&amp;nbsp; The exception is Reed which appears 4x.&lt;/li&gt;
&lt;li&gt;5.6% got if from the UC system (includes UC Berkeley which is 3.6 percent)&lt;/li&gt;
&lt;li&gt;This means that over 2x as many faculty got their undergrad from a LAC than the entire UC system (188,000 undergrads).&amp;nbsp; However, there are many LAC institutions and the total sum of their enrollment is likely greater than 188,000 undergrads.&amp;nbsp;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;43 out of the 248 faculty in this sample got their undergrad degree from Harvard or Princeton.&amp;nbsp; That&#39;s 17%!&amp;nbsp;&amp;nbsp; It is somewhat higher in Group 1, 25%.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0qsmdGjC0exW2-GfFs-mId6fG7gN7OjsjTy2so4iXXQtzS_lPY47syR1aeLGxX4lfLDrWtBqEtMQRc0GcnW_P6UTAj68mkUmdcRFGZbWgzVdlobz6lGEh8_8Jbh1XCUTqNKYggQ/s1600/Fig2-Bac-PhD-Origins.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;354&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0qsmdGjC0exW2-GfFs-mId6fG7gN7OjsjTy2so4iXXQtzS_lPY47syR1aeLGxX4lfLDrWtBqEtMQRc0GcnW_P6UTAj68mkUmdcRFGZbWgzVdlobz6lGEh8_8Jbh1XCUTqNKYggQ/s640/Fig2-Bac-PhD-Origins.jpg&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Related work: There is much work on this in other fields however I have not seen work that also looks at baccalaureate origin.&lt;br /&gt;
&lt;br /&gt;
2015 &lt;a href=&quot;http://advances.sciencemag.org/content/1/1/e1400005&quot;&gt;Systematic inequality and hierarchy in faculty hiring networks&lt;/a&gt;  See esp the list of references in this paper.&lt;/div&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/2469073666450341410/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/2469073666450341410' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/2469073666450341410'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/2469073666450341410'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2016/04/analysis-of-phd-and-baccalaureate.html' title='Analysis of PhD and Baccalaureate origin of math faculty (Part I)'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjws2JGc0gG0EcblqMytZjwOc1sBtqDpgu7rR7vTSvxqWC_3J6RV40Z-MwkBXdQ3Cu1wXlZ9sZSYLl51GOa8KsNtTxcBVibPaIykX_MRdTxMhJtfkRpHe_gqEQvLPeSbsb5DIzcTQ/s72-c/Fig1-Closed-DPS.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-5294435079243291116</id><published>2015-04-23T18:18:00.002-07:00</published><updated>2015-04-23T18:43:00.383-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="R"/><category scheme="http://www.blogger.com/atom/ns#" term="R packages"/><title type='text'>Another way to get R package download stats</title><content type='html'>This is code from Mark Scheuerell that was adapted from this post by Felix Schonbrodt for a different way to get download stats: &lt;a href=&quot;http://www.nicebread.de/finally-tracking-cran-packages-downloads/&quot;&gt;http://www.nicebread.de/finally-tracking-cran-packages-downloads/&lt;/a&gt;
&lt;pre&gt;
## adadpted from code by Felix Schonbrodt
## http://www.nicebread.de/finally-tracking-cran-packages-downloads/


## ======================================================================
## Step 1: Download all log files
## ======================================================================

# start &amp; end dates 12 months prior to current date
this.year = as.numeric(format(Sys.time(), &quot;%Y&quot;))
start &lt;- as.Date( paste(this.year-1,&quot;-&quot;,format(Sys.time(), &quot;%m-%d&quot;),sep=&quot;&quot;) )
today &lt;- as.Date(Sys.time())

all_days &lt;- seq(start, today, by = &#39;day&#39;)

year &lt;- as.POSIXlt(all_days)$year + 1900
urls &lt;- paste0(&#39;http://cran-logs.rstudio.com/&#39;, year, &#39;/&#39;, all_days, &#39;.csv.gz&#39;)

# only download the files you don&#39;t have:
missing_days &lt;- setdiff(as.character(all_days), tools::file_path_sans_ext(dir(&quot;CRANlogs&quot;), TRUE))

dir.create(&quot;CRANlogs&quot;)
for (i in 1:length(missing_days)) {
  print(paste0(i, &quot;/&quot;, length(missing_days)))
  download.file(urls[i], paste0(&#39;CRANlogs/&#39;, missing_days[i], &#39;.csv.gz&#39;))
}


## ======================================================================
## Step 2: Load single data files into one big data.table
##
##   NOTE: this step takes FOREVER to run
## ======================================================================

file_list &lt;- list.files(&quot;CRANlogs&quot;, full.names=TRUE)

logs &lt;- list()
for (file in file_list) {
  print(paste(&quot;Reading&quot;, file, &quot;...&quot;))
  logs[[file]] &lt;- read.table(file, header = TRUE, sep = &quot;,&quot;, quote = &quot;\&quot;&quot;,
                             dec = &quot;.&quot;, fill = TRUE, comment.char = &quot;&quot;, as.is=TRUE)
}

# rbind together all files
library(data.table)
dat &lt;- rbindlist(logs)

# add some keys and define variable types
dat[, date:=as.Date(date)]
dat[, package:=factor(package)]
dat[, country:=factor(country)]
dat[, weekday:=weekdays(date)]
dat[, week:=strftime(as.POSIXlt(date),format=&quot;%Y-%W&quot;)]

setkey(dat, package, date, week, country)

save(dat, file=&quot;CRANlogs/CRANlogs.RData&quot;)

# for later analyses: load the saved data.table
# load(&quot;CRANlogs/CRANlogs.RData&quot;)


## ======================================================================
## Step 3: Plot results
## ======================================================================

# vector of pkgs to compare
pkgs &lt;- c(&quot;MARSS&quot;,&quot;dlm&quot;)

# vector of plot colors
clr &lt;- seq(length(pkgs))

# downloads of selected pkgs by week
com1 &lt;- dat[J(pkgs), length(unique(ip_id)), by=c(&quot;week&quot;, &quot;package&quot;)]

# total downloads to date
com1[, sum(V1), by=package]

# cumulative downloads by week
com1$C1 &lt;- (com1[, cumsum(V1), by=package])$V1

# nicer form for plotting
plotdat &lt;- cast(com1,week ~ package, value=&quot;C1&quot;)

# plot cumulative downloads over time
matplot(plotdat,
        type=&quot;l&quot;, lty=&quot;solid&quot;, lwd=2, col=clr,
        ylab=&quot;Cumulative downloads&quot;,
        xlab=&quot;Week of 2013&quot;)

legend(x=&quot;topleft&quot;, legend=colnames(plotdat)[-1],
       lty=&quot;solid&quot;, lwd=2, col=clr)
&lt;/pre&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/5294435079243291116/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/5294435079243291116' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/5294435079243291116'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/5294435079243291116'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2015/04/another-way-to-get-r-package-download.html' title='Another way to get R package download stats'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-1056207277769975794</id><published>2014-01-10T15:45:00.000-08:00</published><updated>2014-01-14T17:54:17.326-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="MARSS"/><title type='text'>More general formulation. Tests 2</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
More tests today of formulating MARSS model as in the napkin math of &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2014/01/more-general-formulation-of-marss-model.html&quot;&gt;previous post&lt;/a&gt;.&amp;nbsp; Better.&amp;nbsp; Slightly faster (3-5%).&amp;nbsp; I need to think more carefully if the x0 treatment is identical.  data needs to have NA added column since X is x(t) over y(t-1) so at t=1 you have x(1) over y(0).  There is never any data at t=0.&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;Update: But adding NA to the start is not the same as using x00, and I will need to recode the Kalman filter to get the right result with x = [x(t) y(t-1)]&#39; at t=1.&amp;nbsp;&amp;nbsp; It happens to work here, but other tests suggests not in general.&amp;nbsp; Probably not a fruitful direction since perhaps it is not really necessary to have constraints across B and Z, though it feels &#39;complete&#39;.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
To do: This helps, but previous where I incorporated U into B slowed things down a lot.&amp;nbsp; Why is that? Most likely because of the Q=0 bit and hits the OmgQ code.&amp;nbsp; How about adding a y=1 row and setting Q=1 so as not to hit that code?&amp;nbsp; With new formulation, I can have U*y(n+1) so U*1.&amp;nbsp; That should work.&amp;nbsp; &quot;working using Tt form 2.R&quot; in MARSS sandbox dir.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
Estimates are pretty similar but not identical.
&lt;br /&gt;
&lt;pre&gt;#spp interaction example
royale.dat = log(t(isleRoyal[,2:3]))
z.royale.dat=(royale.dat-apply(royale.dat,1,mean,na.rm=TRUE))/
  sqrt(apply(royale.dat,1,var,na.rm=TRUE))
Q=matrix(list(0),2,2);diag(Q)=c(&quot;q1&quot;,&quot;q2&quot;)
royale.model.1=list(Z=&quot;identity&quot;, B=&quot;unconstrained&quot;,
                    Q=Q, R=&quot;diagonal and unequal&quot;,
                    U=&quot;zero&quot;, tinitx=0)
cntl.list=list(allow.degen=FALSE,maxit=200)
tic()
kemfit=MARSS(z.royale.dat, model=royale.model.1, control=list(allow.degen=FALSE))
toc()

a=summary(kemfit$model)
tinitx=a$tinitx
m=dim(a$B)[1];n=dim(a$Z)[1]
Bt=matrix(list(0),n+m,n+m);Bt[1:m,1:m]=a$B;Bt[(m+1):(n+m),1:m]=a$Z
Zt=matrix(list(0),n,m+n); Zt[1:n,(m+1):(m+n)]=diag(1,n)
Qt=matrix(list(0),m+n,m+n); Qt[1:m,1:m]=a$Q; Qt[(m+1):(n+m),(m+1):(n+m)]=a$R
x0t=rbind(a$x0,matrix(list(0),n,1))
V0t=matrix(list(0),n+m,n+m); VV0t[1:m,1:m]=a$V0
Ut=rbind(a$U,a$A)

newa = list(B=Bt, Z=Zt, U=Ut, A=&quot;zero&quot;, Q=Qt, R=&quot;zero&quot;, x0=x0t, V0=V0t, tinitx=tinitx)
inits.list=list(x0=matrix(1+kemfit$model$data[,1],m,1))
ddat=cbind(NA,kemfit$model$data)
tic()
kemfita = MARSS(ddat, model=newa, control=list(allow.degen=FALSE),inits=inits.list)
toc()
p1=coef(kemfit); p2=coef(kemfita)
rbind(c(p1$B,p1$Z,p1$U,p1$Q,p1$R,p1$x0,kemfit$logLik),c(p2$B,p2$U,p2$Q,p2$x0,kemfit$logLik))

#Works with this kemfit too
dat = t(harborSealWA)
dat = dat[2:4,] #remove the year row
#fit a model with 1 hidden state and 3 observation time series
tic()
kemfit = MARSS(dat, model=list(U=matrix(c(&quot;N&quot;,&quot;S&quot;,&quot;S&quot;),3,1),tinitx=0), control=list(allow.degen=FALSE))
toc()
&lt;/pre&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/1056207277769975794/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/1056207277769975794' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/1056207277769975794'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/1056207277769975794'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2014/01/more-general-formulation-tests-2.html' title='More general formulation. Tests 2'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-2209905237294234757</id><published>2014-01-06T14:48:00.000-08:00</published><updated>2014-01-14T14:49:33.052-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="MARSS"/><title type='text'>More general formulation of the MARSS model</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Napkin math.&amp;nbsp; I&#39;ve been pondering for some time how to formulate the MARSS model in a more general way to more fully allow constraints across parameter matrices and across the X and Y parts of the model.&amp;nbsp; I also want to allow X to be observed.&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;Update 1/6/2014: This doesn&#39;t seem to get me anywhere.&amp;nbsp; The EM algorithm requires that estimated matrix elements fall on rows of Q (and R) which are non-zero. Even putting U in B (or A into Z), thus one additional row---slows down the EM algorithm.&amp;nbsp; Merging the y and x together in a matrix, means I have NAs in the y*, representing the unobserved x in the stacked y-x.&amp;nbsp; That leads to problems estimating x_0 because R=0 for those.&amp;nbsp; That problem is fixable, but the others are more intractable.&amp;nbsp; Given that just putting U into B didn&#39;t seem to get me anywhere, I&#39;m going to drop this tangent and work on other stuff.&amp;nbsp;&amp;nbsp; The test code for putting U into B is below.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
The first napkin shows how I think I want to do this.&amp;nbsp; e_t is iid 0,1 Gaussian noise.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFhY6XKli1CGSgKiKI2O_w5sqqblQzpCfooxN1ie78zXzjx1FzirzM0bu6QeIu7pJRw3eRpLqqjMysLlbjuPbIEiXfPRqIRC9WhVYLi0uIbAueBwETON2x-BlVRBMW_0o2NVauMQ/s1600/photo.JPG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;239&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFhY6XKli1CGSgKiKI2O_w5sqqblQzpCfooxN1ie78zXzjx1FzirzM0bu6QeIu7pJRw3eRpLqqjMysLlbjuPbIEiXfPRqIRC9WhVYLi0uIbAueBwETON2x-BlVRBMW_0o2NVauMQ/s1600/photo.JPG&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
The second napkin shows how to set this up as a standard MARSS eqn, but involves a var-cov error matrix with a bunch of 0s.&amp;nbsp; That&#39;s bad because wherever 0 rows appear in Q (or R), that row of B (or Z) cannot be estimated with the EM algorithm because it falls out of the likelihood equation that you integrate to get the updated B.&amp;nbsp; That&#39;s a general difficulty with the EM approach.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDwhuOfvBrzb9je8ujs7RCSEwSqdq5YDfJzTcZq6cPxCgDndXRKn-lZQ_sYQfTTLx7k0tHmNubpUYuTIgdHsmtaiYK2KZEaG1ebhhjZf4YRxkqnluTGsBwzEyFEKfixizQPwBLhQ/s1600/photo2.JPG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;239&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDwhuOfvBrzb9je8ujs7RCSEwSqdq5YDfJzTcZq6cPxCgDndXRKn-lZQ_sYQfTTLx7k0tHmNubpUYuTIgdHsmtaiYK2KZEaG1ebhhjZf4YRxkqnluTGsBwzEyFEKfixizQPwBLhQ/s1600/photo2.JPG&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Also, the Q&#39; and R&#39; matrices (from the Cholesky transformation) above will have different constraints than the original Q and R matrices.&amp;nbsp; That I think makes this bottom formulation above impossible and takes me back to the top formulation.&lt;br /&gt;
&lt;br /&gt;
Reference&lt;br /&gt;
Here&#39;s a write up of ARMA models in state-space form, which seems to have nothing to do with the scratches above but my reformulation is motivated by thinking about (among other things) rewriting ARMA models in state-space form.&lt;br /&gt;
&lt;a href=&quot;http://www-stat.wharton.upenn.edu/~stine/stat910/lectures/14_state_space.pdf&quot;&gt;http://www-stat.wharton.upenn.edu/~stine/stat910/lectures/14_state_space.pdf&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;pre&gt;#12-20 notes
library(matlab)
# Test of some new ways to form the marss model to allow constraints across B and U
#harborSealWA is a n=5 matrix of logged population counts
dat = t(harborSealWA)
dat = dat[2:4,] #remove the year row
#fit a model with 1 hidden state and 3 observation time series
tic() #7.94 sec
kemfit = MARSS(dat, model=list(U=matrix(c(&quot;N&quot;,&quot;S&quot;,&quot;S&quot;),3,1)), control=list(allow.degen=FALSE))
toc()&amp;nbsp;&lt;/pre&gt;
&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre&gt;#reformat model to put U in B;&lt;/pre&gt;
&lt;pre&gt;a=summary(kemfit$model)
m=dim(a$B)[1]
Bt=cbind(rbind(a$B,matrix(0,1,m)),matrix(c(a$U,1),m+1,1)); #KFAS Tt
Zt=cbind(a$Z,a$A)
Qt=matrix(list(0),m+1,m+1); Qt[1:m,1:m]=a$Q; Qt[m+1,m+1]=0
x0t=rbind(a$x0,1)
V0t=matrix(list(0),m+1,m+1); V0t[1:m,1:m]=a$V0

newa = list(B=Bt, Z=Zt, U=&quot;zero&quot;, A=&quot;zero&quot;, Q=Qt, R=a$R, x0=x0t, V0=V0t, tinitx=a$tinitx)
#will get same value but need to run longer
tic() #9.76 sec
kemfita = MARSS(kemfit$model$data, model=newa, control=list(allow.degen=FALSE))
toc()
rbind(c(coef(kemfit,type=&quot;vector&quot;),kemfit$logLik),c(coef(kemfita,type=&quot;vector&quot;),kemfita$logLik))&amp;nbsp;&lt;/pre&gt;
&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre&gt;#This is an alternate approach that uses a y=1 row 9.78sec&lt;/pre&gt;
&lt;pre&gt;#and x is [x y]&#39; &lt;/pre&gt;
&lt;pre&gt;a=summary(kemfit$model)
tinitx=a$tinitx
m=dim(a$B)[1];n=dim(a$Z)[1]
Bt=matrix(list(0),n+m+1,n+m+1);Bt[1:m,1:m]=a$B;Bt[(m+1):(n+m),1:m]=a$Z; Bt[1:m,n+m+1]=a$U
Zt=matrix(list(0),n+1,m+n+1); Zt[,(m+1):(m+n+1)]=diag(1,n+1)
Qt=matrix(list(0),m+n+1,m+n+1); Qt[1:m,1:m]=a$Q; Qt[(m+1):(n+m),(m+1):(n+m)]=a$R;Qt[m+n+1,m+n+1]=1
x0t=rbind(a$x0,matrix(list(0),n+1,1)); x0t[n+m+1,1]=1;
V0t=matrix(list(0),n+m+1,n+m+1)
Ut=&quot;zero&quot;

newa = list(B=Bt, Z=Zt, U=Ut, A=&quot;zero&quot;, Q=Qt, R=&quot;zero&quot;, x0=x0t, V0=V0t, tinitx=tinitx)
inits.list=list(x0=matrix(1+kemfit$model$data[,1],m,1))
ddat=cbind(NA,kemfit$model$data); ddat=rbind(ddat,1)
tic()
kemfita = MARSS(ddat, model=newa, control=list(allow.degen=FALSE),inits=inits.list)
toc()
p1=coef(kemfit); p2=coef(kemfita)
rbind(c(p1$B,p1$Z,p1$U,p1$Q,p1$R,p1$x0,kemfit$logLik),c(p2$B,p2$U,p2$Q,p2$x0,kemfita$logLik))&lt;/pre&gt;
&lt;pre&gt;&amp;nbsp; &lt;/pre&gt;
&lt;pre&gt;#same reformat code can be run with this kemfit
#spp interaction example
royale.dat = log(t(isleRoyal[,2:3]))
z.royale.dat=(royale.dat-apply(royale.dat,1,mean,na.rm=TRUE))/
  sqrt(apply(royale.dat,1,var,na.rm=TRUE))
royale.model.1=list(Z=&quot;identity&quot;, B=&quot;unconstrained&quot;,
                    Q=&quot;diagonal and unequal&quot;, R=&quot;diagonal and unequal&quot;,
                    U=&quot;zero&quot;, tinitx=1)
cntl.list=list(allow.degen=FALSE,maxit=200)
tic()
kemfit=MARSS(z.royale.dat, model=royale.model.1, control=list(allow.degen=FALSE))
toc()&lt;/pre&gt;
&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;
&lt;br /&gt;
&amp;nbsp;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/2209905237294234757/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/2209905237294234757' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/2209905237294234757'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/2209905237294234757'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2014/01/more-general-formulation-of-marss-model.html' title='More general formulation of the MARSS model'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFhY6XKli1CGSgKiKI2O_w5sqqblQzpCfooxN1ie78zXzjx1FzirzM0bu6QeIu7pJRw3eRpLqqjMysLlbjuPbIEiXfPRqIRC9WhVYLi0uIbAueBwETON2x-BlVRBMW_0o2NVauMQ/s72-c/photo.JPG" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-8974515721605111948</id><published>2013-12-20T12:36:00.001-08:00</published><updated>2013-12-20T12:42:47.475-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="R"/><category scheme="http://www.blogger.com/atom/ns#" term="R packages"/><title type='text'>Quantifying R package downloads using the CRAN mirror stats</title><content type='html'>Because I have to justify all the time I spend working on the MARSS package, I collect stats for how much it is downloaded relative to other R packages.  To be honest, I think downloads stats are not really helpful to getting some recognition for the work---not that it hurts.  The only that thing that really counts are citations of the published paper on MARSS, and that relies on users citing the paper.  Even then the citations are not &#39;worth&#39; as much since the paper is in a software journal.  Fact is, one published paper in a high-impact paper cited 3 times is still &quot;worth&quot; a lot more than a R package downloaded hundreds times a day. Such is the research life.
&lt;/br&gt;&lt;/br&gt;
Here the R code to get package stats off the CRAN mirror.  See also this post by Felix Schonbrodt for a completely different way to get download stats: &lt;a href=&quot;http://www.nicebread.de/finally-tracking-cran-packages-downloads/&quot;&gt;http://www.nicebread.de/finally-tracking-cran-packages-downloads/&lt;/a&gt;
&lt;pre&gt;
require(XML)
require(RCurl)
require(httr)
require(stringr)

#read in table 13 which is the download stats table
a=readHTMLTable(&quot;http://cran.r-project.org/report_cran.html&quot;, which=13, stringsAsFactors=FALSE)
b=(as.numeric(a$reqs))
filename=a$file
#detect which filenames are .tar.gz files and which are .zip. (packages)
pkg=str_detect(filename,&quot;tar.gz&quot;) &amp; str_detect(filename, &quot;/src/contrib/&quot;)
pkg2=str_detect(filename,&quot;.zip&quot;) &amp; str_detect(filename, &quot;/bin/windows/contrib/r-release&quot;)
#detect which are documentation
docum=str_detect(filename,&quot;.pdf&quot;)

#make some plots
par(mfrow=c(3,1))
#get the pkgname---because I need to deal with multiple versions of packages and I only want to count 1 of those
pkgname=sapply(filename[pkg],function(x){ tmp=str_split(str_split(x,&quot;_&quot;)[[1]][1],&quot;/&quot;)[[1]]; tmp[length(tmp)] })
#go through and just get the pkg version that has the max downloads
pkgcount=c()
for(i in unique(pkgname)){
  pkgcount=c(pkgcount,max(b[pkg][pkgname==i]))
}
#figure out which filename is MARSS
marsspkg=str_detect(filename,&quot;tar.gz&quot;) &amp; str_detect(filename, &quot;/src/contrib/&quot;) &amp; str_detect(filename, &quot;MARSS&quot;)
#max(b[marsspkg]) means uses the count for whatever MARSS version is maximum to deal with multiple versions listed
titl=paste(&quot;Index of All R Source Package Downloads\ntop &quot;,format(100*sum(pkgcount&gt;max(b[marsspkg]))/length(pkgcount),digits=1),&quot;%&quot;,sep=&quot;&quot;)
hist(log(pkgcount),main=titl,xlab=&quot;log(downloads)&quot;)
abline(v=log(sum(b[marsspkg])),col=&quot;red&quot;)
text(log(max(b[marsspkg])),2000,&quot;MARSS&quot;,pos=4)

pkgname=sapply(filename[pkg2],function(x){ tmp=str_split(str_split(x,&quot;_&quot;)[[1]][1],&quot;/&quot;)[[1]]; tmp[length(tmp)] })
marsspkg2=str_detect(filename,&quot;.zip&quot;) &amp; str_detect(filename, &quot;/bin/windows/contrib/r-release&quot;) &amp; str_detect(filename, &quot;MARSS&quot;)
pkgcount=c()
for(i in unique(pkgname)){
  pkgcount=c(pkgcount,max(b[pkg2][pkgname==i]))
}
titl=paste(&quot;Index of All R Package Windows Binaries Downloads\ntop &quot;,format(100*sum(pkgcount&gt;max(b[marsspkg2]))/length(pkgcount),digits=1),&quot;%&quot;,sep=&quot;&quot;)
hist(log(pkgcount),main=titl,xlab=&quot;log(downloads)&quot;)
abline(v=log(sum(b[marsspkg2])),col=&quot;red&quot;)
text(log(max(b[marsspkg2])),1000,&quot;MARSS&quot;,pos=4)

titl=paste(&quot;Index of R Package Documentation Downloads\ntop &quot;,format(100*sum(b[docum]&gt;max(b[marssdocum]))/length(b[docum]),digits=1),&quot;%&quot;,sep=&quot;&quot;)
marssdocum=str_detect(filename,&quot;.pdf&quot;) &amp; str_detect(filename, &quot;MARSS&quot;)
hist(log(b[docum]),main=titl,xlab=&quot;log(downloads)&quot;)
abline(v=log(max(b[marssdocum])),col=&quot;red&quot;)
text(log(sum(b[marssdocum])),2000,&quot;MARSS&quot;,pos=4)

#dlm compared to marss
dlmpkg=str_detect(filename,&quot;tar.gz&quot;) &amp; str_detect(filename, &quot;/src/contrib/&quot;) &amp; str_detect(filename, &quot;/dlm_&quot;)
max(b[dlmpkg])
max(b[marsspkg]) #max to deal with different package versions and only use one
&lt;/pre&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/8974515721605111948/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/8974515721605111948' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8974515721605111948'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8974515721605111948'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/12/quantifying-r-package-downloads-using.html' title='Quantifying R package downloads using the CRAN mirror stats'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-4384495871460974392</id><published>2013-12-12T15:21:00.002-08:00</published><updated>2014-01-14T10:06:09.183-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="MARSS"/><category scheme="http://www.blogger.com/atom/ns#" term="unit testing"/><title type='text'>Automating testing of package version updates (MARSS specific)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
With a major update to MARSS in the works with the EM algorithm translated to C++, I realized I needed to bite the bullet and automate the testing of the package updates.&amp;nbsp; The main testing in the MARSS package occurs in the code in the extensive User Guide, but one of the tedious tasks for each version update has been making sure that I don&#39;t break anything with new updates and that any differences between output using different versions are expected (due to an intended change).&amp;nbsp;&amp;nbsp; I didn&#39;t want to duplicate effort put into the User Guide code by making special test code.&amp;nbsp; Instead I just wanted to rerun the code from different package versions and make sure everything matched.&amp;nbsp; I came up with a way to automate this by having different versions in different locations (in this case the base R library versus my local library).&amp;nbsp; This also has the side benefit of testing that the R code supplied with the package can be sourced (I discovered a number of problems this way).&lt;br /&gt;
&lt;br /&gt;
Here&#39;s the code and comments explain what it is doing.&amp;nbsp; Each User Guide chapter comes with a code file that allows users to replicate the chapter&#39;s examples.&amp;nbsp; The Sweave file for each chapter is written such with special labels for code chunks that are to appear in these R files and the makefile assembles these into the R files supplied with the package.&amp;nbsp; I&#39;ll have to change this a bit to facilitate using it as test code:&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Avoid not exporting code to the R file.&amp;nbsp; The code in the Sweave files is flagged with &quot;CS_&quot; if I want it to appear in the R files for the users.&amp;nbsp; I need to make sure I export all code that makes stuff in the chapters.&amp;nbsp; Otherwise I risk not testing some of the code in the User Guide.&amp;nbsp; Right now I pick-and-choose a bit and exports mostly examples.&lt;/li&gt;
&lt;li&gt;Avoid reusing object names.&amp;nbsp; I tend to use &quot;kem&quot; and &quot;kemfit&quot; over and over the chapter code.&amp;nbsp; If I do that there won&#39;t be a separate object created for each bit of code.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Use set.seed() to ensure that objects from random number generators are the same. &lt;/li&gt;
&lt;/ul&gt;
Here is the test code.&amp;nbsp; Basic idea is to load one MARSS version, run test code, save all objects as list.&amp;nbsp; Repeat for 2nd version.&amp;nbsp; Compare the lists from the two versions.&amp;nbsp; Report any differences.&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;/ul&gt;
&lt;pre&gt;# ###########################################
# This compares output from two different MARSS versions
# using the R code in the doc folder
# How to run
# Install one version of MARSS into the base R library
# Install a second version into the local R library
# Open the unit test.R file
# RShowDoc(&quot;versiontest.R&quot;, package=&quot;MARSS&quot;)
# Source the code.
# Note: Using &#39;build and reload&#39; from RStudio builds the package into the local
# library but does not install the doc or help files
# Use Install from zip and install from a .tar.gz file instead
# ###########################################

#make sure MARSS isn&#39;t loaded
try(detach(package:MARSS),silent=TRUE)

#New version should be in the local library
lib.loc = Sys.getenv(&quot;R_LIBS_USER&quot;)
unittestvrs=packageVersion(&quot;MARSS&quot;, lib.loc = lib.loc)
library(MARSS, lib.loc = lib.loc)

#Get whatever code files are in the doc directory; these are tested
unittestfiles = dir(path=paste(lib.loc,&quot;/MARSS/doc&quot;,sep=&quot;&quot;), pattern=&quot;*[.]R$&quot;, full.names = TRUE)

cat(&quot;Running code with MARSS version&quot;, as.character(unittestvrs), &quot;\n&quot;)
for(unittestfile in unittestfiles){
  #clean the workspace but keep objects needed for the unit test
  rm(list = ls()[!(ls()%in%c(&quot;unittestfile&quot;,&quot;unittestfiles&quot;,&quot;unittestvrs&quot;))])
  #set up name for log files
  tag=strsplit(unittestfile,&quot;/&quot;)[[1]]
  tag=tag[length(tag)]
  tag=strsplit(tag,&quot;[.]&quot;)[[1]][1]
  #run the code which will create objects
  cat(&quot;Running &quot;,unittestfile, &quot;\n&quot;)
  sink(paste(&quot;outputNew-&quot;,tag,&quot;.txt&quot;,sep=&quot;&quot;))
  #wrapped in try so it keeps going if the code has a problem
  #set the seed so any random nums are the same
  set.seed(10)
  try(source(unittestfile))
  sink()
  #make a list of objects created by the test code
  testNew = mget(ls()[!(ls()%in%c(&quot;unittestfile&quot;,&quot;unittestfiles&quot;,&quot;unittestvrs&quot;))])
  save(testNew,file=paste(tag,unittestvrs,&quot;.Rdata&quot;,sep=&quot;&quot;))
}
#detach the new version
detach(package:MARSS)

#Repeat for an older version of MARSS which is in the R library (no local library)
lib.loc = paste(Sys.getenv(&quot;R_HOME&quot;),&quot;/library&quot;,sep=&quot;&quot;)
unittestvrs=packageVersion(&quot;MARSS&quot;, lib.loc = lib.loc)
library(MARSS, lib.loc = lib.loc)
cat(&quot;\n\nRunning code with MARSS version&quot;, as.character(unittestvrs), &quot;\n&quot;)
for(unittestfile in unittestfiles){
  rm(list = ls()[!(ls()%in%c(&quot;unittestfile&quot;,&quot;unittestfiles&quot;,&quot;unittestvrs&quot;))])
  tag=strsplit(unittestfile,&quot;/&quot;)[[1]]
  tag=tag[length(tag)]
  tag=strsplit(tag,&quot;[.]&quot;)[[1]][1]
  cat(&quot;Running &quot;,unittestfile, &quot;\n&quot;)
  sink(paste(&quot;outputOld-&quot;,tag,&quot;.txt&quot;,sep=&quot;&quot;))
  set.seed(10)
  try(source(unittestfile))
  sink()
  testOld = mget(ls()[!(ls()%in%c(&quot;unittestfile&quot;,&quot;unittestfiles&quot;,&quot;unittestvrs&quot;))])
  save(testOld,file=paste(tag,unittestvrs,&quot;.Rdata&quot;,sep=&quot;&quot;))
}
detach(package:MARSS)

#Now start comparing the lists made using different versions of MARSS
cat(&quot;\n\nStarting object comparisons\n&quot;)
for(unittestfile in unittestfiles){
  #Get the file name
  tag=strsplit(unittestfile,&quot;/&quot;)[[1]]
  tag=tag[length(tag)]
  tag=strsplit(tag,&quot;[.]&quot;)[[1]][1]
  #Load in the 2 lists, testNew and testOld
  vrs=packageVersion(&quot;MARSS&quot;, lib.loc = Sys.getenv(&quot;R_LIBS_USER&quot;))
  load(file=paste(tag,vrs,&quot;.Rdata&quot;,sep=&quot;&quot;))
  lib.loc = paste(Sys.getenv(&quot;R_HOME&quot;),&quot;/library&quot;,sep=&quot;&quot;)
  vrs=packageVersion(&quot;MARSS&quot;, lib.loc = lib.loc)
  load(file=paste(tag,vrs,&quot;.Rdata&quot;,sep=&quot;&quot;))
  
  #Compare the lists and report any differences
  cat(&quot;Checking &quot;, tag, &quot;\n&quot;)
  if(!identical(names(testNew), names(testOld))){
    cat(&quot;ERROR: Names of the test lists not identical\n\n&quot;)
    next
  }
  good=rep(TRUE,length(names(testNew)))
  for(ii in 1:length(names(testNew))){
    if(!identical(testNew[[ii]], testOld[[ii]])) good[ii] = FALSE
  }
  if(!all(good)){
    cat(&quot;ERROR: The following objects are not identical\n&quot;)
    cat(names(testNew)[!good])
    cat(&quot;\n\n&quot;)
  }else{
    cat(&quot;PASSED\n\n&quot;)
  }
}
&lt;/pre&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/4384495871460974392/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/4384495871460974392' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/4384495871460974392'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/4384495871460974392'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/12/automating-testing-of-package-version.html' title='Automating testing of package version updates (MARSS specific)'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-1603187808387608637</id><published>2013-12-11T14:58:00.001-08:00</published><updated>2015-07-27T18:29:32.647-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Rcpp"/><category scheme="http://www.blogger.com/atom/ns#" term="RcppArmadillo"/><category scheme="http://www.blogger.com/atom/ns#" term="speed tests"/><title type='text'>More native R versus RcppArmadillo speed test comparisons for EM algorithm</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Following on my &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/12/speed-comparisons-using-native-r-and.html&quot;&gt;previous post&lt;/a&gt;, I continue to evaluate whether time spent writing C++ code for some of my EM algorithm in MARSS is time well-spent.&amp;nbsp; Today I wrote a small function for one of the update equations, the R update.&amp;nbsp; Below is a little function in R to do the biggest part of that update: &lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;test = function(Z, A, dR, kf, Ey){&lt;br /&gt;&amp;nbsp; sum1 = t.dR.dR = 0&lt;br /&gt;&amp;nbsp; TT = dim(kf[[&quot;xtT&quot;]])[2]&lt;br /&gt;&amp;nbsp; t.dR.dR = t.dR.dR + crossprod(dR)&lt;br /&gt;&amp;nbsp; for (i in 1:TT) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; hatyt = Ey[[&quot;ytT&quot;]][,i,drop=FALSE]; hatyxt=sub3D(Ey[[&quot;yxtT&quot;]],t=i); hatOt = sub3D(Ey[[&quot;OtT&quot;]],t=i)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; hatPt = kf[[&quot;VtT&quot;]][,,i]+tcrossprod(kf[[&quot;xtT&quot;]][,i,drop=FALSE])&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; hatxt = kf[[&quot;xtT&quot;]][,i,drop=FALSE]&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sum1a = (hatOt - tcrossprod(hatyxt, Z) - tcrossprod(Z, hatyxt)- tcrossprod(hatyt, A) - tcrossprod(A, hatyt) + tcrossprod(Z%*%hatPt, Z) + tcrossprod(Z%*%hatxt, A) + tcrossprod(A, Z%*%hatxt) + tcrossprod(A)) + A%*%t.A&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sum1 = sum1 + crossprod(dR, vec(sum1a))&lt;br /&gt;&amp;nbsp; }&amp;nbsp; &lt;br /&gt;&amp;nbsp; return(sum1)&lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
Z is a matrix, A a matrix, dR a 3D array, kf a list with a 3D array and 2D matrix I need, Ey is a list with 2 3D arrays and 1 2D matrix I need.&lt;br /&gt;
&lt;br /&gt;
Here&#39;s some RcppArmadillo (C++) to replicate the function above:&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;// [[Rcpp::depends(RcppArmadillo)]]&lt;br /&gt;&lt;br /&gt;#include &amp;lt;RcppArmadillo.h&amp;gt;&lt;br /&gt;&lt;br /&gt;using namespace arma;&lt;br /&gt;&lt;br /&gt;// [[Rcpp::export]]&lt;br /&gt;vec Rupdate2(mat Z, mat A, Rcpp::NumericVector vecdR, Rcpp::List&amp;amp; kf, Rcpp::List&amp;amp; Ey) {&lt;br /&gt;&amp;nbsp; Rcpp::NumericVector kfVtT = kf[&quot;VtT&quot;], EyyxtT = Ey[&quot;yxtT&quot;], EyOtT = Ey[&quot;OtT&quot;]; &lt;br /&gt;&amp;nbsp; mat ytT = Ey[&quot;ytT&quot;], xtT = kf[&quot;xtT&quot;];&lt;br /&gt;&amp;nbsp; vec dRDim = vecdR.attr(&quot;dim&quot;), VtTDim = kfVtT.attr(&quot;dim&quot;), yxtTDim = EyyxtT.attr(&quot;dim&quot;), OtTDim = EyOtT.attr(&quot;dim&quot;);&lt;br /&gt;&amp;nbsp; unsigned int TT = xtT.n_cols, m = xtT.n_rows, n = ytT.n_rows, p = dRDim[1];&lt;br /&gt;&amp;nbsp; cube VtT(kfVtT.begin(), VtTDim[0], VtTDim[1], VtTDim[2], false);&lt;br /&gt;&amp;nbsp; cube yxtT(EyyxtT.begin(), yxtTDim[0], yxtTDim[1], yxtTDim[2], false);&lt;br /&gt;&amp;nbsp; cube OtT(EyOtT.begin(), OtTDim[0], OtTDim[1], OtTDim[2], false);&lt;br /&gt;&amp;nbsp; cube cubedR(vecdR.begin(), dRDim[0], dRDim[1], dRDim[2], false);&lt;br /&gt;&amp;nbsp; vec hatyt(n), hatxt(m), sum1=zeros(p);&lt;br /&gt;&amp;nbsp; mat hatyxt(n,m), hatOt(n,n), hatPt(m,m), sum1a(n,n), dR=cubedR.slice(0);&lt;br /&gt;&amp;nbsp; for (unsigned int i = 0; i&amp;lt;TT; i++) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if(dRDim[2]&amp;gt;1) dR=cubedR.slice(i);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; hatyt=ytT.col(i); hatxt=xtT.col(i);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; hatOt=OtT.slice(i); hatyxt=yxtT.slice(i);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; hatPt=VtT.slice(i) + hatxt * hatxt.t();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sum1a = hatOt - hatyxt * Z.t() - Z * hatyxt.t()- hatyt * A.t() - A * hatyt.t() + Z * hatPt * Z.t() + (Z * hatxt) * A.t() + A * (hatxt.t() * Z.t()) + A*A.t();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sum1 = sum1 + dR.t() * vectorise(sum1a);&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp; return sum1;&lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
A few notes&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Rcpp::List&amp;amp; is to make it pass the list by reference instead of memory&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;cubedR(vecdR.begin(), dRDim[0], dRDim[1], dRDim[2], false) is the way to do the same thing when you need to construct a cube.&amp;nbsp; See comments by Rcpp developer on &lt;a href=&quot;http://stackoverflow.com/questions/18866130/passing-large-matrices-to-rcpparmadillo-function-without-creating-copy-advanced&quot;&gt;this SO post&lt;/a&gt;.&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
I tried it on a 15 x 20 matrix of data and 15 x 154 matrix and both time got about a 5 fold increase in speed:&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;-webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; background-color: #e1e2e5; border-collapse: separate; color: black; font-family: &#39;Lucida Console&#39;; font-size: 13px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15px; orphans: 2; text-align: -webkit-left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;-webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; background-color: #e1e2e5; border-collapse: separate; color: black; font-family: &#39;Lucida Console&#39;; font-size: 13px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15px; orphans: 2; text-align: -webkit-left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px;&quot;&gt;&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;2         1000    3.15    1.010
1         1000   16.42    5.263&lt;/pre&gt;
&lt;/span&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
So not orders of magnitude like I&#39;d hoped, but probably enough to speed up the EM part by 50% when all is said and done. &lt;/div&gt;
&lt;xmp&gt;
################################################
## Self-contained benchmark example for blog
################################################
require(utils)
require(Rcpp)
require(RcppArmadillo)
require(rbenchmark)
require(MARSS)

#these are internal functions to MARSS since, surprisingly, R doesn&#39;t have these
#in a 3D array say M[2,3,5] get the 2D matrix M[2,3,1] -&gt; sub3D(M, t=1)
sub3D=MARSS:::sub3D
# turn a 2D matrix into a column vector
vec=MARSS:::vec

test = function(Z, A, dR, kf, Ey){
  sum1 = t.dR.dR = 0
  TT = dim(kf[[&quot;xtT&quot;]])[2]
  t.dR.dR = t.dR.dR + crossprod(dR)
  for (i in 1:TT) {
    hatyt = Ey[[&quot;ytT&quot;]][,i,drop=FALSE]
    hatyxt= sub3D(Ey[[&quot;yxtT&quot;]],t=i)
    hatOt = sub3D(Ey[[&quot;OtT&quot;]],t=i)
    hatPt = kf[[&quot;VtT&quot;]][,,i]+tcrossprod(kf[[&quot;xtT&quot;]][,i,drop=FALSE])
    hatxt = kf[[&quot;xtT&quot;]][,i,drop=FALSE]
    sum1a = (hatOt - tcrossprod(hatyxt, Z) - tcrossprod(Z, hatyxt)- tcrossprod(hatyt, A) - tcrossprod(A, hatyt) + 
               tcrossprod(Z%*%hatPt, Z) + tcrossprod(Z%*%hatxt, A) + tcrossprod(A, Z%*%hatxt) + tcrossprod(A)) #A%*%t.A
    #sum1a = symm(sum1a) #enforce symmetry function from MARSSkf
    sum1 = sum1 + crossprod(dR, vec(sum1a))
  }  
  return(sum1)
}

#if this fun saved to file Rupdate.cpp, use sourceCpp(&quot;Rupdate.cpp&quot;)
sourceCpp(code=&#39;
// [[Rcpp::depends(RcppArmadillo)]]

#include &lt;RcppArmadillo.h&gt;

using namespace arma;

// [[Rcpp::export]]
vec Rupdate(mat&amp; Z, mat&amp; A, Rcpp::NumericVector vecdR, Rcpp::List&amp; kf, Rcpp::List&amp; Ey) {
  Rcpp::NumericVector kfVtT = kf[&quot;VtT&quot;], EyyxtT = Ey[&quot;yxtT&quot;], EyOtT = Ey[&quot;OtT&quot;]; 
  mat ytT = Ey[&quot;ytT&quot;], xtT = kf[&quot;xtT&quot;];
  vec dRDim = vecdR.attr(&quot;dim&quot;), VtTDim = kfVtT.attr(&quot;dim&quot;), yxtTDim = EyyxtT.attr(&quot;dim&quot;), OtTDim = EyOtT.attr(&quot;dim&quot;);
  unsigned int TT = xtT.n_cols, m = xtT.n_rows, n = ytT.n_rows, p = dRDim[1];
  cube VtT(kfVtT.begin(), VtTDim[0], VtTDim[1], VtTDim[2], false);
  cube yxtT(EyyxtT.begin(), yxtTDim[0], yxtTDim[1], yxtTDim[2], false);
  cube OtT(EyOtT.begin(), OtTDim[0], OtTDim[1], OtTDim[2], false);
  cube cubedR(vecdR.begin(), dRDim[0], dRDim[1], dRDim[2], false);
  vec hatyt(n), hatxt(m), sum1=zeros(p);
  mat hatyxt(n,m), hatOt(n,n), hatPt(m,m), sum1a(n,n), dR=cubedR.slice(0);
  for (unsigned int i = 0; i&lt;TT; i++) {
    if(dRDim[2]&gt;1) dR=cubedR.slice(i);
    hatyt=ytT.col(i); hatxt=xtT.col(i);
    hatOt=OtT.slice(i); hatyxt=yxtT.slice(i);
    hatPt=VtT.slice(i) + hatxt * hatxt.t();
    sum1a = hatOt - hatyxt * Z.t() - Z * hatyxt.t()- hatyt * A.t() - A * hatyt.t() + Z * hatPt * Z.t() + (Z * hatxt) * A.t() + A * (hatxt.t() * Z.t()) + A*A.t();
    sum1 = sum1 + dR.t() * vectorise(sum1a);
  }
  return sum1;
}&#39;
)

#test w 15 x t matrix of data
nr=15 #rows
for(t in c(20, 154)){
  dat = t(apply(matrix(rnorm(nr*t),nr,t),1,cumsum)) #create nr random walks
  fit = MARSS(dat, silent=TRUE)
  Ey = print(fit, what=&quot;Ey&quot;, silent=TRUE)
  kf = print(fit, what=&quot;kfs&quot;, silent=TRUE)
  model = coef(fit, type=&quot;matrix&quot;)
  dR=fit$model$free[[&quot;R&quot;]]
  Z=model$Z
  A=model$A
  
  res &lt;- benchmark(test(Z, A, dR, kf, Ey), Rupdate(Z, A, dR, kf, Ey), columns = c(&quot;test&quot;, &quot;replications&quot;,&quot;elapsed&quot;, &quot;relative&quot;),order=&quot;relative&quot;,replications=1000)
  cat(&quot;test with &quot;,nr,&quot;x&quot;,t,&quot; matrix\n&quot;)
  print(res[,1:4])
  cat(&quot;are the results the same? &quot;)
  cat(identical(unname(test(Z, A, dR, kf, Ey)), Rupdate(Z, A, dR, kf, Ey)))
  cat(&quot;\n&quot;)
}
&lt;/xmp&gt;</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/1603187808387608637/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/1603187808387608637' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/1603187808387608637'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/1603187808387608637'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/12/more-native-r-versus-rcpparmadillo.html' title='More native R versus RcppArmadillo speed test comparisons for EM algorithm'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-7573769117609617761</id><published>2013-12-10T22:58:00.002-08:00</published><updated>2013-12-11T15:09:47.144-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Rcpp"/><category scheme="http://www.blogger.com/atom/ns#" term="RcppArmadillo"/><category scheme="http://www.blogger.com/atom/ns#" term="speed tests"/><title type='text'>Speed comparisons using native R and RcppArmadillo</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div&gt;
I spent some time today learning the &lt;a href=&quot;http://cran.r-project.org/web/packages/RcppArmadillo/index.html&quot;&gt;RcppArmadillo&lt;/a&gt; package that allows you to run C++ code from the Armadillo linear algebra library. I developed my example (below) from the examples directory in the inst directory of RcppArmadillo, but I also learned a lot from other posts&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;a href=&quot;http://markovjumps.blogspot.com/2011/12/r-array-to-rcpparmadillo-cube.html&quot;&gt;http://markovjumps.blogspot.com/2011/12/r-array-to-rcpparmadillo-cube.html&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.stat.ubc.ca/~andy.leung/doc/seminar/RcppDemo.pdf&quot;&gt;http://www.stat.ubc.ca/~andy.leung/doc/seminar/RcppDemo.pdf&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://people.math.aau.dk/~sorenh/teaching/2012-ASC/day5aux/Rcpp-workshop.pdf&quot;&gt;http://people.math.aau.dk/~sorenh/teaching/2012-ASC/day5aux/Rcpp-workshop.pdf &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://markovjumps.blogspot.com/2013/10/passing-armadillo-matrices-by-value-and.html&quot;&gt;http://markovjumps.blogspot.com/2013/10/passing-armadillo-matrices-by-value-and.html&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://adv-r.had.co.nz/Rcpp.html&quot;&gt;http://adv-r.had.co.nz/Rcpp.html&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://faculty.washington.edu/heagerty/Courses/b572/public/rccp_demo.R&quot;&gt;http://faculty.washington.edu/heagerty/Courses/b572/public/rccp_demo.R&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
and the &lt;a href=&quot;http://arma.sourceforge.net/docs.html#Col&quot;&gt;actual documentation for Armadillo&lt;/a&gt;.&amp;nbsp; And I spent some time on &lt;a href=&quot;http://www.cplusplus.com/doc/tutorial/variables/&quot;&gt;this C++ tutorial&lt;/a&gt; since I don&#39;t actually know C++ (though eons ago I programmed in Fortran and C+ and C++ reminds me why I like matlab and R better).&amp;nbsp; I downloaded the source files for RcppArmadillo from CRAN and extracted the tar file to get example files for &quot;kalman&quot; which I edited for my purposes.&lt;br /&gt;
&lt;br /&gt;
The following code compares this computation in native R versus Armadillo C++&lt;br /&gt;
&lt;br /&gt;
Y=0&lt;br /&gt;
for(i in 1:nrows(A)) Y = Y+(A%*%B) %*% t(A[i])&lt;br /&gt;
&lt;br /&gt;
Here&#39;s the benchmark comparison and you can see that Armadillo C++ is considerably faster.&amp;nbsp; Note, I had to futz a bit to find a computation where C++ was much faster, but this particular computation is very similar to one I make in the EM step for the MARSS package.&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;-webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; background-color: #e1e2e5; border-collapse: separate; color: black; font-family: &#39;Lucida Console&#39;; font-size: 13px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15px; orphans: 2; text-align: -webkit-left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;                test replications elapsed relative
2 crossprodCpp(A, B)           10    0.14    1.000
1    crosstest(A, B)           10    9.50   67.857&lt;/pre&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;&amp;nbsp;&lt;/pre&gt;
Here is the code to run this particular example.  Just install the RcppArmadillo and benchmark R packages and you should be good to go.  You don&#39;t need to install Armadillo.  Just source the code below.  Unfortunately, MARSS stores things in arrays and it turns out that passing these to RcppArmadillo is tedious and my initial speed tests were not promising, but that&#39;s another post.&lt;br /&gt;
&lt;br /&gt;
Update: Turns out I picked a problem where Armadillo excels and used tcrossprod where it is not so efficient. If I&#39;d used&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Y = Y + A%*%(B%*%t(a))+B%*%t(a)&lt;br /&gt;
Rcpp is only 4x faster.&amp;nbsp; If I&#39;d used&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Y&amp;nbsp; = Y + tcrossprod(A%*%B,B) + tcrossprod(B,B)&lt;br /&gt;
or&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Y&amp;nbsp; = Y +A%*%B%*%B + B%*%B&lt;br /&gt;
Rcpp is no faster.&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
CODE ----------------------------------------------------
&lt;br /&gt;
src=&#39;&lt;br /&gt;
// [[Rcpp::depends(RcppArmadillo)]]&lt;br /&gt;
&lt;br /&gt;
#include &amp;lt;RcppArmadillo.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
using namespace arma;&lt;br /&gt;
&lt;br /&gt;
// [[Rcpp::export]]&lt;br /&gt;
mat crossprodCpp(mat A, mat B) {&lt;br /&gt;
&amp;nbsp; unsigned int n = A.n_cols;&lt;br /&gt;
&amp;nbsp; colvec a;&lt;br /&gt;
&amp;nbsp; mat Y = zeros(n, 1);&amp;nbsp; &lt;br /&gt;
&amp;nbsp; for (unsigned int i = 0; i&amp;lt;n; i++) {&lt;br /&gt;
&amp;nbsp; a = A.row(i).t();&lt;br /&gt;
&amp;nbsp; Y = Y + (A*B) * a + B * a;&amp;nbsp; &lt;br /&gt;
&amp;nbsp; }&lt;br /&gt;
&amp;nbsp; return Y;&lt;br /&gt;
}&#39;&lt;br /&gt;
&lt;br /&gt;
require(utils)&lt;br /&gt;
require(RcppArmadillo)&lt;br /&gt;
require(rbenchmark)&lt;br /&gt;
&lt;br /&gt;
sourceCpp(code=src)&lt;br /&gt;
&lt;br /&gt;
crosstest = function(A,B){&lt;br /&gt;
&amp;nbsp; Y = 0&lt;br /&gt;
&amp;nbsp; for(i in 1:dim(A)[1]){&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; a=A[i,,drop=FALSE]&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Y = Y + tcrossprod(A%*%B,a)+tcrossprod(B,a)&lt;br /&gt;
&amp;nbsp; }&lt;br /&gt;
&amp;nbsp; return(Y)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A=diag(200); B=diag(200)&lt;br /&gt;
&lt;br /&gt;
res &amp;lt;- benchmark(crosstest(A,B), crossprodCpp(A,B),&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; columns = c(&quot;test&quot;, &quot;replications&quot;,&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;elapsed&quot;, &quot;relative&quot;),&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; order=&quot;relative&quot;,&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; replications=10)&lt;br /&gt;
&lt;br /&gt;
print(res[,1:4])&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/7573769117609617761/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/7573769117609617761' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/7573769117609617761'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/7573769117609617761'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/12/speed-comparisons-using-native-r-and.html' title='Speed comparisons using native R and RcppArmadillo'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-5304052007155758064</id><published>2013-11-26T14:48:00.001-08:00</published><updated>2013-11-26T14:48:14.785-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="big data"/><category scheme="http://www.blogger.com/atom/ns#" term="speed tests"/><title type='text'>Speeding up R (MARSS specific)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Some notes on MARSS 3.6 update.&lt;br /&gt;
&lt;br /&gt;
MARSS is generally slow since it is in native R but is slower than needed since it is doing a lot of matrix manipulations.&amp;nbsp; I got a 10-20 increase in speed for large matrix (10,000 rows, 100s cols) problems (which arise when say n=120 and 120 r&#39;s are being estimated) by the following in order of how much it helped&lt;br /&gt;
&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Replace all instances of t(A)%*%B and A%*%t(B) with crossprod(A,B) and tcrosprod(A,B), respectively.&lt;/li&gt;
&lt;li&gt;vectorize the one case where I was using for(i in 1:nrow){ for(j in 1:ncol) {} } to do something to each element of matrix, element by element.&amp;nbsp; This only was done once, but ground the code to a halt for big matrices.&lt;/li&gt;
&lt;li&gt;Used R profiling to find that a slow diagonal matrix test was slowing my Kalman filter function.&amp;nbsp; Replaced that with a fast test.&lt;/li&gt;
&lt;li&gt;Found all cases where I was subsetting arrays, like A[,,i], and replaced with code like this if(dim(A)[3]==1) dim(A)=dim(A)[1:2].&amp;nbsp; This torched the dimnames, so I needed to be careful to rest those if needed.&lt;/li&gt;
&lt;li&gt;Made sure I was not recreating matrices unnecessarily.&amp;nbsp; The diagonal matrices created for degenerate R and Q were getting created over and over.&amp;nbsp; Made a flag so that they are created only once and only updated if new 0s appear.&lt;/li&gt;
&lt;/ul&gt;
Things I tried that didn&#39;t help&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;using the Matrix package and sparse matrices, but that only helped when n was really big and hurt when n was small. &lt;/li&gt;
&lt;li&gt;vectorize the for loop over time using block diagonal matrices and the Matrix package.&amp;nbsp; See previous blog post on that test.&amp;nbsp; I was really bummed that didn&#39;t speed things up dramatically.&lt;/li&gt;
&lt;/ul&gt;
To do:&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Bust out the degen code into a bit with if(allow.degen==TRUE).&lt;/li&gt;
&lt;li&gt;Clean up the set-up and testing code for marssMODELs&lt;/li&gt;
&lt;li&gt;Maybe do.&amp;nbsp; If there are no zeros on the diagonals in A, then the solve(A)%*%b call can be sped up with solve(A,b).&amp;nbsp; If I isolate the degen code, then I could us that.&amp;nbsp; Right now I need to do a robust inverse that deals with 0s on the diagonal and structures that prevent solve() from working.&amp;nbsp; I bet I cannot use this though because the problem is not just 0s on the diagonal.&lt;/li&gt;
&lt;/ul&gt;
References&lt;br /&gt;
Faster R notes:&amp;nbsp; &lt;a href=&quot;http://pj.freefaculty.org/blog/?p=122&quot;&gt;http://pj.freefaculty.org/blog/?p=122 &lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
Some speed testing and profiling code&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;require(MARSS)&lt;br /&gt;plankdat=lakeWAplanktonTrans&lt;br /&gt;plankdat=plankdat[plankdat[,&quot;Year&quot;]&amp;gt;=1980 &amp;amp; plankdat[,&quot;Year&quot;]&amp;lt;1990,]&lt;br /&gt;# create vector of phytoplankton group names&lt;br /&gt;phytoplankton = c(&quot;Cryptomonus&quot;, &quot;Diatoms&quot;, &quot;Greens&quot;,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;Bluegreens&quot;, &quot;Unicells&quot;, &quot;Other.algae&quot;)&lt;br /&gt;# get only the phytoplankton&lt;br /&gt;dat.spp.1980 = as.matrix(plankdat[,phytoplankton])&lt;br /&gt;dat.spp.1980 = t(dat.spp.1980)&lt;br /&gt;&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;cntl.list = list(maxit=50)&lt;br /&gt;model.list = list(m=2, R=&quot;diagonal and equal&quot;)&lt;br /&gt;model.list = list(m=2, R=&quot;diagonal and unequal&quot;)&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#quick speed testing using matlab&lt;br /&gt;require(matlab)&lt;br /&gt;n=10&lt;br /&gt;a=c()&lt;br /&gt;for(i in 1:n) a=rbind(a,dat.spp.1980)&lt;br /&gt;a=a+matrix(rnorm(length(a),0,.1),dim(a)[1],dim(a)[2])&lt;br /&gt;R=matrix(list(0),dim(a)[1],dim(a)[1])&lt;br /&gt;diag(R)=as.character(1:dim(a)[1])&lt;br /&gt;model.list = list(m=2, R=R)&lt;br /&gt;tic()&lt;br /&gt;kemz.2 = MARSS(a, model=model.list, z.score=TRUE, form=&quot;dfa&quot;, control=cntl.list)&lt;br /&gt;toc()&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#R profiling&lt;br /&gt;Rprof(tmp&amp;lt;-tempfile())&lt;br /&gt;kemz.2 = MARSS(dat.spp.1980, model=model.list, z.score=TRUE, form=&quot;dfa&quot;, control=list(maxit=50))&lt;br /&gt;Rprof()&lt;br /&gt;summaryRprof(tmp)&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#system.time&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;system.time(MARSS(dat.spp.1980, model=model.list, z.score=TRUE, form=&quot;dfa&quot;, control=list(maxit=50)))&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/5304052007155758064/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/5304052007155758064' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/5304052007155758064'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/5304052007155758064'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/11/speeding-up-r-marss-specific.html' title='Speeding up R (MARSS specific)'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-7691664484700736957</id><published>2013-11-25T14:38:00.000-08:00</published><updated>2014-01-14T10:08:22.512-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="big data"/><category scheme="http://www.blogger.com/atom/ns#" term="R"/><category scheme="http://www.blogger.com/atom/ns#" term="sparse matrices"/><title type='text'>Speed test using Matrix to do block summation</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
I&#39;ve spent the last week &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/11/speeding-up-r-marss-specific.html&quot;&gt;speeding up the MARSS package by getting rid of some expensive matrix manipulations&lt;/a&gt;.&amp;nbsp; It turns out that subscripting a large matrix and taking the transpose is really slow in R.&amp;nbsp; Some of my design matrices have 100s of thousands of rows, so that was getting slow.&lt;br /&gt;
&lt;br /&gt;
In the process, I&#39;ve been thinking about how to speed up the EM algorithm by getting rid of the &quot;for&quot; loops over time.&amp;nbsp;&amp;nbsp; One idea is to use the Matrix package and use block diagonal matrices instead of arrays to hold the time-varying matrices coming out of the Kalman filter.&amp;nbsp; Preliminary speed test was not promising however.&amp;nbsp; It was slow to use matrix multiplication to do a simultaneous summation.&amp;nbsp; Speed tests are below.&amp;nbsp; Doing the summation with matrix multiplication took consistently about twice the time.&lt;br /&gt;
&lt;br /&gt;
Idea is to replace the for loop over 3rd dim (time) of array:&lt;br /&gt;
for(i in 1:TT) sum1=sum1+a[,,i]%*%b[,,i]&lt;br /&gt;
&lt;br /&gt;
with this&lt;br /&gt;
sum1 = II.row %*% a.blockdiag %*% b.blockdiag %*% II.col&lt;br /&gt;
where a.blockdiag is a block diagonal with each a[,,i] a block down the diagonal, b.blockdiag is similar, II.row is a row of TT identity matrices and II.col is a col of TT identity matrices.&lt;br /&gt;
&lt;br /&gt;
Here&#39;s some speed test code&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;require(Matrix)&lt;br /&gt;TT=100; n=20&lt;br /&gt;a=array(1:(n*n),dim=c(n,n,TT))&lt;br /&gt;xtT=matrix(1:n,n,TT)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#set up the II.row and II.col&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;II.row = II.col = Diagonal(n)&lt;br /&gt;for(i in 1:(TT-1)) II.row = cBind(II.row,Diagonal(n))&lt;br /&gt;for(i in 1:(TT-1)) II.col = rBind(II.col,Diagonal(n))&lt;br /&gt;I.row=Matrix(1,1,TT)&lt;br /&gt;I.col=Matrix(1,TT,1)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;br /&gt;#set up the block diag matrices; Matrix wants a list of matrices for bdiag()&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;for(i in 1:TT) b[[i]]=a[,,i]&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;b=list()&lt;br /&gt;d=bdiag(b)&lt;br /&gt;for(i in 1:TT) b[[i]]=xtT[,i,drop=FALSE]&lt;br /&gt;e=bdiag(b)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;br /&gt;#speed test&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;require(matlab)&lt;br /&gt;tic()&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;for(j in 1:100) &lt;br /&gt;sum2=II.row%*%d%*%e%*%I.col&lt;br /&gt;toc()&lt;br /&gt;&lt;br /&gt;tic()&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;for(j in 1:100){&lt;br /&gt;sum1=0; for(i in 1:TT) sum1=sum1+a[,,i]%*%xtT[,i]&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;}&lt;br /&gt;toc()&lt;br /&gt;&lt;br /&gt;tic()&lt;br /&gt;for(j in 1:100){&lt;br /&gt;sum2=I.row%*%crossprod(e,d)%*%II.col&lt;br /&gt;}&lt;br /&gt;toc()&lt;br /&gt;&lt;br /&gt;tic()&lt;br /&gt;for(j in 1:100){&lt;br /&gt;sum1=0; for(i in 1:TT) sum1=sum1+crossprod(xtT[,i,drop=FALSE],a[,,i])&lt;br /&gt;}&lt;br /&gt;toc()&lt;/span&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/7691664484700736957/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/7691664484700736957' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/7691664484700736957'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/7691664484700736957'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/11/speed-test-using-matrix-to-do-block.html' title='Speed test using Matrix to do block summation'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-9100562232349324776</id><published>2013-11-05T17:45:00.002-08:00</published><updated>2013-11-05T17:45:52.697-08:00</updated><title type='text'>Fitting big state-space models with glmnet?</title><content type='html'>Brian Dennis once showed me an algorithm for fitting state-space models using a big matrix of all the data.  I viewed the approach as unworkable for anything but small data sets.  Maybe glmnet could be used?
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/9100562232349324776/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/9100562232349324776' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/9100562232349324776'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/9100562232349324776'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/11/fitting-big-state-space-models-with.html' title='Fitting big state-space models with glmnet?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-501334696773912125</id><published>2013-10-11T14:01:00.003-07:00</published><updated>2014-01-14T10:10:53.727-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="fbRanks"/><category scheme="http://www.blogger.com/atom/ns#" term="glmnet"/><title type='text'>Dixon and Coles tests repeated with glmnet(..., lambda=0)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
I repeated the tests from &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/dixon-and-coles-2-player-model-with.html&quot;&gt;my previous post&lt;/a&gt; using glmnet(..., lambda=0).&amp;nbsp; Given how well this worked with real soccer data, I was surprised that it would not work with &#39;better&#39; simulated data.&amp;nbsp; Maybe I do need to constrain the model?&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;Update: I figured out that this is a problem with family=&quot;poisson&quot; when mu is
 pathologically huge (like 1e365).&amp;nbsp; Works fine on more realistic mu.&amp;nbsp; I 
tested on various soccer fits with speedglm() versus glmnet() and they 
gave the same estimates.&amp;nbsp; I recoded rank.teams() in fbRanks to allow use
 of glmnet.&amp;nbsp;&lt;/i&gt; &lt;br /&gt;
&lt;br /&gt;
In all tests, the network of games played (who plays who) is real.&amp;nbsp; See previous post for a description of the tests.&lt;br /&gt;
Test 1: attack and defense strength for teams are drawn i.i.d.&amp;nbsp; NON-CONVERGENCE&lt;br /&gt;
Test 2: attack and defense strength drawn with same mean and variance but age groups do not have different means.&amp;nbsp; NON-CONVERGENCE&lt;br /&gt;
Test 3: attack and defense strengths set from estimated values from speedglm using real data.&amp;nbsp; glmnet works well and seems a little better than speedglm.&lt;br /&gt;
&lt;br /&gt;
What is up with test 1 and test 2?&amp;nbsp;&amp;nbsp; Works fine if I don&#39;t pass in lambda=0, while test 3 works fine if I do.&amp;nbsp;&amp;nbsp; Maybe too many 0s if I draw strengths randomly?&amp;nbsp; Variance within age groups is maybe less than 1 or 2 (real data)?&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/501334696773912125/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/501334696773912125' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/501334696773912125'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/501334696773912125'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/dixon-and-coles-tests-repeated-with.html' title='Dixon and Coles tests repeated with glmnet(..., lambda=0)'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-3597286016458844525</id><published>2013-10-11T14:00:00.000-07:00</published><updated>2013-10-17T12:42:58.784-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="big data"/><category scheme="http://www.blogger.com/atom/ns#" term="glm-speedglm-glmnet comparison"/><category scheme="http://www.blogger.com/atom/ns#" term="glmnet"/><title type='text'>Follow-up on the glmnet problems I had for fitting poisson models</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;After emailing the maintainer of glmnet, I figured out what was going on with glmnet.&amp;nbsp; It is not a bug with intercept estimation as I had thought, but rather that when mu (that generated the poisson counts) gets very large, as in 1e+13 large, the glmnet algorithm likelihood surface (or whatever surface it is maximizing) gets very, very, very flat.&amp;nbsp; So it shows convergence at the default thresh of 1e-7 long before it is near the correct maximum. &amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;Here is simulated data:&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;N=1000; p=50&lt;br /&gt;nzc=p&lt;br /&gt;x=matrix(rnorm(N*p),N,p)&lt;br /&gt;beta=rnorm(nzc)&lt;br /&gt;f = x[,seq(nzc)]%*%beta&lt;br /&gt;mu=exp(f)&lt;br /&gt;y=rpois(N,mu)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#intercept should be 0; it&#39;s not anywhere close&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;fit=glmnet(x,y,family=&quot;poisson&quot;)&lt;br /&gt;coef(fit)[1,]&lt;br /&gt;fit2=glm(y~x,family=&quot;poisson&quot;)&lt;br /&gt;coef(fit2)[1]&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;So there are 2 problems&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;1) I should have used exact=TRUE in my coef() call&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;cor(coef(fit2),as.numeric(coef(fit,s=0)))&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;[1] 0.4459366&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;cor(coef(fit2),as.numeric(coef(fit,s=0,exact=TRUE)))&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;[1] 0.8289489&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
2) I should have set thresh much lower&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;fit=glmnet(x,y,family=&quot;poisson&quot;,thresh=1e-10)&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;cor(coef(fit2),as.numeric(coef(fit,s=0,exact=TRUE)))&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;[1] 0.9995521
&lt;/span&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;Nonetheless, this still doesn&#39;t work&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;fit=glmnet(x,y,family=&quot;poisson&quot;,thresh=1e-10,intercept=FALSE)&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;Warning message:
from glmnet Fortran code (error code -2); Convergence for 2th lambda value not reached after maxit=100000 iterations; solutions for larger lambdas returned&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;Maybe it would converge if I set maxit much higher, but glm doesn&#39;t have trouble:&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;fit2=glm(y~-1+x,family=&quot;poisson&quot;)&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;At this point, I decided to upgrade R from 2.15.3 to 3.0.2 After the upgrade, my glmnet() call threw a y&amp;lt;0 error about a 1/4 of the time even though y was not &amp;lt; 0 ever.&amp;nbsp; Here&#39;s the email I sent to the maintainer that sorted out all the oddness:&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;-------------------------------&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;br /&gt;
&lt;div&gt;
Hi,&lt;br /&gt;
&lt;br /&gt;
Thanks for the response and edited code. &amp;nbsp;I had tried 
standardize=FALSE and setting thresh=1e-10 before writing, but I had 
still been getting the result so thought that the slow convergence was 
being caused by an intercept estimation issue.&amp;nbsp; Here&#39;s an example with 
some sample output that shows what I was seeing every so often:&lt;br /&gt;
&lt;div class=&quot;im&quot;&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;N=1000; p=50; nzc=p&lt;br /&gt;x=matrix(rnorm(N*p),N,p)&lt;br /&gt;beta=rnorm(nzc)&lt;br /&gt;f = x[,seq(nzc)]%*%beta &amp;nbsp;#intercept is 0&lt;br /&gt;mu=exp(f)&lt;br /&gt;y=rpois(N,mu)&lt;/span&gt;&lt;/div&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;fit=glmnet(x,y,family=&quot;&lt;/span&gt;&lt;wbr&gt;&lt;/wbr&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;poisson&quot;,standardize=FALSE,&lt;/span&gt;&lt;wbr&gt;&lt;/wbr&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;thresh=1e-10,maxit=1e7)&lt;br /&gt;
coef(fit,s=0,exact=TRUE)[1] &amp;nbsp;&lt;b&gt;#big intercept&lt;/b&gt;&lt;br /&gt;[1] 8.289213&lt;br /&gt;cor(coef(fit2),as.numeric(&lt;/span&gt;&lt;wbr&gt;&lt;/wbr&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;coef(fit,s=0,exact=TRUE))) &lt;b&gt;#low correlation with glm()&lt;/b&gt;&lt;br /&gt;[1] 0.4740912&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The reason I thought it was an intercept issue was that I had gotten this error for what seemed an easy problem.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;fit=glmnet(x,y,family=&quot;&lt;/span&gt;&lt;wbr&gt;&lt;/wbr&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;poisson&quot;,&lt;b&gt;intercept=FALSE&lt;/b&gt;)&lt;br /&gt;Warning message:&lt;br /&gt;from
 glmnet Fortran code (error code -2); Convergence for 2th lambda value 
not reached after maxit=100000 iterations; solutions for larger lambdas 
returned &lt;br /&gt;
&lt;/span&gt;&lt;br /&gt;
while this had no trouble&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;fit2=glm(y~-1+x,family=&quot;&lt;/span&gt;&lt;wbr&gt;&lt;/wbr&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;poisson&quot;)&lt;/span&gt;&lt;br /&gt;
I
 thought it odd that glmnet() had trouble on what seemed a relatively 
simple problem and I had never observed glmnet to not converge when glm 
did. I&#39;ve been using glmnet for awhile and had never seen it have 
trouble with a model that glm solved easily.&amp;nbsp; I thought it had 
something to do with a problem with setting intercept=FALSE and that led
 to the query and code I originally sent you.&lt;br /&gt;
&lt;br /&gt;
However, after 
writing you I updated from R 2.15.3 to R 3.0.2.&amp;nbsp; And then glmnet 
starting returning an error that y&amp;lt;0 a quarter of the time with my 
sample code.&amp;nbsp; I tracked this down to a change in the rpois() behavior in
 3.0.2 :&lt;br /&gt;
&lt;br /&gt;
R 2.15.2 and 2.15.3&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;rpois(1,1e10)&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&amp;nbsp;[1] 10000025096 (e.g.)&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;
R 3.02&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;rpois(1,1e10)&lt;br /&gt;[1] NA&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
When
 those NA appeared, glmnet reported some y&amp;lt;0 and thus returned an 
error.&amp;nbsp;&amp;nbsp; At that point, I realized that the example code was producing 
mu&#39;s that were exceedingly large. &amp;nbsp;And when mu was very large, 
that&#39;s when I was seeing the low correlation. &amp;nbsp;For example, for the 
example shown above max(mu) was 4.831217e+12&amp;nbsp; .&amp;nbsp; After reading your 
email, I see that even though thresh=1e-10, with this big of mu, the 
glmnet() algorithm was not near the maximum and was approaching the 
maximum very, very slowly so thresh would need to be even smaller than 
1e-10.&lt;/div&gt;
&lt;div&gt;
But if I change the code so that mu is more reasonable, then glmnet() has no convergence issues:&lt;/div&gt;
&lt;div&gt;
#draw x from normal with smaller variance&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;N=1000; p=50; nzc=p&lt;br /&gt;x=matrix(rnorm(N*p,0,&lt;span style=&quot;background-color: red;&quot;&gt;&lt;b&gt;0.1&lt;/b&gt;&lt;/span&gt;),N,p)&lt;/span&gt;&lt;br /&gt;
&lt;div class=&quot;im&quot;&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;br /&gt;
beta=rnorm(nzc)&lt;br /&gt;f = x[,seq(nzc)]%*%beta &amp;nbsp;#intercept is 0&lt;br /&gt;mu=exp(f)&lt;br /&gt;y=rpois(N,mu)&lt;/span&gt;&lt;/div&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;fit=glmnet(x,y,family=&quot;&lt;/span&gt;&lt;wbr&gt;&lt;/wbr&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;poisson&quot;,standardize=FALSE)&lt;br /&gt;fit2=glm(y~x,family=&quot;poisson&quot;)&lt;br /&gt;cor(coef(fit2),as.numeric(&lt;/span&gt;&lt;wbr&gt;&lt;/wbr&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;coef(fit,s=0,exact=TRUE)))&lt;br /&gt;
[1] 1&lt;/span&gt;&lt;br /&gt;
Now this works fine too&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;fit=glmnet(x,y,family=&quot;&lt;/span&gt;&lt;wbr&gt;&lt;/wbr&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;poisson&quot;,intercept=FALSE)&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
So, no bug just interesting (different) behavior for glm vs glmnet for really large mu.&lt;/div&gt;
&lt;div&gt;
Regards,&lt;br /&gt;
&lt;br /&gt;
Eli&lt;br /&gt;
&lt;br /&gt;
-----------------------------------------------------------&lt;br /&gt;
&lt;br /&gt;
And now this code works fine&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;N=1000; p=50&lt;br /&gt;nzc=p&lt;br /&gt;x=matrix(rnorm(N*p,0,0.1),N,p)&lt;br /&gt;beta=rnorm(nzc)&lt;br /&gt;f = x[,seq(nzc)]%*%beta&amp;nbsp; #intercept is 0&lt;br /&gt;mu=exp(f)&lt;br /&gt;y=rpois(N,mu)&lt;br /&gt;fit=glmnet(x,y,family=&quot;poisson&quot;,intercept=FALSE,lambda=0)&lt;br /&gt;fit2=glm(y~-1+x,family=&quot;poisson&quot;)&lt;br /&gt;cor(coef(fit2),as.numeric(coef(fit)[-1]))&lt;br /&gt;[1] 1&lt;/span&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/3597286016458844525/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/3597286016458844525' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3597286016458844525'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3597286016458844525'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/follow-up-on-glmnet-problems-i-had-for.html' title='Follow-up on the glmnet problems I had for fitting poisson models'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-8171034479117086855</id><published>2013-10-11T13:53:00.000-07:00</published><updated>2013-10-17T13:07:50.469-07:00</updated><title type='text'>glm, speedglm, glmnet comparison (part 1 repeated with lambda=0)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
glmnet does OLS when you set alpha=1 and lambda=0, so should return the same values as glm.&amp;nbsp; I repeated the part 1 tests with lambda=0.&amp;nbsp; Works fine for family=&quot;gaussian&quot;.&amp;nbsp; Crashes for family=&quot;poisson&quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;Update: what&#39;s going on is I inadvertently created mu&#39;s for the poisson that are huge.&amp;nbsp; max(y) = 1e8 to 1e10 .&amp;nbsp; When facs = 20 enough draws, every so often sum(betas) &amp;gt; 17 or so.&amp;nbsp; And then exp(betas) = HUGE.&amp;nbsp; That is where the problem is.&amp;nbsp; When I used more smaller betas, so that sum(betas) never greater than 10 (say), the convergence problem disappears.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Test is a model with facs factors and levs levels.&amp;nbsp; betas drawn from normal(0,1). &amp;nbsp; I took care in this test to set the first level of each factor to 0, same as glm does, and estimated the intercept.&lt;br /&gt;
&lt;br /&gt;
with family gaussian all is fine&lt;br /&gt;
&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;-webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; background-color: #e1e2e5; border-collapse: separate; color: black; font-family: &#39;Lucida Console&#39;; font-size: 13px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15px; orphans: 2; text-align: -webkit-left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;-webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; background-color: #e1e2e5; border-collapse: separate; color: black; font-family: &#39;Lucida Console&#39;; font-size: 13px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15px; orphans: 2; text-align: -webkit-left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px;&quot;&gt;  facs   glm speedglm glmnet
a    5  0.09     0.03   0.02
a   10  0.20     0.06   0.05
a   20  0.67     0.22   0.15
a   50  3.67     1.27   0.09
a  100 14.24     1.67   0.17&lt;/span&gt;&lt;/pre&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;-webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; background-color: #e1e2e5; border-collapse: separate; color: black; font-family: &#39;Lucida Console&#39;; font-size: 13px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15px; orphans: 2; text-align: -webkit-left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px;&quot;&gt;
&lt;/span&gt; &lt;br /&gt;
with family poisson it doesn&#39;t work&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;-webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; background-color: #e1e2e5; border-collapse: separate; color: black; font-family: &#39;Lucida Console&#39;; font-size: 13px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15px; orphans: 2; text-align: -webkit-left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;&lt;span class=&quot;GNVMTOMCLAB  ace_constant&quot; style=&quot;color: #c5060b;&quot;&gt;Warning messages:
&lt;/span&gt;&lt;span class=&quot;GNVMTOMCLAB  ace_constant&quot; style=&quot;color: #c5060b;&quot;&gt;1: from glmnet Fortran code (error code -1); Convergence for 1th lambda value not reached after maxit=100000 iterations; solutions for larger lambdas returned 
&lt;/span&gt;&lt;span class=&quot;GNVMTOMCLAB  ace_constant&quot; style=&quot;color: #c5060b;&quot;&gt;2: In getcoef(fit, nvars, nx, vnames) :
  an empty model has been returned; probably a convergence issue&lt;/span&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
timings&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;-webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; background-color: #e1e2e5; border-collapse: separate; color: black; font-family: &#39;Lucida Console&#39;; font-size: 13px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15px; orphans: 2; text-align: -webkit-left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;           glm  speedglm    glmnet
a  5      0.22      0.11      0.05
a 10      0.44      0.22      0.52
a 20      1.33      0.75     86.09&lt;/pre&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;&amp;nbsp;&lt;/pre&gt;
&lt;br /&gt;
R code&lt;br /&gt;
library(glmnet)&lt;br /&gt;
library(speedglm)&lt;br /&gt;
&lt;br /&gt;
n = 10000&lt;br /&gt;
levs = 10&lt;br /&gt;
&lt;br /&gt;
res=obj=c()&lt;br /&gt;
for(facs in c(5,10,20)){&lt;br /&gt;
&amp;nbsp; beta=matrix(rnorm(levs*facs,0,1),levs,facs)&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; levx = c()&lt;br /&gt;
&amp;nbsp; for(i in 1:facs) levx=cbind(levx,sample(levs,n,replace=TRUE))&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; y &amp;lt;- apply(levx, 1, function(x){ rpois(1,exp(sum(beta[x+seq(0,levs*(facs-1),by=levs)]))) })&lt;br /&gt;
&amp;nbsp; x = data.frame(levx)&lt;br /&gt;
&amp;nbsp; for(i in 1:facs) x[,i]=factor(x[,i],levels=1:levs)&lt;br /&gt;
&amp;nbsp; dat = cbind(y=y,x)&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; cat(facs);cat(&quot;\n&quot;)&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; #set up the formula&lt;br /&gt;
&amp;nbsp; fooform = &quot;y~1&quot;&lt;br /&gt;
&amp;nbsp; for(i in 1:facs) fooform=paste(fooform,&quot;+X&quot;,i,sep=&quot;&quot;)&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; #fit glm&lt;br /&gt;
&amp;nbsp; #don&#39;t do glm if facs&amp;gt;500; too slow&lt;br /&gt;
&amp;nbsp; if(facs&amp;lt;500){&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; a=c(facs, system.time(fit&amp;lt;-glm(formula(fooform), data=dat, family=&quot;poisson&quot;))[1])&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; b=c(facs, object.size(fit))&lt;br /&gt;
&amp;nbsp; }else{&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; a=c(facs, NA)&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; b=c(facs, NA)&lt;br /&gt;
&amp;nbsp; }&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; #fit speedglm&lt;br /&gt;
&amp;nbsp; a=c(a,system.time(fit2&amp;lt;-speedglm(as.formula(fooform), data=dat, family=poisson(log)))[1])&lt;br /&gt;
&amp;nbsp; b=c(b, object.size(fit))&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; #fit glmnet&lt;br /&gt;
&amp;nbsp; sx.j = as.vector(levx+matrix(seq(0,levs*(facs-1),by=levs),n,facs,byrow=TRUE))&lt;br /&gt;
&amp;nbsp; sx.i = rep(1:n,facs)&lt;br /&gt;
&amp;nbsp; #remove the 1st level of each factor; do sx.i first because test depends on sx.j&lt;br /&gt;
&amp;nbsp; sx.i = sx.i[!(sx.j %in% seq(1,levs*facs,by=levs))]&lt;br /&gt;
&amp;nbsp; sx.j = sx.j[!(sx.j %in% seq(1,levs*facs,by=levs))]&lt;br /&gt;
&amp;nbsp; sx=sparseMatrix(sx.i,sx.j,&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x=1,dims=c(n,levs*facs))&lt;br /&gt;
&amp;nbsp; a=c(a, system.time(fit&amp;lt;-glmnet(sx, y, lambda=0, family=&quot;poisson&quot;))[1])&lt;br /&gt;
&amp;nbsp; b=c(b, object.size(fit))&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; res=rbind(res,a)&lt;br /&gt;
&amp;nbsp; obj=rbind(obj,b)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#plot 1&lt;br /&gt;
plot(res[,1],res[,2],type=&quot;l&quot;, ylab=&quot;seconds&quot;, xlab=&quot;number of explanatory variables&quot;,ylim=c(0,500))&lt;br /&gt;
lines(res[,1],res[,3],col=&quot;red&quot;,lty=2)&lt;br /&gt;
lines(res[,1],res[,4],col=&quot;blue&quot;,lty=3)&lt;br /&gt;
legend(&quot;topleft&quot;,c(&quot;glm&quot;,&quot;speedglm&quot;,&quot;glmnet&quot;),col=c(&quot;black&quot;,&quot;red&quot;,&quot;blue&quot;),lty=1)&lt;br /&gt;
&lt;br /&gt;
#plot 2&lt;br /&gt;
plot(obj[,1],log(obj[,2]),type=&quot;l&quot;, ylab=&quot;object size (log(M))&quot;, xlab=&quot;number of explanatory variables&quot;,ylim=c(10,23))&lt;br /&gt;
lines(obj[,1],log(obj[,3]),col=&quot;red&quot;,lty=2)&lt;br /&gt;
lines(obj[,1],log(obj[,4]),col=&quot;blue&quot;,lty=3)&lt;br /&gt;
abline(h=log(8042*1e6))&lt;br /&gt;
abline(h=log(2000*1e6))&lt;br /&gt;
legend(&quot;topleft&quot;,c(&quot;glm&quot;,&quot;speedglm&quot;,&quot;glmnet&quot;),col=c(&quot;black&quot;,&quot;red&quot;,&quot;blue&quot;),lty=1)&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/8171034479117086855/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/8171034479117086855' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8171034479117086855'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8171034479117086855'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/glm-speedglm-glmnet-comparison-part-1.html' title='glm, speedglm, glmnet comparison (part 1 repeated with lambda=0)'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-8583739017993146672</id><published>2013-10-10T12:35:00.001-07:00</published><updated>2013-10-10T18:09:26.906-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="2-player"/><category scheme="http://www.blogger.com/atom/ns#" term="big data"/><category scheme="http://www.blogger.com/atom/ns#" term="Dixon and Cole"/><category scheme="http://www.blogger.com/atom/ns#" term="glm"/><category scheme="http://www.blogger.com/atom/ns#" term="glm-speedglm-glmnet comparison"/><category scheme="http://www.blogger.com/atom/ns#" term="regression"/><title type='text'>Dixon and Coles 2-player model with glmnet: Tests with simulated real data</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;i&gt;Update: all these tests are using the default lambda for glmnet.&amp;nbsp; Since posting this I discovered that passing in lambda=0 to glmnet forces it to return the equivalent glm estimates.&amp;nbsp; speedglm and glmnet estimates are much more similar and glmnet seems more robust with lambda=0.&amp;nbsp; Next post repeats the analyses here but with lambda=0 passed into glmnet.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
Now I will take real soccer match data, with all its non-random mixing, but substitute randomly generated scores from teams with known attack and defend strengths.&amp;nbsp; I do a series of tests to try replicate the problem shown in&amp;nbsp;  &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/dixon-and-coles-2-player-model-fit-with.html&quot;&gt;Dixon and Coles model fit with glmnet: Test 1 with real data.&lt;/a&gt;&lt;b&gt;Test 1&lt;/b&gt; is with i.i.d. attack strengths and didn&#39;t reproduce the problem.&amp;nbsp; &lt;b&gt;Test 2&lt;/b&gt; is a little more realistic and has correlated attack and defend strengths (teams with strong attack tend to have strong defense) mimicking the real data.&amp;nbsp; This didn&#39;t reproduce the problem either. &lt;b&gt;Test 3&lt;/b&gt; uses the attack and defense strengths that came out of speedglm used on the real data.&amp;nbsp; These have the property that different age groups have different strengths.&amp;nbsp; This finally replicates the problem and shows that it is glmnet that is producing the bad estimates (cannot recover the values used to produce the simulated data).&amp;nbsp; The full R code to run all the tests is at the bottom.&amp;nbsp; &lt;i&gt;Note all these results are using glmnet coefficients at lambda = max(lambda) .&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Test 1: Attack and defend strengths are i.i.d normal (the bold bit)&lt;/b&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;sim_data=rank_data&lt;br /&gt;sim_data$scores = rank_data$scores[!(is.na(rank_data$scores$home.score) &amp;amp; is.na(rank_data$scores$away.score)),]&lt;br /&gt;teams = unique(c(as.character(sim_data$scores$home.team),as.character(sim_data$scores$away.team)))&lt;br /&gt;nteams = length(teams)&lt;br /&gt;&lt;b&gt;sim.attack = rnorm(nteams)&lt;br /&gt;sim.defend = rnorm(nteams)-.4&lt;/b&gt;&lt;br /&gt;sim.scores = sim_data$scores&lt;br /&gt;ngames = dim(sim.scores)[1]&lt;br /&gt;for(i in 1:ngames){&lt;br /&gt;&amp;nbsp; sim.scores$home.score[i] = rpois(1,exp(sim.attack[which(teams==sim.scores$home.team[i])] - sim.defend[which(teams==sim.scores$away.team[i])]))&lt;br /&gt;&amp;nbsp; sim.scores$away.score[i] = rpois(1,exp(sim.attack[which(teams==sim.scores$away.team[i])] - sim.defend[which(teams==sim.scores$home.team[i])]))&lt;br /&gt;}&lt;br /&gt;sim_data$scores=sim.scores&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Make sure the sim and real data look remotely similar (the 0.4 added to sim.defend was to get the mean goals scored similar and # of 0s similar).&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjdHqkk_BvY2BCaSmk-aszF7LCdAMmP3KO25oLNa13DCd-YbX6DlKG-z6lBPgsAEjSyNotVTK0Okvi8wRgEzfJzHfxhBgSBEDpF2TyaOQZXEjfq209NqJIFLuhERhJhIEd0nbn7pg/s1600/glm-comp-dixon-cole-2b.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;264&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjdHqkk_BvY2BCaSmk-aszF7LCdAMmP3KO25oLNa13DCd-YbX6DlKG-z6lBPgsAEjSyNotVTK0Okvi8wRgEzfJzHfxhBgSBEDpF2TyaOQZXEjfq209NqJIFLuhERhJhIEd0nbn7pg/s320/glm-comp-dixon-cole-2b.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;par(mfrow=c(1,2))&lt;br /&gt;hist(sim.scores$home.score,breaks=0:500,xlim=c(0,20),ylim=c(0,10000),main=&quot;simulated&quot;,xlab=&quot;home score&quot;)&lt;br /&gt;hist(rank_data$scores$home.score,breaks=0:500,xlim=c(0,20),ylim=c(0,10000),main=&quot;real&quot;,xlab=&quot;home score&quot;)&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Not horrible.&amp;nbsp; I&#39;ll go with that.&lt;br /&gt;
&lt;br /&gt;
Fit the simulated data with speedglm and glmnet&lt;br /&gt;
glmnet run with default settings (except family=&quot;poisson&quot;) &lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#using fbRanks 2.0&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;age=c(&quot;B01&quot;,&quot;B00&quot;,&quot;B99&quot;,&quot;B98&quot;,&quot;B97&quot;,&quot;B96&quot;)&lt;br /&gt;fbRanks.sim=rank.teams(scores=sim_data$scores, teams=sim_data$teams, age=age, min.date=min.date, max.date=max.date, silent=TRUE, time.weight.eta=best.eta, date.format=&quot;%m/%d/%Y&quot;, fun=&quot;glmnet&quot;)&lt;br /&gt;p.sim=print(fbRanks.sim,silent=TRUE)$ranks[[1]]&lt;br /&gt;fbRanks.sim.spdglm=rank.teams(scores=sim_data$scores, teams=sim_data$teams, age=age, min.date=min.date, max.date=max.date, silent=TRUE, time.weight.eta=best.eta, date.format=&quot;%m/%d/%Y&quot;, fun=&quot;speedglm&quot;)&lt;br /&gt;p.spd=print(fbRanks.sim.spdglm,silent=TRUE)$ranks[[1]]&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Plot estimates against true&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;par(mfrow=c(1,2))&lt;br /&gt;plot(log(p.sim$attack),sim.attack[match(p.sim$team,teams)],&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; main=&quot;glmnet&quot;,xlab=&quot;estimated attack&quot;,ylab=&quot;true attack&quot;)&lt;br /&gt;plot(log(p.spd$attack),sim.attack[match(p.spd$team,teams)],&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; main=&quot;speedglm&quot;,xlab=&quot;estimated attack&quot;,ylab=&quot;true attack&quot;)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwJZ2Z_kanqkLjU43sdW2yfAonFeFpDyBTBaB4CHGfzI-zqZ6yRna9t4RSDXOMb1tt7y_WiLXU6dU15CjbpcHc2DSuY8kDi5fxw-uSJDoRBv5h4Jxt4skaxY6lbcZurOytnrFNKg/s1600/glm-comp-dixon-cole-2c.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;212&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwJZ2Z_kanqkLjU43sdW2yfAonFeFpDyBTBaB4CHGfzI-zqZ6yRna9t4RSDXOMb1tt7y_WiLXU6dU15CjbpcHc2DSuY8kDi5fxw-uSJDoRBv5h4Jxt4skaxY6lbcZurOytnrFNKg/s320/glm-comp-dixon-cole-2c.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Compare to each other:&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#compare to each other&lt;br /&gt;par(mfrow=c(1,1))&lt;br /&gt;teamsb=union(as.character(p.sim$team),as.character(p.spd$team))&lt;br /&gt;plot(p.spd$total[match(teamsb,p.spd$team)],p.sim$total[match(teamsb,p.sim$team)])&lt;br /&gt;abline(0,1)&lt;/span&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiA-Cgr_Jc1xX48GQ0Z-znfo2FgblytAIGhMW4zhi45_CCFYxBIvUj8UO4LjZqFyrpoZDYuQjZ-2hv5RP49MoArzOkp9a1P_8DPNQi0UZ8r4Jem3J1nW4ZUZNi58IXjXD1DkDOPaQ/s1600/glm-comp-dixon-cole-2d.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;212&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiA-Cgr_Jc1xX48GQ0Z-znfo2FgblytAIGhMW4zhi45_CCFYxBIvUj8UO4LjZqFyrpoZDYuQjZ-2hv5RP49MoArzOkp9a1P_8DPNQi0UZ8r4Jem3J1nW4ZUZNi58IXjXD1DkDOPaQ/s320/glm-comp-dixon-cole-2d.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
That looks pretty good, except for the points about -2 below the 1-1 line.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Test 2: attack and defense strengths are correlated (the bold bit)&lt;/b&gt;&lt;br /&gt;
For this test, I am going to generate attack and defend strengths with the same mean and var-cov matrix as in the real data.&amp;nbsp; The previous post&amp;nbsp; &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/dixon-and-coles-2-player-model-fit-with.html&quot;&gt;HERE&lt;/a&gt; got estimates of attack and defend strength from the real data.&amp;nbsp; I use those estimates (called &lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;p.b&lt;/span&gt;) here.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
Replace the bolded bit in the Test 1 code with this&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&amp;nbsp; mu=apply(cbind(log(p.b$attack),-1*log(p.b$defense)),2,mean,na.rm=TRUE)&lt;br /&gt;&amp;nbsp; Sigma = cov(cbind(log(p.b$attack),-1*log(p.b$defense)),use=&quot;na.or.complete&quot;)&lt;br /&gt;&amp;nbsp; tmp=mvrnorm(nteams,mu=mu,Sigma=Sigma)&lt;br /&gt;&amp;nbsp; sim.attack = tmp[,1]&lt;br /&gt;&amp;nbsp; sim.defend = tmp[,2]&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Now my attack and defend strengths have the same structure as the estimates from speedglm from the real data (the &lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;p.b$attack&lt;/span&gt; and &lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;p.b$defense&lt;/span&gt;).&lt;br /&gt;
&lt;br /&gt;
Plot estimates against true&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;par(mfrow=c(1,2))&lt;br /&gt;mse.sim = mean((log(p.sim$attack)-sim.attack[match(p.sim$team,teams)])^2)&lt;br /&gt;plot(log(p.sim$attack),sim.attack[match(p.sim$team,teams)],&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; main=paste(&quot;glmnet\nmse =&quot;,mse.sim),xlab=&quot;estimated attack&quot;,ylab=&quot;true attack&quot;)&lt;br /&gt;mse.spd = mean((log(p.spd$attack[p.spd$attack!=0])-sim.attack[match(p.spd$team[p.spd$attack!=0],teams)])^2,na.rm=TRUE)&lt;br /&gt;plot(log(p.spd$attack),sim.attack[match(p.spd$team,teams)],&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; main=paste(&quot;speedglm\nmse =&quot;,mse.spd),xlab=&quot;estimated attack&quot;,ylab=&quot;true attack&quot;)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcfIzR31pkXuBveoxVphok6amurpSHENkjA6kCDmh-MBDm1UXSrpJ7BDkDyKf1NLb1dv1yxN_IbeuTip28UaQw3ld_iikQMrjyhprFOTkYMc3AkZrdNRGsmOwqKpfs1cbXY6idgg/s1600/glm-comp-dixon-cole-3a.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;306&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcfIzR31pkXuBveoxVphok6amurpSHENkjA6kCDmh-MBDm1UXSrpJ7BDkDyKf1NLb1dv1yxN_IbeuTip28UaQw3ld_iikQMrjyhprFOTkYMc3AkZrdNRGsmOwqKpfs1cbXY6idgg/s400/glm-comp-dixon-cole-3a.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;That looks ok.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Look at total strength which combines attack and defense strengths.&amp;nbsp; print(fbRanks) is subtracting the mean total, so I&#39;m doing my abline with the mean added back on.&amp;nbsp;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;par(mfrow=c(1,2))&lt;br /&gt;sim.total = (sim.attack+sim.defend)/log(2)&lt;br /&gt;plot(p.sim$total,sim.total[match(p.sim$team,teams)],&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; main=&quot;glmnet&quot;,xlab=&quot;estimated&quot;,ylab=&quot;true&quot;)&lt;br /&gt;abline(mean(sim.total[match(p.sim$team,teams)]),1)&lt;br /&gt;abline(mean(sim.total[match(p.sim$team,teams)])+sin(pi/4),1,col=&quot;red&quot;)&lt;br /&gt;abline(mean(sim.total[match(p.sim$team,teams)])-1*sin(pi/4),1,col=&quot;red&quot;)&lt;br /&gt;plot(p.spd$total,sim.total[match(p.spd$team,teams)],&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; main=&quot;speedglm&quot;,xlab=&quot;estimated&quot;,ylab=&quot;true&quot;)&lt;br /&gt;abline(mean(sim.total[match(p.spd$team,teams)]),1)&lt;br /&gt;abline(mean(sim.total[match(p.spd$team,teams)])+sin(pi/4),1,col=&quot;red&quot;)&lt;br /&gt;abline(mean(sim.total[match(p.spd$team,teams)])-1*sin(pi/4),1,col=&quot;red&quot;)&lt;br /&gt;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgH4FbkpF1hU7KNjSXvSNA5O3XTL_y-CeRdGNH8JO0a8HPv0jqVWxTE_hibPsqXj_52DRa9SFBlaYD-iSWbG0906ezgNv8EvjTFbFWS7aiSpZHoYIuEusDcUOoA74jnlHvI8KT3IQ/s1600/glm-comp-dixon-coles-3b.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;316&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgH4FbkpF1hU7KNjSXvSNA5O3XTL_y-CeRdGNH8JO0a8HPv0jqVWxTE_hibPsqXj_52DRa9SFBlaYD-iSWbG0906ezgNv8EvjTFbFWS7aiSpZHoYIuEusDcUOoA74jnlHvI8KT3IQ/s640/glm-comp-dixon-coles-3b.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
I really want to be within those red lines which off the true total by +/- 1.0.&amp;nbsp; A lot of my estimates are outside that.&amp;nbsp; Let&#39;s look at what fraction fall outside the +/- 1.0 for different numbers of games played.&amp;nbsp; I expect that estimates are better for teams that have played more games.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#compare total against games played&lt;br /&gt;par(mfrow=c(1,2))&lt;br /&gt;sim.total = (sim.attack+sim.defend)/log(2)&lt;br /&gt;nrange=1:30&lt;br /&gt;fracbig = c()&lt;br /&gt;for(nlim in nrange){&lt;br /&gt;&amp;nbsp; fracbig = c(fracbig, sum(abs(p.sim$total[p.sim$n&amp;gt;nlim]-sim.total[match(p.sim$team[p.sim$n&amp;gt;nlim],teams)])&amp;gt;1,na.rm=TRUE)/sum(p.sim$n&amp;gt;nlim))&lt;br /&gt;}&lt;br /&gt;par(mfrow=c(1,1))&lt;br /&gt;plot(nrange,fracbig,type=&quot;l&quot;,xlab=&quot;number of games played&quot;)&lt;br /&gt;fracbig = c()&lt;br /&gt;for(nlim in nrange){&lt;br /&gt;&amp;nbsp; fracbig = c(fracbig, sum(abs(p.spd$total[p.spd$n&amp;gt;nlim]-sim.total[match(p.spd$team[p.spd$n&amp;gt;nlim],teams)])&amp;gt;1,na.rm=TRUE)/sum(p.spd$n&amp;gt;nlim))&lt;br /&gt;}&lt;br /&gt;lines(nrange,fracbig,col=&quot;red&quot;)&lt;br /&gt;title(&quot;fraction outside abs(est total - true total)&amp;gt;1\nglmnet black and speedglm red&quot;)&lt;/span&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhlc1B1GNF4S50dyk-MEhh5E8tSurFcdcZs839yQVA6LwBInP0RLGzNqGYwR0HxAUCdXikorKankw5k7T290DxHh4LbpAapFlzqglpc-pBdIqAAHm7jB8DrC-SRsZtiKyENB_IUYQ/s1600/glm-comp-dixon-coles-3c.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;340&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhlc1B1GNF4S50dyk-MEhh5E8tSurFcdcZs839yQVA6LwBInP0RLGzNqGYwR0HxAUCdXikorKankw5k7T290DxHh4LbpAapFlzqglpc-pBdIqAAHm7jB8DrC-SRsZtiKyENB_IUYQ/s400/glm-comp-dixon-coles-3c.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
This suggests that glmnet is performing better than speedglm when I use a minimum number of games (so just don&#39;t show estimates for teams with few games).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
But I still haven&#39;t replicated the problem seen in the real data.&amp;nbsp; Test 3, make the age groups have different means.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Test 3: use estimates from speedglm as attack and defense strength.&amp;nbsp;&lt;/b&gt; Now attack and defense are correlated, but also the different age groups have different mean strengths (order teams tend to be stronger).&amp;nbsp; For this I am just going to use the estimates from cluster.1 in fbRanks.b from the previous Dixon &amp;amp; Coles post.&amp;nbsp; It so happens that rank_data has 9 unique clusters.&lt;br /&gt;
&lt;br /&gt;
Replace the attack and strength generating code with this&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&amp;nbsp; tmp=p.b[!is.na(p.b$attack) &amp;amp; !is.na(p.b$defense) &amp;amp; !(p.b$defense==0) &amp;amp; !(p.b$attack==0),]&lt;br /&gt;&amp;nbsp; teams = as.character(tmp$team)&lt;br /&gt;&amp;nbsp; nteams = length(teams)&lt;br /&gt;&amp;nbsp; sim.attack = log(tmp$attack)&lt;br /&gt;&amp;nbsp; sim.defend = log(tmp$defense)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&amp;nbsp; #get rid of data from teams that are not in cluster.1&lt;br /&gt;&amp;nbsp; sim.scores = sim_data$scores[sim_data$scores$home.team %in% teams &amp;amp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; sim_data$scores$away.team %in% teams,]&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
FINALLY, this replicates the problem of multiple parallel lines.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnb6X5Rg43iGUrOaoz8rFTy8O6l_WBJzCSgJ2j6S51Z3ct9o4BHOCOdDyNxZKGD1AUMX5z-f2QQ9xi8kAPQQcBf0-UDVvNtf8IfkXoG8qM1JwJpGL1aMPz9GVUe7Po-3PxZfOD_Q/s1600/glm-comp=dixon-coles-4a.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;308&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnb6X5Rg43iGUrOaoz8rFTy8O6l_WBJzCSgJ2j6S51Z3ct9o4BHOCOdDyNxZKGD1AUMX5z-f2QQ9xi8kAPQQcBf0-UDVvNtf8IfkXoG8qM1JwJpGL1aMPz9GVUe7Po-3PxZfOD_Q/s640/glm-comp=dixon-coles-4a.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
And it is glmnet that is having problems:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhF9jkHxIHyhwAZ6ids-uRywGGV5_4iO_FuXBKtkgcpM9VN3czNlMn7fBcTw1vkPwtRI6ICbkxmjcgZt80z8do-Yi2VvlVC4xsOe3DbqItXhJQEcH9nzRDQ6bMDaHZUHmI-XTEaDA/s1600/glm-comp-dixon-coles-4b.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;330&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhF9jkHxIHyhwAZ6ids-uRywGGV5_4iO_FuXBKtkgcpM9VN3czNlMn7fBcTw1vkPwtRI6ICbkxmjcgZt80z8do-Yi2VvlVC4xsOe3DbqItXhJQEcH9nzRDQ6bMDaHZUHmI-XTEaDA/s640/glm-comp-dixon-coles-4b.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
And the consequences for the total strength estimate are very bad.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPjxkyh0w3j_mNvAjshhJWFyVRX170BqZ1boI8bmA_uV9YNjd_B7uAq2-f6AuC-w2i3v-Re8I6HQbjD28HwtxyxwljRww-EW4tx08RxhLkloNbRn4hSwIu6tGRqfkOwiK-vD-ZQQ/s1600/glm-comp-dixon-coles-4c.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;346&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPjxkyh0w3j_mNvAjshhJWFyVRX170BqZ1boI8bmA_uV9YNjd_B7uAq2-f6AuC-w2i3v-Re8I6HQbjD28HwtxyxwljRww-EW4tx08RxhLkloNbRn4hSwIu6tGRqfkOwiK-vD-ZQQ/s400/glm-comp-dixon-coles-4c.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
Next I&#39;ll work on trying to tweak glmnet&#39;s settings and see if I can get around this problem.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Full R code for running these simulations and tests&lt;/b&gt;&lt;br /&gt;
depends on fbRanks 2.0&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;library(fbRanks)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#load in rank_data from RData file and run code to produce p.b&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#takes 10 min or so &lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#fbRanks.b=rank.teams(scores=rank_data$scores, teams=rank_data$teams, min.date=min.date, max.date=max.date, silent=TRUE, time.weight.eta=best.eta, date.format=&quot;%m/%d/%Y&quot;, fun=&quot;speedglm&quot;)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;#p.b=print(fbRanks.b,silent=TRUE)$ranks[[1]] #cluster.1&lt;br /&gt;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;testt = 1; #Test with i.i.d. strengths&lt;br /&gt;testt = 2; #Test with correlated strengths&lt;br /&gt;testt = 3; #use the speedglm estimates from the real data&lt;br /&gt;sim_data=rank_data&lt;br /&gt;sim_data$scores = rank_data$scores[!(is.na(rank_data$scores$home.score) &amp;amp; is.na(rank_data$scores$away.score)),]&lt;br /&gt;teams = unique(c(as.character(sim_data$scores$home.team),as.character(sim_data$scores$away.team)))&lt;br /&gt;nteams = length(teams)&lt;br /&gt;sim.scores = sim_data$scores&lt;br /&gt;if(testt == 1){&lt;br /&gt;sim.attack = rnorm(nteams)&lt;br /&gt;sim.defend = rnorm(nteams)-.4&lt;br /&gt;}&lt;br /&gt;if(testt==2){&lt;br /&gt;&amp;nbsp; mu=apply(cbind(log(p.b$attack),-1*log(p.b$defense)),2,mean,na.rm=TRUE)&lt;br /&gt;&amp;nbsp; Sigma = cov(cbind(log(p.b$attack),-1*log(p.b$defense)),use=&quot;na.or.complete&quot;)&lt;br /&gt;&amp;nbsp; tmp=mvrnorm(nteams,mu=mu,Sigma=Sigma)&lt;br /&gt;&amp;nbsp; sim.attack = tmp[,1]&lt;br /&gt;&amp;nbsp; sim.defend = tmp[,2]&lt;br /&gt;}&lt;br /&gt;if(testt==3){&lt;br /&gt;&amp;nbsp; tmp=p.b[!is.na(p.b$attack) &amp;amp; !is.na(p.b$defense) &amp;amp; !(p.b$defense==0) &amp;amp; !(p.b$attack==0),]&lt;br /&gt;&amp;nbsp; teams = as.character(tmp$team)&lt;br /&gt;&amp;nbsp; nteams = length(teams)&lt;br /&gt;&amp;nbsp; sim.attack = log(tmp$attack)&lt;br /&gt;&amp;nbsp; sim.defend = log(tmp$defense)&lt;br /&gt;&amp;nbsp; sim.scores = sim_data$scores[sim_data$scores$home.team %in% teams &amp;amp; sim_data$scores$away.team %in% teams,]&lt;br /&gt;}&lt;br /&gt;ngames = dim(sim.scores)[1]&lt;br /&gt;for(i in 1:ngames){&lt;br /&gt;&amp;nbsp; sim.scores$home.score[i] = rpois(1,exp(sim.attack[which(teams==sim.scores$home.team[i])] - sim.defend[which(teams==sim.scores$away.team[i])]))&lt;br /&gt;&amp;nbsp; sim.scores$away.score[i] = rpois(1,exp(sim.attack[which(teams==sim.scores$away.team[i])] - sim.defend[which(teams==sim.scores$home.team[i])]))&lt;br /&gt;}&lt;br /&gt;sim_data$scores=sim.scores&lt;br /&gt;age=c(&quot;B01&quot;,&quot;B00&quot;,&quot;B99&quot;,&quot;B98&quot;,&quot;B97&quot;,&quot;B96&quot;)&lt;br /&gt;fbRanks.sim=rank.teams(scores=sim_data$scores, teams=sim_data$teams, age=age, min.date=min.date, max.date=max.date, silent=TRUE, time.weight.eta=best.eta, date.format=&quot;%m/%d/%Y&quot;, fun=&quot;glmnet&quot;)&lt;br /&gt;fbRanks.sim.spdglm=rank.teams(scores=sim_data$scores, teams=sim_data$teams, age=age, min.date=min.date, max.date=max.date, silent=TRUE, time.weight.eta=best.eta, date.format=&quot;%m/%d/%Y&quot;, fun=&quot;speedglm&quot;)&lt;br /&gt;p.sim=print(fbRanks.sim,silent=TRUE)$ranks&lt;br /&gt;p.spd=print(fbRanks.sim.spdglm,silent=TRUE)$ranks&lt;br /&gt;if(testt!=3){ #use cluster 1; there are many&lt;br /&gt;&amp;nbsp; p.sim=p.sim[[1]]&lt;br /&gt;&amp;nbsp; p.spd=p.spd[[1]]&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;#compare estimates agains true&lt;br /&gt;par(mfrow=c(1,2))&lt;br /&gt;mse.sim = mean((log(p.sim$attack[p.sim$attack!=0])-sim.attack[match(p.sim$team[p.sim$attack!=0],teams)])^2,na.rm=TRUE)&lt;br /&gt;plot(log(p.sim$attack),sim.attack[match(p.sim$team,teams)],&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; main=paste(&quot;glmnet\nmse =&quot;,mse.sim),xlab=&quot;estimated attack&quot;,ylab=&quot;true attack&quot;)&lt;br /&gt;abline(0,1)&lt;br /&gt;mse.spd = mean((log(p.spd$attack[p.spd$attack!=0])-sim.attack[match(p.spd$team[p.spd$attack!=0],teams)])^2,na.rm=TRUE)&lt;br /&gt;plot(log(p.spd$attack),sim.attack[match(p.spd$team,teams)],&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; main=paste(&quot;speedglm\nmse =&quot;,mse.spd),xlab=&quot;estimated attack&quot;,ylab=&quot;true attack&quot;)&lt;br /&gt;abline(0,1)&lt;br /&gt;&lt;br /&gt;#compare total&lt;br /&gt;par(mfrow=c(1,2))&lt;br /&gt;sim.total = (sim.attack+sim.defend)/log(2)&lt;br /&gt;plot(p.sim$total,sim.total[match(p.sim$team,teams)],&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; main=&quot;glmnet&quot;,xlab=&quot;estimated&quot;,ylab=&quot;true&quot;)&lt;br /&gt;abline(mean(sim.total[match(p.sim$team,teams)]),1)&lt;br /&gt;abline(mean(sim.total[match(p.sim$team,teams)])+sin(pi/4),1,col=&quot;red&quot;)&lt;br /&gt;abline(mean(sim.total[match(p.sim$team,teams)])-1*sin(pi/4),1,col=&quot;red&quot;)&lt;br /&gt;plot(p.spd$total,sim.total[match(p.spd$team,teams)],&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; main=&quot;speedglm&quot;,xlab=&quot;estimated&quot;,ylab=&quot;true&quot;)&lt;br /&gt;abline(mean(sim.total[match(p.spd$team,teams)]),1)&lt;br /&gt;abline(mean(sim.total[match(p.spd$team,teams)])+sin(pi/4),1,col=&quot;red&quot;)&lt;br /&gt;abline(mean(sim.total[match(p.spd$team,teams)])-1*sin(pi/4),1,col=&quot;red&quot;)&lt;br /&gt;&lt;br /&gt;#compare total against games played&lt;br /&gt;sim.total = (sim.attack+sim.defend)/log(2)&lt;br /&gt;nrange=1:30&lt;br /&gt;fracbig = c()&lt;br /&gt;for(nlim in nrange){&lt;br /&gt;&amp;nbsp; fracbig = c(fracbig, sum(abs(p.sim$total[p.sim$n&amp;gt;nlim]-sim.total[match(p.sim$team[p.sim$n&amp;gt;nlim],teams)])&amp;gt;1,na.rm=TRUE)/sum(p.sim$n&amp;gt;nlim))&lt;br /&gt;}&lt;br /&gt;par(mfrow=c(1,1))&lt;br /&gt;plot(nrange,fracbig,type=&quot;l&quot;,xlab=&quot;number of games played&quot;,ylim=c(0,.6))&lt;br /&gt;fracbig = c()&lt;br /&gt;for(nlim in nrange){&lt;br /&gt;&amp;nbsp; fracbig = c(fracbig, sum(abs(p.spd$total[p.spd$n&amp;gt;nlim]-sim.total[match(p.spd$team[p.spd$n&amp;gt;nlim],teams)])&amp;gt;1,na.rm=TRUE)/sum(p.spd$n&amp;gt;nlim))&lt;br /&gt;}&lt;br /&gt;lines(nrange,fracbig,col=&quot;red&quot;)&lt;br /&gt;title(&quot;fraction outside abs(est total - true total)&amp;gt;1\nglmnet black and speedglm red&quot;)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;#compare to each other&lt;br /&gt;par(mfrow=c(1,2))&lt;br /&gt;teamsb=union(as.character(p.sim$team),as.character(p.spd$team))&lt;br /&gt;plot(log(p.spd$attack[match(teamsb,p.spd$team)]),log(p.sim$attack[match(teamsb,p.sim$team)]),&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; xlab=&quot;speedglm estimate&quot;,ylab=&quot;glmnet estimate&quot;,main=&quot;attack estimates&quot;)&lt;br /&gt;abline(0,1)&lt;br /&gt;plot(log(p.spd$defense[match(teamsb,p.spd$team)]),log(p.sim$defense[match(teamsb,p.sim$team)]),&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; xlab=&quot;speedglm estimate&quot;,ylab=&quot;glmnet estimate&quot;,main=&quot;defend estimates&quot;)&lt;br /&gt;abline(0,1)&lt;br /&gt;&lt;br /&gt;#plot 1 make sure the sim and real data look kind of similar&lt;br /&gt;par(mfrow=c(1,2))&lt;br /&gt;hist(sim.scores$home.score,breaks=0:500,xlim=c(0,20),ylim=c(0,10000),main=&quot;simulated&quot;,xlab=&quot;home score&quot;)&lt;br /&gt;hist(rank_data$scores$home.score,breaks=0:500,xlim=c(0,20),ylim=c(0,10000),main=&quot;real&quot;,xlab=&quot;home score&quot;)&lt;/span&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/8583739017993146672/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/8583739017993146672' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8583739017993146672'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8583739017993146672'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/dixon-and-coles-2-player-model-with.html' title='Dixon and Coles 2-player model with glmnet: Tests with simulated real data'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjdHqkk_BvY2BCaSmk-aszF7LCdAMmP3KO25oLNa13DCd-YbX6DlKG-z6lBPgsAEjSyNotVTK0Okvi8wRgEzfJzHfxhBgSBEDpF2TyaOQZXEjfq209NqJIFLuhERhJhIEd0nbn7pg/s72-c/glm-comp-dixon-cole-2b.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-3628829560515409518</id><published>2013-10-10T09:32:00.000-07:00</published><updated>2013-10-10T17:39:38.266-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="2-player"/><category scheme="http://www.blogger.com/atom/ns#" term="big data"/><category scheme="http://www.blogger.com/atom/ns#" term="Dixon and Cole"/><category scheme="http://www.blogger.com/atom/ns#" term="glm"/><category scheme="http://www.blogger.com/atom/ns#" term="glm-speedglm-glmnet comparison"/><title type='text'>Dixon and Coles 2-player model fit with glmnet: Test 1 with real data</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Follow up on &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/dixon-and-coles-2-player-model-in-glm.html&quot;&gt;Dixon and Coles 2-player model in glm, speed, and glmnet&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
Initial tests with simulated data with random mixing---meaning the graph of interactions across players has no &#39;clusters&#39;---was promising and suggested that glmnet is both much faster and more robust.&amp;nbsp; However, real social networks (and 2-player systems can be thought of as a type of social network) are highly non-random.&amp;nbsp; The norm is a network with clusters in which players interact strongly and where there is lower (and potentially quite low) interactions across clusters.&amp;nbsp; The result is going to be a likelihood surface with strong ridges.&amp;nbsp; I don&#39;t fully understand the algorithm used by glmnet, but if it is using any kind of ascent algorithm, it might get stuck on these ridges.&lt;br /&gt;
&lt;br /&gt;
It looks like this might be happening.&amp;nbsp; Here is a plot of speedglm versus glmnet for some real soccer match data spanning 6 age groups.&amp;nbsp; Age groups are clusters and within age groups there are further clusters (states and leagues).&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;Update:&lt;/b&gt; I was using glmnet default lambda which does not quite replicate glm behavior.&amp;nbsp; I was using the coefficients at min(fit$lambda) which was almost a saturated model but still not quite the same. See update below where I pass in lambda=0 to force glmnet to return glm-equivalent estimates.&amp;nbsp; The speedglm and glmnet estimates are now identical.&amp;nbsp; See updated plot below.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbZFd5pXk_KPhIEW51OPfcIeHsDSHkWXHbbK-wLCdSqbeiJa97MxbfjjVDAlGMFvivrcWlIPZ507LEAf0gaxbrv9n31Po5IsabO7EvzU3m5WqqHK8kWyAv2Tp4xPn4RgddBpSe_Q/s1600/glm-comp-dixon-cole-2a.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;330&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbZFd5pXk_KPhIEW51OPfcIeHsDSHkWXHbbK-wLCdSqbeiJa97MxbfjjVDAlGMFvivrcWlIPZ507LEAf0gaxbrv9n31Po5IsabO7EvzU3m5WqqHK8kWyAv2Tp4xPn4RgddBpSe_Q/s400/glm-comp-dixon-cole-2a.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
The estimates should be parallel to the 1-1 line (but not necessarily on it).&amp;nbsp; Notice the data seem to fall on multiple 1-1 lines.&amp;nbsp; This suggests that individual clusters (age groups) are ok, but glmnet is stopping before getting to a solution that gets all those the same 1-1 line.&amp;nbsp; However to understand what is going wrong this to work with simulated data where I know the &quot;truth&quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;R code to produce plot above.&amp;nbsp;&amp;nbsp;&lt;/b&gt;&lt;br /&gt;
rank_data is a data.frame of the 2013 match data for WA and OR youth boys select soccer teams.&amp;nbsp; About 2500 teams.&amp;nbsp; The data includes age B02, B95 and B94 (B=boys, 02=birth year), but I left that off to speed up speedglm.&amp;nbsp; The problem shown in the plot above is much much worse with those ages added.&lt;br /&gt;
&lt;br /&gt;
#using fbRanks R package 2.0&lt;br /&gt;
library(fbRanks)&lt;br /&gt;
#this was using default lambda for glmnet and getting coefficients using coef(fit, s=min(fit$lambda))&lt;br /&gt;
#where fit is what is returned from the fit=glmnet() call &lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;age=c(&quot;B01&quot;,&quot;B00&quot;,&quot;B99&quot;,&quot;B98&quot;,&quot;B97&quot;,&quot;B96&quot;)&lt;br /&gt;fbRanks.a=rank.teams(scores=rank_data$scores, teams=rank_data$teams, age=age, min.date=min.date, max.date=max.date, silent=TRUE, time.weight.eta=best.eta, date.format=&quot;%m/%d/%Y&quot;, fun=&quot;glmnet&quot;)&lt;br /&gt;fbRanks.b=rank.teams(scores=rank_data$scores, teams=rank_data$teams, age=age, min.date=min.date, max.date=max.date, silent=TRUE, time.weight.eta=best.eta, date.format=&quot;%m/%d/%Y&quot;, fun=&quot;speedglm&quot;)&lt;br /&gt;p.a=print(fbRanks.a,silent=TRUE)$ranks[[1]]&lt;br /&gt;p.b=print(fbRanks.b,silent=TRUE)$ranks[[1]]&lt;br /&gt;teams=union(as.character(p.a$team),as.character(p.b$team))&lt;br /&gt;plot(p.a$total[match(teams,p.a$team)],p.b$total[match(teams,p.b$team)],ylab=&quot;speedglm&quot;,xlab=&quot;glmnet&quot;)&lt;br /&gt;abline(0,1)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Update&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Passing in lambda=0 to the glmnet call fixes the problem.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Same code as above but with glmnet(...., lambda=0) call in the rank.teams() function.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;The estimates are not identical but my analysis with simulated data suggests that glmnet estimates are more robust. &lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjdjzbKo5O86HD7xvf4srpmV8g0hx4Coc-VsBdOo1VbMHdVjItVQBQLCGlkWgX_DSAS0EvAKUC9xpSD_IaM5W8PpkWfzV_GQ-Xg1q6_DZ2pkt4KxvWpY86bZqmnboTc4vbQfjDy9Q/s1600/glm-comp-dixon-cole-update-a.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;472&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjdjzbKo5O86HD7xvf4srpmV8g0hx4Coc-VsBdOo1VbMHdVjItVQBQLCGlkWgX_DSAS0EvAKUC9xpSD_IaM5W8PpkWfzV_GQ-Xg1q6_DZ2pkt4KxvWpY86bZqmnboTc4vbQfjDy9Q/s640/glm-comp-dixon-cole-update-a.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&amp;nbsp;&lt;/span&gt; &lt;/span&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/3628829560515409518/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/3628829560515409518' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3628829560515409518'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3628829560515409518'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/dixon-and-coles-2-player-model-fit-with.html' title='Dixon and Coles 2-player model fit with glmnet: Test 1 with real data'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbZFd5pXk_KPhIEW51OPfcIeHsDSHkWXHbbK-wLCdSqbeiJa97MxbfjjVDAlGMFvivrcWlIPZ507LEAf0gaxbrv9n31Po5IsabO7EvzU3m5WqqHK8kWyAv2Tp4xPn4RgddBpSe_Q/s72-c/glm-comp-dixon-cole-2a.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-8792304113130528029</id><published>2013-10-08T15:50:00.002-07:00</published><updated>2013-10-08T15:53:51.312-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="2-player"/><category scheme="http://www.blogger.com/atom/ns#" term="big data"/><category scheme="http://www.blogger.com/atom/ns#" term="Dixon and Cole"/><category scheme="http://www.blogger.com/atom/ns#" term="glm"/><category scheme="http://www.blogger.com/atom/ns#" term="glm-speedglm-glmnet comparison"/><category scheme="http://www.blogger.com/atom/ns#" term="regression"/><title type='text'>Dixon and Coles&#39; 2-player model in glm, speedglm and glmnet</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Back to Dixon and Coles model applied to a huge team pool.&amp;nbsp; &lt;span style=&quot;font-family: inherit;&quot;&gt;This is part of a &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/search/label/glm-speedglm-glmnet%20comparison&quot;&gt;series of posts comparing glm, speedglm and glmnet&lt;/a&gt; and is related to stuff I have been playing with regarding &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/search/label/2-player&quot;&gt;massive 2-player estimation problems&lt;/a&gt;.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Dixon, M. J. and Coles, S. G. (1997), Modelling Association Football 
Scores and Inefficiencies in the Football Betting Market. Journal of the
 Royal Statistical Society: Series C (Applied Statistics), 46:&amp;nbsp;265–280. 
doi:&amp;nbsp;10.1111/1467-9876.00065&lt;/span&gt;&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;The last post used a model that is pretty similar to Dixon and Coles model.&amp;nbsp; I&#39;ll tweak it a bit and do the same series of tests.&amp;nbsp; Some oddities about how I set up the model, which are irrelevant for the purpose of these speed tests, but I note them anyhow.&amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;In the simulated data, attack and defend strengths of a team are uncorrelated.&amp;nbsp; This is not true.&amp;nbsp; They are highly correlated.&amp;nbsp; This is btw why I can&#39;t use glmer on real data, i.e. can&#39;t just treat the strengths as random effects.&amp;nbsp; I tried and failed to figure how to treat different random effects as correlated with glmer in the &lt;a href=&quot;http://cran.r-project.org/web/packages/lme4/index.html&quot;&gt;lme4 R package&lt;/a&gt;.&amp;nbsp; Easy enough in a bayesian-glmer, but that is slow....&amp;nbsp;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;The model I passed to glm is unidentifiable.&amp;nbsp; One of the coefficients needs to be set to 0.&amp;nbsp; But glm and speedglm are smart enough to figure out what to do though they complain a bit.&amp;nbsp; Easy enough to fix.&amp;nbsp; Just specify the glm model as having 2 factor (attack and defend) and treat the subjects as levels.&amp;nbsp; Easy but not relevant for this test.&amp;nbsp; Btw I set this model up the correct way for glm normally.&amp;nbsp; I did it the other way here since my code from previous posts was closer to that.&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;For glmnet, I don&#39;t know how to specify lambda for the model with 1 coefficient equal to 0. I&#39;m sure it is possible to compute that, but I don&#39;t know how.&amp;nbsp; So I used the default lambda.&amp;nbsp; This will lead to some variable number of 0s.&amp;nbsp; Seems to work ok, in fact, works better than glm no doubt the extra constraints help.&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;b&gt;The model&lt;/b&gt;&lt;br /&gt;
Two subjects in each &quot;competition&quot;.&amp;nbsp; One is attacking, other is defending.&amp;nbsp; Each subject has an attack and defend strength.&amp;nbsp; The outcome of the competition is a poisson distributed random variable with mean = exp(attack strength of attacker + defend strength of defender).&amp;nbsp; If a subject has a low (very negative) defend strength, then only strong attackers can score against them.&amp;nbsp; If a subject has a high attack strength, they score against all but the strongest defenders.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;The simulation&lt;/b&gt;&lt;br /&gt;
I draw attack and defend strengths randomly from normal distributions.&amp;nbsp; I sample 2 subjects from the pool and assign them randomly to attack or defend.&amp;nbsp; I compute the &#39;result&#39; as a random number generated from the appropriate poisson distribution.&amp;nbsp; Repeat for 10*nSubjects number of competitions.&amp;nbsp; So the size of the my dataset is increasing with the number of subjects, which I do to make the data a bit more realistic.&amp;nbsp; This gives me about 10 competitions per subject.&amp;nbsp; So on average 5 competitions to get their attack strength and 5 to get their defend strength.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Results&lt;/b&gt;&lt;br /&gt;
glm is desperately slow.&amp;nbsp; 25 minutes for 1500 subjects! And that&#39;s a small test case.&amp;nbsp; Speedglm is considerably speedier at 7.5 minutes. But glmnet is HALF A SECOND for this problem and more robust.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYiR36T2QXU-2vkOfvzQAuADNWrD0NboHbgf35V8FYN4-jzumlkqmb_p16rfF1sMQUIWZ8ZRjPksqAl4-4inGJWhkLTZMFYPFNy5hRUxK_ZpdXXelqxYstiF0dp00jup1C59zR9w/s1600/glm-comp-attack-a.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;312&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYiR36T2QXU-2vkOfvzQAuADNWrD0NboHbgf35V8FYN4-jzumlkqmb_p16rfF1sMQUIWZ8ZRjPksqAl4-4inGJWhkLTZMFYPFNy5hRUxK_ZpdXXelqxYstiF0dp00jup1C59zR9w/s640/glm-comp-attack-a.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
glm is not particularly robust for this problem.&amp;nbsp; Top plot shows glmnet versus true.&amp;nbsp; Shows about what I expect.&amp;nbsp; Looks pretty good to me.&amp;nbsp; It widens out for low attack or defend strengths because those are cases where you get 0s from the poisson.&amp;nbsp; The way I set it up (adding the attack and defend strengths as opposed to subtracting defend strength from attack strength), negative defend strength equals strong defense and negative attack equals weak attack.&lt;br /&gt;
&lt;br /&gt;
Next plot shows glm versus true.&amp;nbsp; Bah, look at all those 1e-15 values. Ok, I made it hard for glm with sometimes only 1-2 competitions with which to estimate a strength, but glmnet did a lot better by setting some coef to 0s and thus constraining the problem a bit.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4lflbO8HNS-JVm0nJKv1cfBX67OOODU5ZZ_5QZOJ50RkD1ZoQapIDj7rq6k-GbwljEDOyRZMgdSVu3WJ573K2MrGX3aogBjjpQg5IT_TV95gtR5E9LWxWK3kJIFlW3WHl287wxA/s1600/glm-comp-attack-c.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;285&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4lflbO8HNS-JVm0nJKv1cfBX67OOODU5ZZ_5QZOJ50RkD1ZoQapIDj7rq6k-GbwljEDOyRZMgdSVu3WJ573K2MrGX3aogBjjpQg5IT_TV95gtR5E9LWxWK3kJIFlW3WHl287wxA/s400/glm-comp-attack-c.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBQELqhbZO37ZmGqp7zagvlm2N5ukXOq8uSGPPgUYiDwO5J7bEPC0rcDoKo6ftEKWBpkQF3bt-3JRoZQ0_788NwhzStOwPZ79gKnVCtSnrcvYsHykz7DJgnkNnrKx2r0zlvz04Ww/s1600/glm-comp-attack-d.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;285&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBQELqhbZO37ZmGqp7zagvlm2N5ukXOq8uSGPPgUYiDwO5J7bEPC0rcDoKo6ftEKWBpkQF3bt-3JRoZQ0_788NwhzStOwPZ79gKnVCtSnrcvYsHykz7DJgnkNnrKx2r0zlvz04Ww/s400/glm-comp-attack-d.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&amp;nbsp;When the values were not 1e-15, they matched glmnet&#39;s values:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9Cv36VzlAAacjVTiocPXyGoVZUSxcMV806N96WTlQ1pARn8IprbVpyCyM_vE4sobGAeRHG8ZSAsLqzXODvREaHA60ZG6YSyWwIyrtNzteDJFaLXzbX5PIuYmB9BhCkP_zuFxk-Q/s1600/glm-comp-attack-e.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;285&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9Cv36VzlAAacjVTiocPXyGoVZUSxcMV806N96WTlQ1pARn8IprbVpyCyM_vE4sobGAeRHG8ZSAsLqzXODvREaHA60ZG6YSyWwIyrtNzteDJFaLXzbX5PIuYmB9BhCkP_zuFxk-Q/s400/glm-comp-attack-e.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;b&gt;R code&lt;/b&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; font-size: small;&quot;&gt;library(glmnet)&lt;br /&gt;library(speedglm)&lt;br /&gt;&lt;br /&gt;#Treat subject as a explanatory variable (x). There will be nSubject x variables&lt;br /&gt;#This allows us to take into account that subject 1 in the player1, player2, or player3 is the same subject&lt;br /&gt;nPlayers=2 #how many 1s in each row of data&lt;br /&gt;res=obj=c() &lt;br /&gt;for(nSubjects in c(100,200,500,1000,1500)){&lt;br /&gt;&amp;nbsp; n=10*nSubjects&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #variance of the distribution of the player pool x&#39;s&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; mean.x = 0&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sig2.x = 1&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #true.x is what we are trying to estimate&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; true.attack = rnorm(nSubjects, mean.x, sig2.x)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; true.defend = rnorm(nSubjects, mean.x, sig2.x)&lt;br /&gt;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #There are 2 ways to set this up.&amp;nbsp; Treat subject as level in factors attack and defend&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #or create 2 (attack+defend) x n.x explanatory variables that are 0/1&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #they are mathematically equivalent to glmnet&lt;br /&gt;&amp;nbsp; levx=y=c() #levx is holder for player #; y is data&lt;br /&gt;&amp;nbsp; x = matrix(0,n,2*nSubjects) #x is the n x 2nSubjects explanatory variable matrix needed by glm&lt;br /&gt;&amp;nbsp; for(i in 1:n){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #draw nPlayers randomly for each of the n competitions&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; levx=rbind(levx,sample(nSubjects, 2, replace=FALSE))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; x[i,c(levx[i,]+c(0,nSubjects))]=1 #set x var for attacksubject = 1 if subject is present; same for defendsubject&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; y=c(y,rpois(1,exp(true.attack[levx[i,1]]+true.defend[levx[i,2]])))&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp; #set the colnames on the explanatory variables&lt;br /&gt;&amp;nbsp; colnames(x)=c(paste(&quot;attack&quot;,1:nSubjects,sep=&quot;&quot;),&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; font-size: small;&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; paste(&quot;defend&quot;,1:nSubjects,sep=&quot;&quot;))&lt;br /&gt;&amp;nbsp; dat = cbind(y=y,x)&lt;br /&gt;&amp;nbsp; dat = data.frame(dat) #glm wants a data frame&lt;br /&gt;&amp;nbsp; &lt;br /&gt;&amp;nbsp; cat(nSubjects); cat(&quot; &quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #set up the formula&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fooform = &quot;y~-1&quot;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fooform=paste(fooform,paste(&quot;+attack&quot;,1:nSubjects,collapse=&quot;&quot;,sep=&quot;&quot;),&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; font-size: small;&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; paste(&quot;+defend&quot;,1:nSubjects,collapse=&quot;&quot;,sep=&quot;&quot;),sep=&quot;&quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #fit glm&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; a=c(nSubjects, system.time(fit1&amp;lt;-glm(formula(fooform), data=dat, family=&quot;poisson&quot;))[1])&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; b=c(nSubjects, object.size(fit1))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #fit speedglm&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; a=c(a,system.time(fit2&amp;lt;-speedglm(formula(fooform), data=dat))[1])&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; b=c(b, object.size(fit2))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #fit glmnet&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #1 row for each player; col is just the player number&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; font-size: small;&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #need to t() levx so as.vector works by row&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace; font-size: small;&quot;&gt;&amp;nbsp; &amp;nbsp; #add that 0,nSubjects bit because I have 1:nSubjects for attack and another 1:nSubjects for defend &amp;nbsp; sx=sparseMatrix(rep(1:n,each=nPlayers),as.vector(t(levx+matrix(c(0,nSubjects),n,2,byrow=TRUE))),x=1)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; a=c(a, system.time(fit3&amp;lt;-glmnet(sx, y, intercept=FALSE, family=&quot;poisson&quot;))[1])&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; b=c(b, object.size(fit3))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; res=rbind(res,a)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; obj=rbind(obj,b)&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp; &lt;br /&gt;#plot 1&lt;br /&gt;plot(res[,1],res[,2],type=&quot;l&quot;, ylab=&quot;seconds&quot;, xlab=&quot;number of subjects&quot;)&lt;br /&gt;lines(res[,1],res[,3],col=&quot;red&quot;,lty=2)&lt;br /&gt;lines(res[,1],res[,4],col=&quot;blue&quot;,lty=3)&lt;br /&gt;legend(&quot;topleft&quot;,c(&quot;glm&quot;,&quot;speedglm&quot;,&quot;glmnet&quot;),col=c(&quot;black&quot;,&quot;red&quot;,&quot;blue&quot;),lty=1)&lt;br /&gt;title(&quot;Time to compute on my laptop&quot;)&lt;br /&gt;&lt;br /&gt;#plot 2&lt;br /&gt;plot(res[,1],res[,2]/res[,4],xlab=&quot;number of subjects&quot;,ylab=&quot;glm (or speedglm) speed/glmnet speed&quot;, type=&quot;l&quot;)&lt;br /&gt;lines(res[,1],res[,3]/res[,4], col=&quot;red&quot;)&lt;br /&gt;title(&quot;relative speed of glm (black)\n and speedglm (red) to glmnet&quot;)&lt;br /&gt;&lt;br /&gt;#plot 3&lt;br /&gt;par(mfrow=c(1,2))&lt;br /&gt;coef.glm = coef(fit1) #since I didn&#39;t est an intercept&lt;br /&gt;coef.speedglm = coef(fit2)&lt;br /&gt;coef.glmnet.attack = coef(fit3,s=min(fit3$lambda))[2:(nSubjects+1)]&lt;br /&gt;coef.glmnet.defend = coef(fit3,s=min(fit3$lambda))[(nSubjects+2):(2*nSubjects+1)]&lt;br /&gt;#true to glmnet&lt;br /&gt;plot(true.attack,coef.glmnet.attack,ylab=&quot;estimated beta&quot;,main=&quot;glmnet&quot;)&lt;br /&gt;plot(true.defend,coef.glmnet.defend,ylab=&quot;estimated beta&quot;,main=&quot;glmnet&quot;)&lt;br /&gt;#glm to glmnet&lt;br /&gt;plot(coef.glm[1:nSubjects],coef.glmnet.attack,ylab=&quot;from glmnet&quot;,xlab=&quot;from glm&quot;,main=&quot;attack&quot;)&lt;br /&gt;plot(coef.glm[(nSubjects+1):(2*nSubjects)],coef.glmnet.defend,ylab=&quot;from glmnet&quot;,xlab=&quot;from glm&quot;,main=&quot;defend&quot;)&lt;br /&gt;#glm to true&lt;br /&gt;plot(true.attack,coef.glm[1:nSubjects],ylab=&quot;estimated beta&quot;,main=&quot;glm&quot;)&lt;br /&gt;plot(true.defend,coef.glm[(nSubjects+1):(2*nSubjects)],ylab=&quot;estimated beta&quot;,main=&quot;glm&quot;)&lt;/span&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/8792304113130528029/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/8792304113130528029' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8792304113130528029'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8792304113130528029'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/dixon-and-coles-2-player-model-in-glm.html' title='Dixon and Coles&#39; 2-player model in glm, speedglm and glmnet'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYiR36T2QXU-2vkOfvzQAuADNWrD0NboHbgf35V8FYN4-jzumlkqmb_p16rfF1sMQUIWZ8ZRjPksqAl4-4inGJWhkLTZMFYPFNy5hRUxK_ZpdXXelqxYstiF0dp00jup1C59zR9w/s72-c/glm-comp-attack-a.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-8539813390328430016</id><published>2013-10-08T12:19:00.003-07:00</published><updated>2013-10-08T12:31:17.485-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="2-player"/><category scheme="http://www.blogger.com/atom/ns#" term="glm"/><category scheme="http://www.blogger.com/atom/ns#" term="glm-speedglm-glmnet comparison"/><category scheme="http://www.blogger.com/atom/ns#" term="multi-player"/><category scheme="http://www.blogger.com/atom/ns#" term="regression"/><title type='text'>Multiplayer problem revisited with glm vs speedglm vs glmnet</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Here I discuss a specific 
problem: using glm to estimate player &quot;strengths&quot; in a multi-player 
problem where the player pool is huge.&amp;nbsp; &lt;span style=&quot;font-family: inherit;&quot;&gt;This is part of a &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/search/label/glm-speedglm-glmnet%20comparison&quot;&gt;series of posts I did comparing glm, speedglm and glmnet&lt;/a&gt;.&amp;nbsp; And this is related to stuff I have been playing with regarding &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/search/label/2-player&quot;&gt;massive 2-player estimation problems&lt;/a&gt;.&lt;/span&gt;&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;Scenario&lt;/b&gt;&lt;br /&gt;
Imagine
 we have a series of competitions where each competition consists of 
nPlayers randomly chosen from a pool of nSubjects.&amp;nbsp; Each 
subject has a &#39;strength&#39; and the outcome of the competition is some 
function of the additive strengths.&amp;nbsp; Some examples might be:&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;players are pulling on a rope and we measure force (on um a scale of -Inf to Inf....).&amp;nbsp; y ~ normal(sum(strengths))&lt;/li&gt;
&lt;li&gt;players are playing a game where they score 0-10 (or so).&amp;nbsp; y ~ poisson(exp(sum(strengths)))&lt;/li&gt;
&lt;li&gt;players are playing a win/lose game.&amp;nbsp; y ~ binomial(logit(sum(strengths)))&lt;/li&gt;
&lt;/ul&gt;
Here I just use a normal to be simple.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Set up in glm framework&lt;/b&gt;&lt;br /&gt;
We
 don&#39;t want to treat the subjects at levels and player1, player2, etc as
 a factor since subject i could be player1, player2, etc in any one 
competition but they are still the same subject.&amp;nbsp; Instead we treat 
subject as a 0/1 explanatory variable.&amp;nbsp; 1 = subject was in competition. 0
 = they were not.&amp;nbsp; Our data consists of nSubjects explanatory variables 
with nPlayer 1s in each rows.&amp;nbsp; So...most of our explanatory variable 
data is all zeros and we are going to have a huge number of explanatory 
variables.&amp;nbsp; We can expect that glmnet will excel here.&lt;br /&gt;
&lt;br /&gt;
The R code below shows how to set up the simulated data and then set the
 model up for glm, speedglm and glmnet.&amp;nbsp; It&#39;s pretty similar to the R 
code from my previous posts.&amp;nbsp; But here I show some plots of estimated 
betas (subject strengths) versus true values, which requires getting the
 coefficients out of glmnet. &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/getting-coefficients-out-of-glmnet.html&quot;&gt;Read this post on what glmnet does, how to get coefficients out of glmnet and why I pass lambda=1e-6 into my glmnet call.&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Results of speed test (R code below)&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Now that I pass in lambda=1e-6, glmnet didn&#39;t get slower as nSubjects increased.&amp;nbsp; Wow.&amp;nbsp; It was basically instantaneous for these tests while glm took about a minute.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNxt4cFRTcWIwKh95F3jEGvMefFNFDRm9CoIshQNAoOmqJRo1G74Q06CbD3SwNqexEBGX2O2FejOuL2ie57bs6opmU2cMMJcJoeLYRe2D7F8-kI23rO-xCnKYWVaIECzIMft62Sw/s1600/glm-comp-part5a.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;299&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNxt4cFRTcWIwKh95F3jEGvMefFNFDRm9CoIshQNAoOmqJRo1G74Q06CbD3SwNqexEBGX2O2FejOuL2ie57bs6opmU2cMMJcJoeLYRe2D7F8-kI23rO-xCnKYWVaIECzIMft62Sw/s320/glm-comp-part5a.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&amp;nbsp;Relative speed correspondingly skyrockets for glm and speedglm versus glmnet for this problem.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEht-ZP3UdeihcqCja3Blc6qtf_6ZB7xunsa8E4NWah_vg7_JMVBblRX0yI-gkx1_O92LumFMK2S1v_K4FsG_UugLjzKGrqVWGfB8wzi5fUSGOCjUw7woKIZxWR-ZifC9n_h2O_EBA/s1600/glm-comp-part5b.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;299&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEht-ZP3UdeihcqCja3Blc6qtf_6ZB7xunsa8E4NWah_vg7_JMVBblRX0yI-gkx1_O92LumFMK2S1v_K4FsG_UugLjzKGrqVWGfB8wzi5fUSGOCjUw7woKIZxWR-ZifC9n_h2O_EBA/s320/glm-comp-part5b.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&amp;nbsp;Estimates however are basically identical.&amp;nbsp; First plot shows glmnet versus true and the next show glmnet versus glm and speedglm versus glm estimates.&amp;nbsp; Yes, they are on the 1-1 line.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8MaktaENpR87K9ZFJqeR_foqv7dHx07D5uA3pz7KHdyQNXn7NBe7VV89PUpcRRYELPR0AcX1ekDYlvQsEF7sq5cR3JwHJRmL9z-k5ix2Lw8yLjeaKQE1_udJjCcd8_7W0ezz41w/s1600/glm-comp-part5c.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8MaktaENpR87K9ZFJqeR_foqv7dHx07D5uA3pz7KHdyQNXn7NBe7VV89PUpcRRYELPR0AcX1ekDYlvQsEF7sq5cR3JwHJRmL9z-k5ix2Lw8yLjeaKQE1_udJjCcd8_7W0ezz41w/s1600/glm-comp-part5c.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;b&gt;R code&lt;/b&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;library(glmnet)&lt;br /&gt;library(speedglm)&lt;br /&gt;&lt;br /&gt;#3 players&lt;br /&gt;#Treat subject as a explanatory variable (x). There will be nSubject x variables&lt;br /&gt;#This allows us to take into account that subject 1 in the player1, player2, or player3 is the same subject&lt;br /&gt;nPlayers = 3&lt;br /&gt;n = 10000&lt;br /&gt;&lt;br /&gt;res=obj=c() &lt;br /&gt;for(nSubjects in c(100,200,500,1000,1500)){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #subject strength is drawn from a normal&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; beta=rnorm(nSubjects,0,1)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; levx=y=c() #levx is holder for player #; y is data&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; x = matrix(0,n,nSubjects) #x is the n x nSubjects explanatory variable matrix needed by glm&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; for(i in 1:n){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; #draw nPlayers randomly for each of the n competitions&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; levx=rbind(levx,sample(nSubjects, nPlayers, replace=FALSE))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x[i,levx[i,]]=1 #set x var for subject = 1 if subject is present in this competition&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; #outcome of competition is normal (could be binomial-win/loss, or poisson, or whatever)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; y=c(y,rnorm(1,sum(beta[levx[i,]])))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #set the colnames on the explanatory variables&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; colnames(x)=paste(&quot;X&quot;,1:nSubjects,sep=&quot;&quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dat = cbind(y=y,x)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dat = data.frame(dat) #glm wants a data frame&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; cat(nSubjects); cat(&quot; &quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #set up the formula&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fooform = &quot;y~-1&quot;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; for(i in 1:nSubjects) fooform=paste(fooform,&quot;+X&quot;,i,sep=&quot;&quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #fit glm&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; a=c(nSubjects, system.time(fit1&amp;lt;-glm(formula(fooform), data=dat))[1])&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; b=c(nSubjects, object.size(fit1))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #fit speedglm&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; a=c(a,system.time(fit2&amp;lt;-speedglm(formula(fooform), data=dat))[1])&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; b=c(b, object.size(fit2))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #fit glmnet&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #1 row for each player; col is just the player number; need to t() levx so as.vector works by row&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sx=sparseMatrix(rep(1:n,each=nPlayers),as.vector(t(levx)),x=1)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; a=c(a, system.time(fit3&amp;lt;-glmnet(sx, y, intercept=FALSE, lambda=1e-6))[1])&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; b=c(b, object.size(fit3))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; res=rbind(res,a)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; obj=rbind(obj,b)&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp; &lt;br /&gt;#plot 1&lt;br /&gt;plot(res[,1],res[,2],type=&quot;l&quot;, ylab=&quot;seconds&quot;, xlab=&quot;number of categories&quot;)&lt;br /&gt;lines(res[,1],res[,3],col=&quot;red&quot;,lty=2)&lt;br /&gt;lines(res[,1],res[,4],col=&quot;blue&quot;,lty=3)&lt;br /&gt;legend(&quot;topleft&quot;,c(&quot;glm&quot;,&quot;speedglm&quot;,&quot;glmnet&quot;),col=c(&quot;black&quot;,&quot;red&quot;,&quot;blue&quot;),lty=1)&lt;br /&gt;title(&quot;Time to compute on my laptop&quot;)&lt;br /&gt;&lt;br /&gt;#plot 2&lt;br /&gt;plot(res[,1],res[,2]/res[,4],xlab=&quot;number of subjects&quot;,ylab=&quot;glm (or speedglm) speed/glmnet speed&quot;, type=&quot;l&quot;)&lt;br /&gt;lines(res[,1],res[,3]/res[,4], col=&quot;red&quot;)&lt;br /&gt;title(&quot;relative speed of glm (black)\n and speedglm (red) to glmnet&quot;)&lt;br /&gt;&lt;br /&gt;#plot 3&lt;br /&gt;par(mfrow=c(3,1))&lt;br /&gt;coef.glm = coef(fit1) #since I didn&#39;t est an intercept&lt;br /&gt;coef.speedglm = coef(fit2)&lt;br /&gt;coef.glmnet = coef(fit3,s=min(fit3$lambda))[2:(nSubjects+1)]&lt;br /&gt;plot(beta,coef.glmnet,ylab=&quot;estimated beta&quot;,main=&quot;glmnet estimates vs true&quot;)&lt;br /&gt;plot(coef.glm,coef.glmnet,ylab=&quot;from glmnet&quot;,xlab=&quot;estimated beta from glm&quot;)&lt;br /&gt;plot(coef.glm,coef.speedglm,ylab=&quot;from speedglm&quot;,xlab=&quot;estimated beta from glm&quot;)&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/8539813390328430016/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/8539813390328430016' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8539813390328430016'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8539813390328430016'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/multiplayer-problem-revisited-with-glm.html' title='Multiplayer problem revisited with glm vs speedglm vs glmnet'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNxt4cFRTcWIwKh95F3jEGvMefFNFDRm9CoIshQNAoOmqJRo1G74Q06CbD3SwNqexEBGX2O2FejOuL2ie57bs6opmU2cMMJcJoeLYRe2D7F8-kI23rO-xCnKYWVaIECzIMft62Sw/s72-c/glm-comp-part5a.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-7242589497644831392</id><published>2013-10-08T11:29:00.000-07:00</published><updated>2013-10-10T17:19:27.802-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="big data"/><category scheme="http://www.blogger.com/atom/ns#" term="glm"/><category scheme="http://www.blogger.com/atom/ns#" term="glm-speedglm-glmnet comparison"/><category scheme="http://www.blogger.com/atom/ns#" term="lasso regression"/><category scheme="http://www.blogger.com/atom/ns#" term="regression"/><title type='text'>Getting coefficients out of glmnet</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Surprisingly, figuring out how to get the coefficients out of a &lt;a href=&quot;http://cran.r-project.org/web/packages/glmnet/index.html&quot;&gt;glmnet&lt;/a&gt; fit&amp;nbsp; took me about 2 hours of reading posts on stackexchange and R forums.&amp;nbsp; I would have given up except I saw a blog where someone said they used glmnet to do glms, so I knew it was possible.&amp;nbsp; Turns out it is really easy but you need to know what coef(glmnet.fit) is outputting.&amp;nbsp; The problem was that I was avoiding reading the paper accompanying glmnet and couldn&#39;t really understand the output until I bucked up and read the paper.&amp;nbsp; &lt;span style=&quot;font-family: inherit;&quot;&gt;This is part of a &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/search/label/glm-speedglm-glmnet%20comparison&quot;&gt;series of posts I did comparing glm, speedglm and glmnet&lt;/a&gt;.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
This paper describes the glmnet package and its algorithms&lt;br /&gt;
Jerome Friedman, Trevor Hastie, Robert Tibshirani (2010). Regularization
 Paths for Generalized Linear Models via Coordinate Descent. Journal of 
Statistical Software, 33(1), 1-22. URL &lt;a href=&quot;http://www.jstatsoft.org/v33/i01/&quot;&gt;http://www.jstatsoft.org/v33/i01/&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
glmnet is used to find a reduced regression model that leads to minimized mean squared error---so you have many, many explanatory variables but most of these don&#39;t increase the predictive value of the model and you want to find the optimal reduced model.&amp;nbsp; The parameter &#39;lambda&#39; is a measure of the model size.&amp;nbsp; When you type coef(fit) after a glmnet fit, you get all the fits for the lambda used.&amp;nbsp; The first columns are for small models, so most of the coef are 0.&amp;nbsp; As you increase column number, the models get bigger and bigger.&amp;nbsp; The idea, in a normal glmnet use, is to find the size of model that minimizes mean squared error.&amp;nbsp; Here&#39;s one of the plots from their paper showing mean square error of predictions (cross-validation) versus size of model fit (with glmnet):&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjiFZthGANgcV6Fw4EyHBApHPyq7pogzr2-Hu7qkFdu60yI6TZiQrzU_a0Jl86d5xCwBA3N2zcqNqDjIRyDq8p6CAycjMTP7I7a1OFl35eHyXNNK4t_8x0Jgo5sMFRxFIykHGP9BA/s1600/glmnet-lambda.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjiFZthGANgcV6Fw4EyHBApHPyq7pogzr2-Hu7qkFdu60yI6TZiQrzU_a0Jl86d5xCwBA3N2zcqNqDjIRyDq8p6CAycjMTP7I7a1OFl35eHyXNNK4t_8x0Jgo5sMFRxFIykHGP9BA/s1600/glmnet-lambda.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
In this example they had 100 explanatory variables.&amp;nbsp; The size of the model is at the top.&amp;nbsp; The corresponding lambda is at the bottom.&amp;nbsp; In normal use, you do some cross-validation (glmnet has functions for that) and use that to make a plot like above and select the lambda (size of model) that minimizes the mean squared error for your problem.&lt;br /&gt;
&lt;br /&gt;
The output for coef(fit), where fit is a glmnet fit, is a 1+#coefs&amp;nbsp; X #lambdas matrix.&amp;nbsp; You can call coef() with the argument s to specify the lambda level you want.&amp;nbsp; Why &quot;s&quot; and not &quot;lambda&quot;??&amp;nbsp; Anyhow &quot;s&quot; is &quot;lambda&quot; in the coef call.&amp;nbsp; So let&#39;s say I wanted the coefficients at lambda = log(-2), about the minimum in the figure above.&amp;nbsp;&amp;nbsp; I would use the following:&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;fit3&amp;lt;-glmnet(sx, y)&lt;br /&gt;coef.glmnet = coef(fit3, s=log(-2))[2:(nSubjects+1)]&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
However, I am not using glmnet that way.&amp;nbsp; I&#39;m not trying to find a reduced model. I want to fit a saturated model---meaning I want to estimate all the coefficients.&amp;nbsp; I want an estimate of strength for every subject in my model.&amp;nbsp; Though I suppose 0 is an estimate, I don&#39;t want that.&amp;nbsp; So I want to force glmnet to fit the saturated model (careful, sometimes you do need to fix a coef to 0 to have a solveable model; e.g. models with factors with multiple levels).&lt;br /&gt;
&lt;br /&gt;
I had trouble figuring out how to force glmnet to do this.&amp;nbsp; &lt;span style=&quot;color: blue;&quot;&gt;[update: turns out that setting lambda=0 makes glmnet return the &quot;glm&quot; parameters.&amp;nbsp; See below.]&amp;nbsp;&lt;/span&gt; argument &lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;lambda.min.ratio&lt;/span&gt; should do the trick but seemed to have no effect. However passing in argument &lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;lambda&lt;/span&gt; to set your own lambda values seems to work.&amp;nbsp; Friedman et al (2010) says to not pass in just one lambda value because the algorithm works better with a &quot;warm start&quot;.&amp;nbsp; Hmm, I&#39;m not sure what a &quot;warm start&quot; is but my guess is that it is a saturated model.&amp;nbsp; In other words, that the algorithm works better is you start with the full model and work down.&amp;nbsp;&amp;nbsp; So...I&#39;m just going to start with the full model.&amp;nbsp; &lt;i&gt;Need to make sure that the full model is identifiable!&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
I should be able to compute the lambda for the saturated model and send 
that to glmnet, but I couldn&#39;t figure out how to compute that.&amp;nbsp; So after some futzing, it seemed like passing in &lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;lambda=1e-6&lt;/span&gt; forced glmnet to fit the saturated model for my toy problems.&amp;nbsp; So my call to glmnet and corresponding coef() call looks like so:&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;fit3&amp;lt;-glmnet(sx, y, lambda=1e-6)&lt;br /&gt;coef.glmnet = coef(fit3)&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
I don&#39;t need to pass &lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;s&lt;/span&gt; into coef(fit) since I only have 1 column because I passed in one value of lambda.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Update, a week later&lt;/b&gt;&lt;br /&gt;
Fitting the saturated or near-saturated models worked for most of my test cases---until I tried to use it on real soccer match data which has a clustered structure.&amp;nbsp; &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/dixon-and-coles-2-player-model-fit-with.html&quot;&gt;See this post&lt;/a&gt;. &amp;nbsp;&lt;b&gt; &lt;/b&gt;In the process of trying to come up with a work-around for the problems &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/dixon-and-coles-2-player-model-with.html&quot;&gt;explored more fully here&lt;/a&gt;, I came across a forum post where someone wrote that you can pass in lambda=0, to get glmnet to duplicate the behavior of glm. I had already tried passing in lambda really small to get it to fit the saturated model.&amp;nbsp; The estimates were almost exactly the same but not quite and I ran into the problem that glmnet complained when I gave it a saturated model that is non-identifiable.&amp;nbsp; glm deals with this by setting one of the factor coefficients to 0 to make the model identifiable, but I couldn&#39;t figure out how to set that constraint for glmnet.&amp;nbsp; But turns out passing in lambda=0 works just fine for those non-identifiable models.&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/7242589497644831392/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/7242589497644831392' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/7242589497644831392'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/7242589497644831392'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/getting-coefficients-out-of-glmnet.html' title='Getting coefficients out of glmnet'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjiFZthGANgcV6Fw4EyHBApHPyq7pogzr2-Hu7qkFdu60yI6TZiQrzU_a0Jl86d5xCwBA3N2zcqNqDjIRyDq8p6CAycjMTP7I7a1OFl35eHyXNNK4t_8x0Jgo5sMFRxFIykHGP9BA/s72-c/glmnet-lambda.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-4414040175835760982</id><published>2013-10-07T15:05:00.002-07:00</published><updated>2013-10-08T11:37:05.646-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="big data"/><category scheme="http://www.blogger.com/atom/ns#" term="glm"/><category scheme="http://www.blogger.com/atom/ns#" term="glm-speedglm-glmnet comparison"/><category scheme="http://www.blogger.com/atom/ns#" term="regression"/><title type='text'>glm, speedglm, glmnet comparison (Part 4: models with a few categorical variables but many levels)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/glm-speedglm-glmnet-comparison-part-3.html&quot;&gt;Part 3&lt;/a&gt; talked about models with many categorical variables but fairly low numbers of categories within those variables.&amp;nbsp; &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/glm-speedglm-glmnet-comparison-part-2.html&quot;&gt;Part 2&lt;/a&gt; discussed that the size of the relative size of the model matrix compared to its sparse matrix representation scales with levels/2, so we might expect that glm would get even worse relative to glmnet as we try to use it to estimate a model with categorical variables where there are many (1000s or 10000s) of levels for the variable.&amp;nbsp; &lt;span style=&quot;font-family: inherit;&quot;&gt;This is part of a &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/search/label/glm-speedglm-glmnet%20comparison&quot;&gt;series of posts I did comparing glm, speedglm and glmnet&lt;/a&gt;.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
In this test, I use again n=10,000.&amp;nbsp; I use 2 categorical explanatory variables and allow the number of levels to go up. &lt;br /&gt;
&lt;br /&gt;
Speed comparison&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivzRsZoD2PE1AsMY9m5zSCNL_Q8DcPjauAwtKLZph4zcW4XV03l1OooGZgwMgzOcUskmYFjEaQDNnZoEQNWE4L__pSXz3yHeUF5SDOCfIqoTew4Kv_STSXsr6LE3w0OdC_YQRENw/s1600/glm-comp-part4a.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivzRsZoD2PE1AsMY9m5zSCNL_Q8DcPjauAwtKLZph4zcW4XV03l1OooGZgwMgzOcUskmYFjEaQDNnZoEQNWE4L__pSXz3yHeUF5SDOCfIqoTew4Kv_STSXsr6LE3w0OdC_YQRENw/s1600/glm-comp-part4a.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&amp;nbsp;Here&#39;s the relative comparison.&amp;nbsp; glm is getting slower and slower relative to glmnet as the number of categories goes up.&amp;nbsp; For 1000 categories (and 2 factors), it was 750 times slower. &lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhohB5quOadxWo2UOWrrBC-TL1L5cPpx7B4-0W2uIldbmW1moY-xQhrU9az7F7dvHKBm3_5hsYr2yMtGL4ep8FhJWKd1_kRepDA6rnXcJeeius-HN0nIOQ9VU98YufJn2LqA3C8DA/s1600/glm-comp-part4b.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhohB5quOadxWo2UOWrrBC-TL1L5cPpx7B4-0W2uIldbmW1moY-xQhrU9az7F7dvHKBm3_5hsYr2yMtGL4ep8FhJWKd1_kRepDA6rnXcJeeius-HN0nIOQ9VU98YufJn2LqA3C8DA/s1600/glm-comp-part4b.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
bottom line is for speedglm.&amp;nbsp; It&#39;s not red as the title suggests.&amp;nbsp; Little jiggle for glm at 200 is because glmnet was so fast so didn&#39;t get good speed estimate (likely affected by surfing I was doing while running the test).&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;RAM notes&lt;/b&gt;&lt;br /&gt;
At about 2500 categories, I use up the 8M of RAM on my laptop with glm.&amp;nbsp; There is no discernible jump in RAM use at 2500 categories for glmnet.&amp;nbsp; I don&#39;t have a good way to measure RAM use during the function calls.&amp;nbsp; I can watch it using the Windows performance monitor while running code, but I don&#39;t know how to get the max memory used with R code.&amp;nbsp; Rprofmem() didn&#39;t seem to get me what I wanted nor does gc().&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;R code&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
library(glmnet)&lt;br /&gt;
library(speedglm)&lt;br /&gt;
&lt;br /&gt;
n = 10000&lt;br /&gt;
facs = 2&lt;br /&gt;
&lt;br /&gt;
res=obj=c()&lt;br /&gt;
for(levs in c(50,100,200,300,500,1000)){&lt;br /&gt;
&amp;nbsp; beta=matrix(rnorm(levs*facs,0,1),levs,facs)&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; levx = c()&lt;br /&gt;
&amp;nbsp; for(i in 1:facs) levx=cbind(levx,sample(levs,n,replace=TRUE))&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; y &amp;lt;- apply(levx, 1, function(x){ sum(beta[x+seq(0,10*(facs-1),by=10)]) }) + rnorm(n)&lt;br /&gt;
&amp;nbsp; x = data.frame(levx)&lt;br /&gt;
&amp;nbsp; for(i in 1:facs) x[,i]=factor(x[,i],levels=1:levs)&lt;br /&gt;
&amp;nbsp; dat = cbind(y=y,x)&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; cat(levs);cat(&quot;\n&quot;)&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; #set up the formula&lt;br /&gt;
&amp;nbsp; fooform = &quot;y~-1&quot;&lt;br /&gt;
&amp;nbsp; for(i in 1:facs) fooform=paste(fooform,&quot;+X&quot;,i,sep=&quot;&quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; #fit glm&lt;br /&gt;
&amp;nbsp; a=c(levs, system.time(fit&amp;lt;-glm(formula(fooform), data=dat))[1])&lt;br /&gt;
&amp;nbsp; b=c(levs, object.size(fit))&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; #fit speedglm&lt;br /&gt;
&amp;nbsp; a=c(a,system.time(fit&amp;lt;-speedglm(as.formula(fooform), data=dat))[1])&lt;br /&gt;
&amp;nbsp; b=c(b, object.size(fit))&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
&amp;nbsp; #fit glmnet&lt;br /&gt;
&amp;nbsp; sx=sparseMatrix(rep(1:n,facs),as.vector(levx+matrix(seq(0,levs*(facs-1),by=levs),n,facs,byrow=TRUE)),x=1)&lt;br /&gt;
&amp;nbsp; a=c(a, system.time(fit&amp;lt;-glmnet(sx, y))[1])&lt;br /&gt;
&amp;nbsp; b=c(b, object.size(fit))&lt;br /&gt;
&amp;nbsp; &lt;br /&gt;
res=rbind(res,a)&lt;br /&gt;
obj=rbind(obj,b)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#plot 1&lt;br /&gt;
plot(res[,1],res[,2],type=&quot;l&quot;, ylab=&quot;seconds&quot;, xlab=&quot;number of categories&quot;)&lt;br /&gt;
lines(res[,1],res[,3],col=&quot;red&quot;,lty=2)&lt;br /&gt;
lines(res[,1],res[,4],col=&quot;blue&quot;,lty=3)&lt;br /&gt;
legend(&quot;topleft&quot;,c(&quot;glm&quot;,&quot;speedglm&quot;,&quot;glmnet&quot;),col=c(&quot;black&quot;,&quot;red&quot;,&quot;blue&quot;),lty=1)&lt;br /&gt;
title(paste(facs,&quot;explanatory variables&quot;))&lt;br /&gt;
&lt;br /&gt;
#plot 2&lt;br /&gt;
plot(res[,1],res[,2]/res[,4],xlab=&quot;number of categories&quot;,ylab=&quot;glm (or speedglm) speed/glmnet speed&quot;, type=&quot;l&quot;)&lt;br /&gt;
lines(res[,1],res[,3]/res[,4], col=&quot;red&quot;)&lt;br /&gt;
title(&quot;relative speed of glm (black) and speedglm (red) to glmnet&quot;)&lt;br /&gt;
&lt;br /&gt;
#plot 2&lt;br /&gt;
plot(obj[,1],log(obj[,2]),type=&quot;l&quot;, ylab=&quot;object size (log(M))&quot;, xlab=&quot;number of explanatory variables&quot;,ylim=c(10,23))&lt;br /&gt;
lines(obj[,1],log(obj[,3]),col=&quot;red&quot;,lty=2)&lt;br /&gt;
lines(obj[,1],log(obj[,4]),col=&quot;blue&quot;,lty=3)&lt;br /&gt;
abline(h=log(8042*1e6))&lt;br /&gt;
abline(h=log(2000*1e6))&lt;br /&gt;
legend(&quot;topleft&quot;,c(&quot;glm&quot;,&quot;speedglm&quot;,&quot;glmnet&quot;),col=c(&quot;black&quot;,&quot;red&quot;,&quot;blue&quot;),lty=1)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/4414040175835760982/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/4414040175835760982' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/4414040175835760982'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/4414040175835760982'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/glm-speedglm-glmnet-comparison-part-4.html' title='glm, speedglm, glmnet comparison (Part 4: models with a few categorical variables but many levels)'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivzRsZoD2PE1AsMY9m5zSCNL_Q8DcPjauAwtKLZph4zcW4XV03l1OooGZgwMgzOcUskmYFjEaQDNnZoEQNWE4L__pSXz3yHeUF5SDOCfIqoTew4Kv_STSXsr6LE3w0OdC_YQRENw/s72-c/glm-comp-part4a.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-2738743211827223066</id><published>2013-10-07T14:19:00.001-07:00</published><updated>2013-10-08T11:36:50.133-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="big data"/><category scheme="http://www.blogger.com/atom/ns#" term="glm"/><category scheme="http://www.blogger.com/atom/ns#" term="glm-speedglm-glmnet comparison"/><category scheme="http://www.blogger.com/atom/ns#" term="regression"/><title type='text'>glm, speedglm, glmnet comparison (Part 3: models with many categorical explanatory variables)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
In &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/glm-speedglm-versus-glmnet-comparison.html&quot;&gt;Part 1&lt;/a&gt; of the glm, speedglm, glmnet comparison, I looked at models with continuous explanatory variables.&amp;nbsp; In Part 3, I look at speeds for models with lots of categorical explanatory variables.&amp;nbsp; This will use the sparse matrix representation of a model matrix for models with categorical explanatory variables.&amp;nbsp; &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/glm-speedglm-glmnet-comparison-part-2.html&quot;&gt;Part 2&lt;/a&gt; talked about that.&amp;nbsp; &lt;span style=&quot;font-family: inherit;&quot;&gt;This is part of a &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/search/label/glm-speedglm-glmnet%20comparison&quot;&gt;series of posts I did comparing glm, speedglm and glmnet&lt;/a&gt;.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Here I have a model that looks like this&lt;br /&gt;
&lt;br /&gt;
y ~ factor1 + factor2 + factor3 + ... + factor-k&lt;br /&gt;
&lt;br /&gt;
where k is big or # of levels gets big.&amp;nbsp; This is the case where the model matrix gets huge, and we might expect glm to really bog down.&amp;nbsp; &lt;br /&gt;
&lt;br /&gt;
First test.&amp;nbsp; # of categorical explanatory variables gets big.&amp;nbsp; I set n to 10,000 and number of levels per explanatory variable at 10.&amp;nbsp; So yes glm is getting really slow relative to glm.&amp;nbsp; In fact, I didn&#39;t do more than 300 variables for glm since the speed was going down so much.&amp;nbsp; speedglm also shows trouble as number of explanatory variables gets big.&amp;nbsp; R code to generate this is below.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDywiwUYStON4ftordAEBUqcLSLtbACQyCNxNX_hE4Sj6D-msJPa0rriG2f_vZq2QIH2XwFf9nBelwQ7MSG6JYF4n2f6TMb9TEAKVqUKmfXk4W_oj5IzZdYxtPOQzCFFzeSD4MEQ/s1600/glm-comp-part3a.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDywiwUYStON4ftordAEBUqcLSLtbACQyCNxNX_hE4Sj6D-msJPa0rriG2f_vZq2QIH2XwFf9nBelwQ7MSG6JYF4n2f6TMb9TEAKVqUKmfXk4W_oj5IzZdYxtPOQzCFFzeSD4MEQ/s1600/glm-comp-part3a.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
But look at glm with categorical explanatory variables versus continuous explanatory variables.&amp;nbsp; Yipes.&amp;nbsp; Using glm with large numbers (1000s) of categorical explanatory variables is not going to work.&amp;nbsp; We are slowing down quickly and using up RAM.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-MBPFBmmR8am1ZXmuIo7GXb6vBM6bKqqKQ5-KcNliTrDknpa3ZN0TZXtaVmbv1F90VM_QZVvnYxFoMmZ4jRDHz80dTHWlC6FsnTEJC3ciGwJoUQ0-3HWzZJDFYIGp8T_UYSKcUw/s1600/glm-comp-part3b.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-MBPFBmmR8am1ZXmuIo7GXb6vBM6bKqqKQ5-KcNliTrDknpa3ZN0TZXtaVmbv1F90VM_QZVvnYxFoMmZ4jRDHz80dTHWlC6FsnTEJC3ciGwJoUQ0-3HWzZJDFYIGp8T_UYSKcUw/s1600/glm-comp-part3b.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is the object size&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5vGpCn_uIFOn6jxHWmL_KB1O2iYb29S6MKctSxt4_f4EdrZ6qoTwGfKLrXStTZxKO_0YHnbvaeXQkyUOmxu35OTQXlK_DxEUr-rQFeZ43Eis0l40agV3MllmzzNAAjYBt-89IFw/s1600/glm-comp-part3c.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5vGpCn_uIFOn6jxHWmL_KB1O2iYb29S6MKctSxt4_f4EdrZ6qoTwGfKLrXStTZxKO_0YHnbvaeXQkyUOmxu35OTQXlK_DxEUr-rQFeZ43Eis0l40agV3MllmzzNAAjYBt-89IFw/s1600/glm-comp-part3c.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;R code&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;code&gt;library(glmnet)&lt;br /&gt;library(speedglm)&lt;br /&gt;&lt;br /&gt;n = 10000&lt;br /&gt;levs = 10&lt;br /&gt;&lt;br /&gt;res=obj=c()&lt;br /&gt;for(facs in c(50,100,200,300,500,1000)){&lt;br /&gt;&amp;nbsp; beta=matrix(rnorm(levs*facs,0,1),levs,facs)&lt;br /&gt;&amp;nbsp; &lt;br /&gt;&amp;nbsp; levx = c()&lt;br /&gt;&amp;nbsp; for(i in 1:facs) levx=cbind(levx,sample(levs,n,replace=TRUE))&lt;br /&gt;&amp;nbsp; &lt;br /&gt;&amp;nbsp; y &amp;lt;- apply(levx, 1, function(x){ sum(beta[x+seq(0,10*(facs-1),by=10)]) }) + rnorm(n)&lt;br /&gt;&amp;nbsp; x = data.frame(levx)&lt;br /&gt;&amp;nbsp; for(i in 1:facs) x[,i]=factor(x[,i],levels=1:levs)&lt;br /&gt;&amp;nbsp; dat = cbind(y=y,x)&lt;br /&gt;&lt;br /&gt;&amp;nbsp; cat(facs);cat(&quot;\n&quot;)&lt;br /&gt;&amp;nbsp; &lt;br /&gt;&amp;nbsp; #set up the formula&lt;br /&gt;&amp;nbsp; fooform = &quot;y~-1&quot;&lt;br /&gt;&amp;nbsp; for(i in 1:facs) fooform=paste(fooform,&quot;+X&quot;,i,sep=&quot;&quot;)&lt;br /&gt;&lt;br /&gt;&amp;nbsp; #fit glm&lt;br /&gt;&amp;nbsp; #don&#39;t do glm if facs&amp;gt;500; too slow&lt;br /&gt;&amp;nbsp; if(facs&amp;lt;500){&lt;br /&gt;&amp;nbsp; a=c(facs, system.time(fit&amp;lt;-glm(formula(fooform), data=dat))[1])&lt;br /&gt;&amp;nbsp; b=c(facs, object.size(fit))&lt;br /&gt;&amp;nbsp; }else{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; a=c(facs, NA)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; b=c(facs, NA)&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp; &lt;br /&gt;&amp;nbsp; #fit speedglm&lt;br /&gt;&amp;nbsp; a=c(a,system.time(fit&amp;lt;-speedglm(as.formula(fooform), data=dat))[1])&lt;br /&gt;&amp;nbsp; b=c(b, object.size(fit))&lt;br /&gt;&amp;nbsp; &lt;br /&gt;&amp;nbsp; #fit glmnet&lt;br /&gt;&amp;nbsp; sx=sparseMatrix(rep(1:n,facs),as.vector(levx+matrix(seq(0,levs*(facs-1),by=levs),n,facs,byrow=TRUE)),x=1)&lt;br /&gt;&amp;nbsp; a=c(a, system.time(fit&amp;lt;-glmnet(sx, y))[1])&lt;br /&gt;&amp;nbsp; b=c(b, object.size(fit))&lt;br /&gt;&amp;nbsp; &lt;br /&gt;res=rbind(res,a)&lt;br /&gt;obj=rbind(obj,b)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;#plot 1&lt;br /&gt;plot(res[,1],res[,2],type=&quot;l&quot;, ylab=&quot;seconds&quot;, xlab=&quot;number of explanatory variables&quot;,ylim=c(0,500))&lt;br /&gt;lines(res[,1],res[,3],col=&quot;red&quot;,lty=2)&lt;br /&gt;lines(res[,1],res[,4],col=&quot;blue&quot;,lty=3)&lt;br /&gt;legend(&quot;topleft&quot;,c(&quot;glm&quot;,&quot;speedglm&quot;,&quot;glmnet&quot;),col=c(&quot;black&quot;,&quot;red&quot;,&quot;blue&quot;),lty=1)&lt;br /&gt;&lt;br /&gt;#plot 2&lt;br /&gt;plot(obj[,1],log(obj[,2]),type=&quot;l&quot;, ylab=&quot;object size (log(M))&quot;, xlab=&quot;number of explanatory variables&quot;,ylim=c(10,23))&lt;br /&gt;lines(obj[,1],log(obj[,3]),col=&quot;red&quot;,lty=2)&lt;br /&gt;lines(obj[,1],log(obj[,4]),col=&quot;blue&quot;,lty=3)&lt;br /&gt;abline(h=log(8042*1e6))&lt;br /&gt;abline(h=log(2000*1e6))&lt;br /&gt;legend(&quot;topleft&quot;,c(&quot;glm&quot;,&quot;speedglm&quot;,&quot;glmnet&quot;),col=c(&quot;black&quot;,&quot;red&quot;,&quot;blue&quot;),lty=1)&lt;br /&gt;&lt;br /&gt;
&lt;!--500--&gt;&lt;!-----&gt;&lt;/code&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/2738743211827223066/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/2738743211827223066' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/2738743211827223066'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/2738743211827223066'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/glm-speedglm-glmnet-comparison-part-3.html' title='glm, speedglm, glmnet comparison (Part 3: models with many categorical explanatory variables)'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDywiwUYStON4ftordAEBUqcLSLtbACQyCNxNX_hE4Sj6D-msJPa0rriG2f_vZq2QIH2XwFf9nBelwQ7MSG6JYF4n2f6TMb9TEAKVqUKmfXk4W_oj5IzZdYxtPOQzCFFzeSD4MEQ/s72-c/glm-comp-part3a.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-3066948201272546586</id><published>2013-10-07T12:53:00.000-07:00</published><updated>2013-10-08T12:49:18.669-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="big data"/><category scheme="http://www.blogger.com/atom/ns#" term="glm"/><category scheme="http://www.blogger.com/atom/ns#" term="glm-speedglm-glmnet comparison"/><category scheme="http://www.blogger.com/atom/ns#" term="regression"/><title type='text'>Writing a model matrix in sparse matrix form</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;The last post &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/glm-speedglm-versus-glmnet-comparison.html&quot;&gt;glm, speedglm, glmnet comparison (part 1)&lt;/a&gt; showed that glmnet gives us a big speed and object size advantage for a vanilla regression when we have many explanatory variables (1000s).&amp;nbsp; In my next posts, I will look at models with lots of factors.&amp;nbsp; Here glmnet has an even bigger advantage because we can use sparse matrix notation to pass in our model.&amp;nbsp; Before using sparse matrices with glmnet, I want to review how to specify a sparse matrix in R.&amp;nbsp; This uses the &lt;a href=&quot;http://www.google.com/url?sa=t&amp;amp;rct=j&amp;amp;q=&amp;amp;esrc=s&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CCwQFjAA&amp;amp;url=http%3A%2F%2Fcran.r-project.org%2Fpackage%3DMatrix&amp;amp;ei=nmFUUsCGM9HSiALltYCoCg&amp;amp;usg=AFQjCNFWKX9U2LNbd-V8BJ6UqyHw3f5xxg&amp;amp;sig2=iJn_IJ2rXKRSgWQvOUipPw&amp;amp;bvm=bv.53760139,d.cGE&quot;&gt;Matrix R package&lt;/a&gt;.&amp;nbsp; This is part of a &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/search/label/glm-speedglm-glmnet%20comparison&quot;&gt;series of posts I did comparing glm, speedglm and glmnet&lt;/a&gt;.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;Let&#39;s say we had 5 data points and 2 explanatory variables X1 and X2.&amp;nbsp; Each has 2 levels, &quot;a&quot; and &quot;b&quot;.&amp;nbsp; Our data look like so, a 5x2 matrix:&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;X1 X2
a  a
b  a
b  a
b  b
a  b&lt;/pre&gt;
&lt;br /&gt;
glm will represent this will a model matrix that will expand that out into binary form with a column for each level-factor combination.  It&#39;ll look something like this*, a 2x2x5 matrix:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;X1a X1b X2a X2b
1   0   1   0
0   1   1   0
0   1   1   0
0   1   0   1
1   0   0   1&lt;/pre&gt;
&lt;br /&gt;
*Ok, assume that no intercept is estimated and ignore that we have to set one factor to 0 (or something) to make the problem identifiable.&lt;br /&gt;
&lt;br /&gt;
This model matrix will have (#data points) rows and (#factors * #levels) columns AND it is almost all zeros.  As the number of factors or levels gets big, this will get very wasteful and will will run out of RAM and everything slows down.
&lt;br /&gt;
&lt;br /&gt;
We can represent this more concisely in sparse matrix form.  For sparse matrix form, we just need the row and columns that are 1s.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;row col
1   1
2   2
3   2
4   2
5   1
1   3
2   3
3   3
4   4
5   4&lt;/pre&gt;
&lt;br /&gt;
The sparse matrix representation has (#factors * #data points) rows and 2 cols (a col for row # and one for col #). The ratio of the size of the original model matrix to the sparse model matrix is #levels/2.  So as number of levels and factors gets big, sparse model matrix form will save lots of space.&lt;/div&gt;
&lt;/div&gt;
&lt;b&gt;How to write the model matrix in R&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Here&#39;s a little piece of code to make the sparse matrix from a data frame where each column of the data frame is a factor.&amp;nbsp; It uses the numeric representation of a factor, so as.numeric(factor).&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-size: x-small;&quot;&gt;x=data.frame(X1=c(&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;a&quot;), X2=c(&quot;a&quot;,&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;b&quot;))&lt;br /&gt;cols=0&lt;br /&gt;sx=c() #the sparse matrix representation&lt;br /&gt;for(i in 1:ncol(x)){&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&lt;span style=&quot;font-size: x-small;&quot;&gt;&amp;nbsp; #we need to add on the numbers of cols used for previous factors&lt;br /&gt;&amp;nbsp; sx=rbind(sx,cbind(1:nrow(x),as.numeric(x[,i])+cols))&lt;br /&gt;&amp;nbsp; cols = cols + length(levels(x[,i]))&lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/3066948201272546586/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/3066948201272546586' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3066948201272546586'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3066948201272546586'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/glm-speedglm-glmnet-comparison-part-2.html' title='Writing a model matrix in sparse matrix form'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-1512759080710956135</id><published>2013-10-03T19:47:00.000-07:00</published><updated>2013-10-08T12:50:41.063-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="big data"/><category scheme="http://www.blogger.com/atom/ns#" term="glm"/><category scheme="http://www.blogger.com/atom/ns#" term="glm-speedglm-glmnet comparison"/><category scheme="http://www.blogger.com/atom/ns#" term="regression"/><title type='text'>glm, speedglm versus glmnet comparison tests (part 1)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
I spent part of today learning &lt;a href=&quot;http://cran.r-project.org/web/packages/glmnet/index.html&quot;&gt;glmnet&lt;/a&gt;, another R package for speedier generalized linear regression.&amp;nbsp;&amp;nbsp; &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/10/getting-coefficients-out-of-glmnet.html&quot;&gt;Read this post for some background on what glmnet does&lt;/a&gt; This is for massive linear regression problems where you are trying to find a minimal model and where the model matrix is so huge that it is maxing out your RAM and the computation is getting slow.&amp;nbsp; The RAM is the kicker.&amp;nbsp; If the computation is just slow, you can wait but if it requires more RAM than you have then you are stuck.&amp;nbsp; glm() is very RAM hungry due to the model.matrix that it constructs.&amp;nbsp; This gets enormous as the number of response variables gets huge.&amp;nbsp; This post is based on this one by someone else &lt;a href=&quot;http://www.johnmyleswhite.com/notebook/2011/10/31/using-sparse-matrices-in-r/&quot;&gt;using-sparse-matrices-in-r&lt;/a&gt;&amp;nbsp;&amp;nbsp; This is the first of a &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/search/label/glm-speedglm-glmnet%20comparison&quot;&gt;whole series of posts I did comparing glm, speedglm and glmnet&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Speed test #1&amp;nbsp; My first speed test used a simple gaussian errors regression with continuous response variables (meaning not factors, not categorical).&amp;nbsp; First plot shows speed in seconds (on my laptop).&amp;nbsp; Model is y ~ x1 + x2 + ... + xn, family=&quot;gaussian&quot;.&amp;nbsp; R code for the test is below (and shows how to set each up for glm(), speedglm() and glmnet() ).&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjrTSK7-Qd7fksVNkI-3_N2_2g3ykea9S4_N-_ERfiKo75zitb6SbvKlEBK0mziHMhT-pKexnn1Mdi3DXnbT9pg5C6Xn2yWFahgujdh0AofhxorWKokFTCpCsjNOnFYl-h6KOlhAQ/s1600/glm-comparison-par1a.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;293&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjrTSK7-Qd7fksVNkI-3_N2_2g3ykea9S4_N-_ERfiKo75zitb6SbvKlEBK0mziHMhT-pKexnn1Mdi3DXnbT9pg5C6Xn2yWFahgujdh0AofhxorWKokFTCpCsjNOnFYl-h6KOlhAQ/s400/glm-comparison-par1a.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
Plot 2 shows object size.&amp;nbsp; The top 2 lines show 2M RAM and 8M RAM &lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJPyIn5tBYl4temTIBoqyw4zuocGIeyOzkHkmD1yyzddd4IK4w5-dKRiINZGqze86squoQRpSeQLEc1UrMovO05v4XDE5UTrYa72BND2R4geHYM2D828Q9ANbQLSKsYinupTCEtg/s1600/glm-comp-part1b.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;293&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJPyIn5tBYl4temTIBoqyw4zuocGIeyOzkHkmD1yyzddd4IK4w5-dKRiINZGqze86squoQRpSeQLEc1UrMovO05v4XDE5UTrYa72BND2R4geHYM2D828Q9ANbQLSKsYinupTCEtg/s400/glm-comp-part1b.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
library(glmnet)&lt;br /&gt;
library(speedglm)&lt;br /&gt;
n =10000 #number of data points (y)&lt;br /&gt;
res = obj = c() #holders for output&lt;br /&gt;
#p is number of response variables &lt;br /&gt;
for(p in c(100,500,1000,1500,2000)){&lt;br /&gt;
#create random covariate values &lt;br /&gt;
x = matrix(rnorm(n * p), n, p)&lt;br /&gt;
beta = rnorm(p) #random betas&lt;br /&gt;
y = x %*% beta + rnorm(n) #the response variable&lt;br /&gt;
&lt;br /&gt;
cat(p);cat(&quot;\n&quot;)&lt;br /&gt;
#vanilla glm&lt;br /&gt;
#glm.fit = glm(y ~ x)&lt;br /&gt;
a=c(p, system.time(fit&amp;lt;-glm(y ~ x))[1])&lt;br /&gt;
b=c(p, object.size(fit))&lt;br /&gt;
&lt;br /&gt;
#speedglm&lt;br /&gt;
da=data.frame(y=y, x)&lt;br /&gt;
#spdglm.fit = speedglm(y ~ x, data=da)&lt;br /&gt;
a=c(a,system.time(fit&amp;lt;-speedglm(y ~ x, data=da))[1])&lt;br /&gt;
b=c(b, object.size(fit))&lt;br /&gt;
&lt;br /&gt;
#glmnet&lt;br /&gt;
#glmnet.fit = glmnet(x, y)&lt;br /&gt;
a=c(a, system.time(fit&amp;lt;-glmnet(x, y))[1])&lt;br /&gt;
b=c(b, object.size(fit))&lt;br /&gt;
&lt;br /&gt;
res=rbind(res,a)&lt;br /&gt;
obj=rbind(obj,b) &lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#plot 1&lt;br /&gt;
plot(res[,1],res[,2],type=&quot;l&quot;, ylab=&quot;seconds&quot;, xlab=&quot;number of response variables&quot;)&lt;br /&gt;
lines(res[,1],res[,3],col=&quot;red&quot;,lty=2)&lt;br /&gt;
lines(res[,1],res[,4],col=&quot;blue&quot;,lty=3)&lt;br /&gt;
legend(&quot;topleft&quot;,c(&quot;glm&quot;,&quot;speedglm&quot;,&quot;glmnet&quot;),col=c(&quot;black&quot;,&quot;red&quot;,&quot;blue&quot;),lty=1)&lt;br /&gt;
&lt;br /&gt;
#plot 2&lt;br /&gt;
plot(obj[,1],log(obj[,2]),type=&quot;l&quot;, ylab=&quot;object size (log(M))&quot;, xlab=&quot;number of response variables&quot;,ylim=c(10,23))&lt;br /&gt;
lines(obj[,1],log(obj[,3]),col=&quot;red&quot;,lty=2)&lt;br /&gt;
lines(obj[,1],log(obj[,4]),col=&quot;blue&quot;,lty=3)&lt;br /&gt;
abline(h=log(8042*1e6))&lt;br /&gt;
abline(h=log(2000*1e6))&lt;br /&gt;
legend(&quot;topleft&quot;,c(&quot;glm&quot;,&quot;speedglm&quot;,&quot;glmnet&quot;),col=c(&quot;black&quot;,&quot;red&quot;,&quot;blue&quot;),lty=1)&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/1512759080710956135/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/1512759080710956135' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/1512759080710956135'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/1512759080710956135'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/10/glm-speedglm-versus-glmnet-comparison.html' title='glm, speedglm versus glmnet comparison tests (part 1)'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjrTSK7-Qd7fksVNkI-3_N2_2g3ykea9S4_N-_ERfiKo75zitb6SbvKlEBK0mziHMhT-pKexnn1Mdi3DXnbT9pg5C6Xn2yWFahgujdh0AofhxorWKokFTCpCsjNOnFYl-h6KOlhAQ/s72-c/glm-comparison-par1a.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-3901566078734530994</id><published>2013-09-27T12:58:00.000-07:00</published><updated>2013-09-27T14:25:48.168-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="2-player"/><category scheme="http://www.blogger.com/atom/ns#" term="algorithms"/><category scheme="http://www.blogger.com/atom/ns#" term="Dixon and Cole"/><title type='text'>Test with real data</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
The previous test indicated that the 2 factor model is working.&amp;nbsp; But test with real data is problematic.&lt;br /&gt;
&lt;br /&gt;
First good news. Estimates are correlated within well connected groups. Here&#39;s the soccer data&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgp3Zm3Q5cUxUZ99KBhgcgSCFdsp1BaGM0b_bn7LduUC9OHRnhCAXcqe7NyiWuG7g536onHN9yTkYjowSSpfA2bJ1KIxAj4xc32iw5-T-YTacuc9oq-uZa_i71T2DRCYDwBoqLlQ/s1600/Sept+27+test+to+soccer+data.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;624&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgp3Zm3Q5cUxUZ99KBhgcgSCFdsp1BaGM0b_bn7LduUC9OHRnhCAXcqe7NyiWuG7g536onHN9yTkYjowSSpfA2bJ1KIxAj4xc32iw5-T-YTacuc9oq-uZa_i71T2DRCYDwBoqLlQ/s640/Sept+27+test+to+soccer+data.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
It&#39;s not a cloud.&amp;nbsp; That&#39;s something.&amp;nbsp; What&#39;s with it not being on the 1-1 line?&amp;nbsp; Wrong prior?&lt;br /&gt;
&lt;br /&gt;
But when I add more groups that are loosely connected to each other.&amp;nbsp; It breaks down and starts looking like a cloud.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEwjjyt-rtxcAgdeLE3_jPWklvDHyQ6ZAcIMMBKUWTQWgt3wE5EEEJkNE6LYCbht6Ry79DBFDaNs8VVTvXSPiKKe7iXC3-H9zBVmBlSFPE3Wst6Izm1BDF9EbeBm_cUdz8DZkF2g/s1600/Sept+27+3+ages.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;390&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEwjjyt-rtxcAgdeLE3_jPWklvDHyQ6ZAcIMMBKUWTQWgt3wE5EEEJkNE6LYCbht6Ry79DBFDaNs8VVTvXSPiKKe7iXC3-H9zBVmBlSFPE3Wst6Izm1BDF9EbeBm_cUdz8DZkF2g/s400/Sept+27+3+ages.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
This makes sense as there is not a whole lot of information to sort out groups against each other.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Add a smoother step to condition on all the data.&amp;nbsp; ALAS it depends on retaining the covariances.&amp;nbsp; But still I don&#39;t need to retain all of them and make a nxn var-cov matrix (which is what is hogging the RAM).&amp;nbsp; That matrix is incredibly sparse and working with the whole thing is the problem.&amp;nbsp; Look in to methods for storing sparse matrices.&lt;/li&gt;
&lt;li&gt;&amp;nbsp;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbziU8vE5zgXKH0P7f9Sh9G8_jiM8pNB6aiUSu2ouKZwLu2WGPn7aJSCypBrQsg8jSQU4zt2WCpZIfeH0YCtfGk7bzbN5KuvPPlM-GozCobR8nl9XP4gUwqwePMVOA3ZOkq6HUFA/s1600/photo.JPG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;298&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbziU8vE5zgXKH0P7f9Sh9G8_jiM8pNB6aiUSu2ouKZwLu2WGPn7aJSCypBrQsg8jSQU4zt2WCpZIfeH0YCtfGk7bzbN5KuvPPlM-GozCobR8nl9XP4gUwqwePMVOA3ZOkq6HUFA/s400/photo.JPG&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Do some sims to see if being off the 1-1 is from the prior.&amp;nbsp;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;The filterglm() is still working ok for a well-mixed group so still has potential. Do some sims to understand how the lack of mixing hurts.&amp;nbsp;&amp;nbsp; Elo starts all new players at a low level.&amp;nbsp; I&#39;m kind of doing that too.&amp;nbsp; Do some time-series to understand how players move &quot;up&quot;.&amp;nbsp; I have priors for the groups.&amp;nbsp; Why not use that as a better prior?&lt;/li&gt;
&lt;li&gt;Or perhaps a hierarchical approach?&amp;nbsp; Where I define &#39;groups&#39; and try to estimate the group mean?&amp;nbsp; It would work, but to pedantic.&amp;nbsp; I like the organic &#39;crowd-sourced&#39; ranking idea better.&amp;nbsp; The structure is idiosyncratic to the problem and I don&#39;t see how I&#39;d organically get the groups.&lt;/li&gt;
&lt;/ul&gt;
&lt;b&gt;Code to run this test&lt;/b&gt;&lt;br /&gt;
f&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;ormula=y~-1+attack+defend&lt;br /&gt;dat=read.csv(&quot;2013 match data/2013-2014/boys-scores-master.csv&quot;, stringsAsFactors=FALSE)&lt;br /&gt;attack = c(dat$home.team, dat$away.team)&lt;br /&gt;defend = c(dat$away.team, dat$home.team)&lt;br /&gt;y = c(dat$home.score,dat$away.score)&lt;br /&gt;moddat = data.frame(y=y,attack=attack, defend=defend,stringsAsFactors=FALSE)&lt;br /&gt;#No NaN allowed in this approach&lt;br /&gt;moddat = moddat[!is.na(moddat$y),]&lt;br /&gt;#now make the factors&lt;br /&gt;levs = unique(c(moddat$attack,moddat$defend))&lt;br /&gt;moddat = data.frame(y=moddat$y,attack=factor(moddat$attack, levels=levs), &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; defend=factor(moddat$defend, levels=levs))&lt;br /&gt;test=filterglm(formula, moddat)&lt;br /&gt;test2=as.data.frame(test)&lt;br /&gt;&lt;br /&gt;#load in the fbRanks speedglm object for the 9-24 data above&lt;br /&gt;test3=print(fbRanks,silent=TRUE,age=&quot;B00&quot;,region=&quot;WA&quot;)$ranks[[1]]&lt;br /&gt;#resort to match whatever is output by print.fbRanks&lt;br /&gt;test4=test2[match(test3$team,rownames(test2)),]&lt;br /&gt;#print.fbRanks is showing exp(attack)&lt;br /&gt;plot(log(test3$attack),test4$attack.mean,xlab=&quot;speedglm estimate&quot;,ylab=&quot;filterglm estimate&quot;)&lt;br /&gt;abline(a=-1*mean(log(test3$attack)),b=1)&lt;br /&gt;&lt;br /&gt;par(mfrow=c(2,2))&lt;br /&gt;for(i in c(&quot;B01&quot;,&quot;B00&quot;,&quot;B99&quot;,&quot;B98&quot;)){&lt;br /&gt;#load in the fbRanks speedglm object for the 9-24 data above&lt;br /&gt;test3=print(fbRanks,silent=TRUE,age=i,region=c(&quot;OR&quot;,&quot;WA&quot;))$ranks[[1]]&lt;br /&gt;#resort to match whatever is output by print.fbRanks&lt;br /&gt;test4=test2[match(test3$team,rownames(test2)),]&lt;br /&gt;#print.fbRanks is showing exp(attack)&lt;br /&gt;plot(log(test3$attack)-mean(log(test3$attack),na.rm=TRUE),test4$attack.mean-mean(test4$attack.mean,na.rm=TRUE),xlab=&quot;speedglm estimate&quot;,ylab=&quot;filterglm estimate&quot;)&lt;br /&gt;title(i)&lt;br /&gt;abline(a=0,b=1)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;par(mfrow=c(2,2))&lt;br /&gt;i = c(&quot;B00&quot;,&quot;B99&quot;,&quot;B98&quot;)&lt;br /&gt;&amp;nbsp; #load in the fbRanks speedglm object for the 9-24 data above&lt;br /&gt;&amp;nbsp; test3=print(fbRanks,silent=TRUE,age=i,region=c(&quot;OR&quot;,&quot;WA&quot;))$ranks[[1]]&lt;br /&gt;&amp;nbsp; #resort to match whatever is output by print.fbRanks&lt;br /&gt;&amp;nbsp; test4=test2[match(test3$team,rownames(test2)),]&lt;br /&gt;&amp;nbsp; #print.fbRanks is showing exp(attack)&lt;br /&gt;&amp;nbsp; plot(log(test3$attack)-mean(log(test3$attack),na.rm=TRUE),test4$attack.mean-mean(test4$attack.mean,na.rm=TRUE),xlab=&quot;speedglm estimate&quot;,ylab=&quot;filterglm estimate&quot;)&lt;br /&gt;&amp;nbsp; title(i)&lt;br /&gt;&amp;nbsp; abline(a=0,b=1)&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;New functions&lt;/b&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;filterglm = function(formula, data, weights = NULL){&lt;br /&gt;&amp;nbsp; #this code is specific to the soccer ranking problem&lt;br /&gt;&amp;nbsp; #it requires that factors have the same levels; not a requirement&lt;br /&gt;&amp;nbsp; #the data must be a dataframe with attack and defend&lt;br /&gt;&amp;nbsp; tf &amp;lt;- terms(formula)&lt;br /&gt;&amp;nbsp; M &amp;lt;- model.frame(tf, data)&lt;br /&gt;&amp;nbsp; names.x = levels(data$attack)&lt;br /&gt;&amp;nbsp; n.x = length(names.x)&lt;br /&gt;&amp;nbsp; M = lapply(M,function(x){if(is.factor(x))x=as.numeric(x) else x})&lt;br /&gt;&amp;nbsp; M = as.data.frame(M)&lt;br /&gt;&amp;nbsp; #mean and variance&lt;br /&gt;&amp;nbsp; est.x=matrix(c(0, 0,1,1), n.x, 4, byrow=TRUE)&lt;br /&gt;&amp;nbsp; rownames(est.x)=names.x&lt;br /&gt;&amp;nbsp;colnames(est.x)=c(paste(colnames(attr(tf,&quot;factors&quot;)),&quot;.mean&quot;,sep=&quot;&quot;),&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; paste(colnames(attr(tf,&quot;factors&quot;)),&quot;.var&quot;,sep=&quot;&quot;))&lt;br /&gt;&amp;nbsp; n.trials = dim(M)[1]&lt;br /&gt;&amp;nbsp; for(i in 1:n.trials){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #go through each contest sequentially and update the factors estimates&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; prior.xtt = matrix(c(est.x[M[i,2],1],est.x[M[i,3],2]),2,1)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; prior.Ptt = diag(c(est.x[M[i,2],3],est.x[M[i,3],4]))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; out=filter.update(M[i,1],prior.xtt=prior.xtt, prior.Ptt=prior.Ptt)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; est.x[M[i,2],1]=out$post.xtt[1]&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; est.x[M[i,3],2]=out$post.xtt[2]&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #post.Ptt is not a diagonal matrix! Think about it.&amp;nbsp; It shouldn&#39;t be.&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #but I don&#39;t retain the information regarding covariance between player estimates&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #this is where this approach loses efficiency relative to an approach that &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #analyzes all the data jointly.&amp;nbsp; But I&#39;m assume I never have the data.....&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; est.x[M[i,2],3]=diag(out$post.Ptt)[1]&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; est.x[M[i,3],4]=diag(out$post.Ptt)[2]&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp; return(est.x)&lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;filter.update=function(y, prior.xtt = matrix(0,2,1), prior.Ptt = diag(1,2), Q=diag(0,2)){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; require(KFAS)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; n=1; TT=1; m=2&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; B=diag(1,2); t.B=B&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Z=matrix(c(1,-1),1,2)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Q=diag(0,2)&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; P1inf=matrix(0,m,m) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if(packageVersion(&quot;KFAS&quot;)==&quot;0.9.11&quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; stop(&quot;KFAS 1.0.0 required and you have old version&quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; #kfas.model=SSModel(y, Z=Z, T=B, R=diag(1,m), Q=Q, a1=prior.xtt, P1=prior.Ptt, P1inf=P1inf, distribution=&quot;Poisson&quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; else&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; kfas.model=SSModel(y ~ -1+SSMcustom( Z=Z, T=B, R=diag(1,m), Q=Q, a1=prior.xtt, P1=prior.Ptt, P1inf=P1inf), distribution=&quot;poisson&quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ks.out=KFS(kfas.model)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return(list(post.xtt=ks.out$alphahat[1:2],post.Ptt=ks.out$V[1:2,1:2,1]))&lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3901566078734530994'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3901566078734530994'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/09/test-with-real-data.html' title='Test with real data'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgp3Zm3Q5cUxUZ99KBhgcgSCFdsp1BaGM0b_bn7LduUC9OHRnhCAXcqe7NyiWuG7g536onHN9yTkYjowSSpfA2bJ1KIxAj4xc32iw5-T-YTacuc9oq-uZa_i71T2DRCYDwBoqLlQ/s72-c/Sept+27+test+to+soccer+data.png" height="72" width="72"/></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-4243855512023753060</id><published>2013-09-27T11:46:00.002-07:00</published><updated>2013-09-27T11:46:56.520-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="2-player"/><category scheme="http://www.blogger.com/atom/ns#" term="algorithms"/><category scheme="http://www.blogger.com/atom/ns#" term="Dixon and Cole"/><title type='text'>Test of the 2-player filter model with attack and defend</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Same ideas as yesterday, except now players have different types of x&#39;s depending on whether they are player 1 or 2 (i.e. attacking and defending).&amp;nbsp; I did this after testing the idea on a real dataset, seeing no correlation to speedglm, then I tested against a known dataset and saw no correlation there.&amp;nbsp; So I did this to see if the problem is the 2 factors types or a bug in the code I wrote this AM.&amp;nbsp; Looks like the later.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAqVwHslTNlbp_8ZYNMYWLG7kg9v-aiQJeg9dFcNqfP_ung6YpPfNHLSXEHdIMMJz5U0XJGdduoFFnijWO1u1kqkK7mZkhFZ1CsfsFrui_S6OPHIZW3MUsEKqUpUUeIQNJKG5AQA/s1600/Sept+27+attack+and+defend.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;360&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAqVwHslTNlbp_8ZYNMYWLG7kg9v-aiQJeg9dFcNqfP_ung6YpPfNHLSXEHdIMMJz5U0XJGdduoFFnijWO1u1kqkK7mZkhFZ1CsfsFrui_S6OPHIZW3MUsEKqUpUUeIQNJKG5AQA/s640/Sept+27+attack+and+defend.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Here&#39;s the 2nd test.&amp;nbsp; Uses the simple.update() function from yesterday&#39;s post.&amp;nbsp; Requires KFAS 1.0.0.&amp;nbsp; I tried 0.9.11, and though it looks to have the poisson, it returns NaN if count is 0.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;sim.poisson.test2 = function(n.x=1000, n.trials=10*1000){&lt;br /&gt;&amp;nbsp; #variance of the distribution of the player pool x&#39;s&lt;br /&gt;&amp;nbsp; mean.x = 0&lt;br /&gt;&amp;nbsp; sig2.x = 1&lt;br /&gt;&amp;nbsp; #true.x is what we are trying to estimate&lt;br /&gt;&amp;nbsp; true.attack = rnorm(n.x, mean.x, sig2.x)&lt;br /&gt;&amp;nbsp; true.defend = rnorm(n.x, mean.x, sig2.x)&lt;br /&gt;&amp;nbsp; dat = matrix(0,n.trials,3)&lt;br /&gt;&amp;nbsp; for(i in 1:n.trials){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dat[i,2:3] = sample(1:n.x,2)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dat[i,1] = rpois(1,exp(true.attack[dat[i,2]]-true.defend[dat[i,3]]))&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp; &lt;br /&gt;&amp;nbsp; #start everyone with an estimate and uncertainty&lt;br /&gt;&amp;nbsp; #corresponding to the player pool mean and variance&lt;br /&gt;&amp;nbsp; est.x=matrix(c(mean.x, mean.x, sig2.x, sig2.x),n.x,4,byrow=TRUE)&lt;br /&gt;&amp;nbsp; for(i in 1:n.trials){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #go through each contest sequentially and update the player x&#39;s&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; prior.xtt = matrix(c(est.x[dat[i,2],1],est.x[dat[i,3],2]),2,1)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; prior.Ptt = diag(c(est.x[dat[i,2],3],est.x[dat[i,3],4]))&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; out=simple.update(dat[i,1],prior.xtt=prior.xtt, prior.Ptt=prior.Ptt, distribution=&quot;poisson&quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; est.x[dat[i,2],1]=out$post.xtt[1]&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; est.x[dat[i,3],2]=out$post.xtt[2]&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #post.Ptt is not a diagonal matrix! Think about it.&amp;nbsp; It shouldn&#39;t be.&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #but I don&#39;t retain the information regarding covariance between player estimates&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #this is where this approach loses efficiency relative to an approach that &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #analyzes all the data jointly.&amp;nbsp; But I&#39;m assume I never have the data.....&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; est.x[dat[i,2],3]=diag(out$post.Ptt)[1]&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; est.x[dat[i,3],4]=diag(out$post.Ptt)[2]&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp; par(mfrow=c(1,2))&lt;br /&gt;&amp;nbsp; plot(est.x[,1],true.attack,xlab=&quot;estimated attack&quot;,ylab=&quot;true attack&quot;)&lt;br /&gt;&amp;nbsp; plot(est.x[,2],true.defend,xlab=&quot;estimated defend&quot;,ylab=&quot;true defend&quot;)&lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/4243855512023753060'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/4243855512023753060'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/09/test-of-2-player-filter-model-with.html' title='Test of the 2-player filter model with attack and defend'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAqVwHslTNlbp_8ZYNMYWLG7kg9v-aiQJeg9dFcNqfP_ung6YpPfNHLSXEHdIMMJz5U0XJGdduoFFnijWO1u1kqkK7mZkhFZ1CsfsFrui_S6OPHIZW3MUsEKqUpUUeIQNJKG5AQA/s72-c/Sept+27+attack+and+defend.png" height="72" width="72"/></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-8931410452972475111</id><published>2013-09-26T12:30:00.003-07:00</published><updated>2013-09-26T12:30:39.092-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="refs of interest"/><title type='text'>Sept 23 2013 Papers</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
25 Years of Forecasting w Time Series Models&lt;br /&gt;
&lt;a href=&quot;http://www.est.uc3m.es/esp/nueva_docencia/comp_col_get/lade/tecnicas_prediccion/Practicas0708/Practica1/25%20years%20of%20time%20series%20forecasting%20%28Gooijer%20and%20Hyndman%29.pdf&quot;&gt;http://www.est.uc3m.es/esp/nueva_docencia/comp_col_get/lade/tecnicas_prediccion/Practicas0708/Practica1/25%20years%20of%20time%20series%20forecasting%20%28Gooijer%20and%20Hyndman%29.pdf&lt;/a&gt;&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8931410452972475111'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8931410452972475111'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/09/sept-23-2013-papers.html' title='Sept 23 2013 Papers'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-8959454062377654715</id><published>2013-09-26T12:29:00.000-07:00</published><updated>2013-09-26T14:17:13.212-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="2-player"/><category scheme="http://www.blogger.com/atom/ns#" term="algorithms"/><title type='text'>update equations for the 2-player contest with a poisson link function</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div data-canvas-width=&quot;84.88000000000001&quot; data-font-name=&quot;Times&quot; dir=&quot;ltr&quot; style=&quot;font-family: serif; font-size: 16px; left: 141.76px; top: 941.12px; transform-origin: 0% 0% 0px; transform: scale(0.999764, 1);&quot;&gt;
&lt;i&gt;The equations for various link functions are here but it&#39;s for a univariate case.&amp;nbsp; Crud.&amp;nbsp; I need univariate y and bivariate x.&lt;/i&gt;&lt;br /&gt;
Harvey, A.C. and C. Fernandes, 1989, Time series models for count or qualitative observations,&lt;/div&gt;
&lt;div data-canvas-width=&quot;109.2704&quot; data-font-name=&quot;Times&quot; dir=&quot;ltr&quot; style=&quot;font-family: serif; font-size: 16px; left: 321.84px; top: 941.12px; transform-origin: 0% 0% 0px; transform: scale(0.999424, 1);&quot;&gt;
J. Bus, Statist., 7, pp. 407-423.&amp;nbsp;&lt;/div&gt;
&lt;div data-canvas-width=&quot;109.2704&quot; data-font-name=&quot;Times&quot; dir=&quot;ltr&quot; style=&quot;font-family: serif; font-size: 16px; left: 321.84px; top: 941.12px; transform-origin: 0% 0% 0px; transform: scale(0.999424, 1);&quot;&gt;
http://www.tandfonline.com/doi/abs/10.1080/07350015.1989.10509750#.UkSIXxD0eUM &lt;/div&gt;
&lt;div data-canvas-width=&quot;109.2704&quot; data-font-name=&quot;Times&quot; dir=&quot;ltr&quot; style=&quot;font-family: serif; font-size: 16px; left: 321.84px; top: 941.12px; transform-origin: 0% 0% 0px; transform: scale(0.999424, 1);&quot;&gt;
&lt;/div&gt;
&lt;div data-canvas-width=&quot;109.2704&quot; data-font-name=&quot;Times&quot; dir=&quot;ltr&quot; style=&quot;font-family: serif; font-size: 16px; left: 321.84px; top: 941.12px; transform-origin: 0% 0% 0px; transform: scale(0.999424, 1);&quot;&gt;
See also Lambert 1996 &lt;/div&gt;
&lt;div data-canvas-width=&quot;109.2704&quot; data-font-name=&quot;Times&quot; dir=&quot;ltr&quot; style=&quot;font-family: serif; font-size: 16px; left: 321.84px; top: 941.12px; transform-origin: 0% 0% 0px; transform: scale(0.999424, 1);&quot;&gt;
http://www.statsoc.ulg.ac.be/publis/Lambert1996JRSSC.pdf&lt;br /&gt;
&lt;br /&gt;
But the new version of KFAS coming out in October 2013 has a Kalman filter for poisson errors.&amp;nbsp; So I can use KFAS&#39;s filter to get the updates.&amp;nbsp; However, it is painfully slow and the gaussian filter is no faster than the poisson filter, so there must be an easy way to compute the updates.&amp;nbsp; Anyhow, this works...but is slow... However(!) and this is super key, it does not take any RAM to speak of.&amp;nbsp; I saw no jump.&amp;nbsp; It just slows as the number of players increases and the number of contests increases.&amp;nbsp; This is key since doing a big glm on the whole dataset with 1000-10,000 factors takes enormous amounts of RAM.&lt;br /&gt;
&lt;br /&gt;
This at least shows proof of concept for an online filter version of Dixon and Cole&#39;s model.&amp;nbsp; Need to figure out how to compute the poisson filter though so I could write it in javascript and have it on a website, say, without having to interact with a computation back-end. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;#Note this depends on KFAS version 1.0.0 which isn&#39;t out yet.&lt;/b&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;simple.update=function(y, prior.xtt = matrix(0,2,1), prior.Ptt = diag(1,2), Q=diag(0,2), R=.1, distribution=&quot;gaussian&quot;){&lt;br /&gt;&amp;nbsp; if(distribution==&quot;gaussian&quot;){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #This is a Kalman filter&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #y is the response (data point)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #Q is how mean x varies in time&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #R is how y (response) is variable with given mu1-mu2&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #y ~ N(mu1-mu2,R)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Z=matrix(c(1,-1),1,2); tZ = t(Z)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Ptt1 = prior.Ptt + Q&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; xtt1 = prior.xtt&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Kt = Ptt1%*%tZ%*%solve(Z%*%Ptt1%*%tZ + R)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; xtt = xtt1 + Kt%*%(y-Z%*%xtt1)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Ptt = (diag(1,2)-Kt%*%Z)%*%Ptt1&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return(list(post.xtt=xtt,post.Ptt=Ptt))&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp; if(distribution==&quot;poisson&quot;){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; require(KFAS)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; n=1; TT=1; m=2&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; B=diag(1,2); t.B=B&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Z=matrix(c(1,-1),1,2)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; R=matrix(r)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Q=diag(0,2)&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; P1inf=matrix(0,m,m)&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; kfas.model=SSModel(y ~ -1+SSMcustom( Z=Z, T=B, R=diag(1,m), Q=Q, a1=prior.xtt, P1=prior.Ptt, P1inf=P1inf), distribution=&quot;poisson&quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ks.out=KFS(kfas.model)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return(list(post.xtt=ks.out$alphahat[1:2],post.Ptt=ks.out$V[1:2,1:2,1]))&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp; if(distribution==&quot;kfas-gaussian&quot;){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; require(KFAS)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; n=1; TT=1; m=2&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; B=diag(1,2); t.B=B&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Z=matrix(c(1,-1),1,2)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; R=matrix(r)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Q=diag(0,2)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; P1inf=matrix(0,m,m)&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; kfas.model=SSModel(y ~ -1+SSMcustom( Z=Z, T=B, R=diag(1,m), Q=Q, a1=prior.xtt, P1=prior.Ptt, P1inf=P1inf), H=R)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ks.out=KFS(kfas.model)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return(list(post.xtt=ks.out$alphahat[1:2],post.Ptt=ks.out$V[1:2,1:2,1]))&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp; &lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Some code to run a little test&lt;/b&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;sim.poisson.test = function(n.x=1000, n.trials=10*1000){&lt;br /&gt;&amp;nbsp; #variance of the distribution of the player pool x&#39;s&lt;br /&gt;&amp;nbsp; mean.x = 0&lt;br /&gt;&amp;nbsp; sig2.x = 1&lt;br /&gt;&amp;nbsp; #true.x is what we are trying to estimate&lt;br /&gt;&amp;nbsp; true.x = rnorm(n.x, mean.x, sig2.x)&lt;br /&gt;&amp;nbsp; dat = matrix(0,n.trials,3)&lt;br /&gt;&amp;nbsp; for(i in 1:n.trials){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dat[i,2:3] = sample(1:n.x,2)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dat[i,1] = rpois(1,exp(true.x[dat[i,2]]-true.x[dat[i,3]]))&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp; &lt;br /&gt;&amp;nbsp; #start everyone with an estimate and uncertainty&lt;br /&gt;&amp;nbsp; #corresponding to the player pool mean and variance&lt;br /&gt;&amp;nbsp; est.x=matrix(c(mean.x, sig2.x),n.x,2,byrow=TRUE)&lt;br /&gt;&amp;nbsp; for(i in 1:n.trials){&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #go through each contest sequentially and update the player x&#39;s&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; prior.xtt = matrix(est.x[dat[i,2:3],1])&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; prior.Ptt = diag(est.x[dat[i,2:3],2])&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; out=simple.update(dat[i,1],prior.xtt=prior.xtt, prior.Ptt=prior.Ptt, distribution=&quot;poisson&quot;)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; est.x[dat[i,2:3],1]=out$post.xtt&amp;nbsp;&amp;nbsp;&amp;nbsp; est.x[dat[i,2:3],2]=diag(out$post.Ptt)&lt;br /&gt;&amp;nbsp; }&lt;br /&gt;&amp;nbsp; plot(est.x[,1],true.x,xlab=&quot;estimated x&quot;,ylab=&quot;true x&quot;)&lt;br /&gt;}&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;background-color: #e1e2e5; border-collapse: separate; font-family: &#39;Lucida Console&#39;; font-size: 13px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 15px; orphans: 2; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;pre class=&quot;GNVMTOMCABB&quot; style=&quot;-webkit-user-select: text; border-bottom-style: none; border-color: initial; border-left-style: none; border-right-style: none; border-top-style: none; border-width: initial; font-family: &#39;Lucida Console&#39;; font-size: 10pt !important; line-height: 1.2; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: none; outline-width: initial; white-space: pre-wrap !important;&quot; tabindex=&quot;0&quot;&gt;&lt;span class=&quot;GNVMTOMCHAB ace_keyword&quot;&gt;system.time(sim.poisson.test(n.trials=5*1000))&lt;/span&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
output.&amp;nbsp; Note performance is rather better than one would get normally since this has really weak players against strong ones.&amp;nbsp; You might expect that strong players tend to play strong players....&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEUKOCTX0zLe1I9mF8xXgmrYe-U2hwrhGJiTvycjc0XeG4k03pkQS7zme_iK_TuxLPhqB1AJr4z3JAE_c7sa4B-Qq-hv46OQzTSbUMdCgP6OMY3AoQwVSL8sYTNFTB8xM-HJiNJA/s1600/poisson+test+1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;280&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEUKOCTX0zLe1I9mF8xXgmrYe-U2hwrhGJiTvycjc0XeG4k03pkQS7zme_iK_TuxLPhqB1AJr4z3JAE_c7sa4B-Qq-hv46OQzTSbUMdCgP6OMY3AoQwVSL8sYTNFTB8xM-HJiNJA/s400/poisson+test+1.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/8959454062377654715/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/8959454062377654715' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8959454062377654715'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/8959454062377654715'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/09/update-equations-for-2-player-contest.html' title='update equations for the 2-player contest with a poisson link function'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEUKOCTX0zLe1I9mF8xXgmrYe-U2hwrhGJiTvycjc0XeG4k03pkQS7zme_iK_TuxLPhqB1AJr4z3JAE_c7sa4B-Qq-hv46OQzTSbUMdCgP6OMY3AoQwVSL8sYTNFTB8xM-HJiNJA/s72-c/poisson+test+1.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-6578884879276437578</id><published>2013-09-26T11:03:00.002-07:00</published><updated>2013-09-26T11:04:20.709-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="2-player"/><category scheme="http://www.blogger.com/atom/ns#" term="algorithms"/><category scheme="http://www.blogger.com/atom/ns#" term="bayesian"/><category scheme="http://www.blogger.com/atom/ns#" term="Elo"/><title type='text'>Toy example of a filter for computing the 2-player hidden x&#39;s</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Follow-up on &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/09/relationship-of-elo-algorithm-to.html&quot;&gt;relationship-of-elo-algorithm-to-logistic-regression&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
This morning I coded up an implementation of the idea for an Elo-like (or Kalman-like or filter-esque or Bayesian) update algorithm for 2-player data.&amp;nbsp; It is Elo-like because the idea is that you never store the data nor the player information.&amp;nbsp; Rather each player knows their own estimated &lt;i&gt;mean x&lt;/i&gt; and &lt;i&gt;uncertainty&lt;/i&gt; in that estimate. They meet another player and have a contest.&amp;nbsp; At the end of the contest, they exchange their priors (their mean &lt;i&gt;x&lt;/i&gt; and uncertainty before the contest) and each updates their own estimate of their &lt;i&gt;x&lt;/i&gt;.&lt;br /&gt;
&lt;br /&gt;
I&#39;m going to tackle first an easy problem for which I already know the update equation.&amp;nbsp; Ultimately, I want to use this for a problem where I will have to derive the update equation.&amp;nbsp; I would prefer a closed form update equation, but the principle will work even if I have to do a numerical update&amp;nbsp; using a MCMC algorithm.&lt;br /&gt;
&lt;br /&gt;
Set-up of the problem:&lt;br /&gt;
Assume a large player pool. Player x&#39;s are drawn from a Normal distribution with mean mu and variance pi.&amp;nbsp; We assume that we know what this distribution is but don&#39;t known the individual player x&#39;s .&amp;nbsp; Our objective is to estimate those x&#39;s.&amp;nbsp; Two players are drawn at random.&amp;nbsp; One is chosen (randomly) to be #1 (attacker) and the other is #2 (defender).&amp;nbsp; They have a contest.&amp;nbsp; The outcome of this contest is a Normal distribution with mean (x.attacker - x.defender) and variance of contest.var.&amp;nbsp; Again we assume we know a lot about the nature of this contest, so we know the contest variance and we know the outcome is normally distributed.&amp;nbsp; But we don&#39;t know the &lt;i&gt;x&lt;/i&gt;&#39;s of the players in the contest.&amp;nbsp; Our players start with an estimated &lt;i&gt;x&lt;/i&gt; and uncertainty of mu and pi (the distribution of x&#39;s in the player population).&amp;nbsp; They head out and randomly encounter other players and have contests with them.&amp;nbsp; After each contest, the individual players update their &lt;i&gt;x&lt;/i&gt; estimate and uncertainty in that.&lt;br /&gt;
&lt;br /&gt;
Code is below.&amp;nbsp; This plot summarizes the results with 1000 players and 10,000 or 5,000 contests.&amp;nbsp; The attacker and defender were chosen randomly.&amp;nbsp; The mean number of contests per player was 20 for 10,000 contests (each contest includes 2 players) and 10 for 5,000 contests.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEionnJkA5AH2mvqgn_opSvS6l-yert4wsMQOq0bZzKQqShLnZC6YIlkIUZt3Df3OVeUzNeUClKZ6fUh3pv8HFddjH5h5sCtqgyPqnZGo9Q4eduqr_Q-LXzm_m_8wg5tq-L-WhPt-A/s1600/Sept+25+B.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEionnJkA5AH2mvqgn_opSvS6l-yert4wsMQOq0bZzKQqShLnZC6YIlkIUZt3Df3OVeUzNeUClKZ6fUh3pv8HFddjH5h5sCtqgyPqnZGo9Q4eduqr_Q-LXzm_m_8wg5tq-L-WhPt-A/s1600/Sept+25+B.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
First, cool. This works!!&amp;nbsp; Second, it depends a lot on the characteristic of the contest.&amp;nbsp; If the contest involves a lot of luck (bottom row) then there is a loose relationship between mu1-mu2 and the outcome, then many contests are needed to get a good estimate of players&#39; x&#39;s.&amp;nbsp; If the contest outcome is closely related to m1-mu2 (top row), then fewer contests are needed.&lt;br /&gt;
&lt;br /&gt;
The R code:&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;Courier New&amp;quot;,Courier,monospace;&quot;&gt;simple.update=function(y, prior.xtt = matrix(0,2,1), prior.Ptt = diag(1,2), Q=diag(0,2), R=.1){&lt;br /&gt;&amp;nbsp; #This is a Kalman filter&lt;br /&gt;&amp;nbsp; #y is the response (data point)&lt;br /&gt;&amp;nbsp; #Q is how mean x varies in time&lt;br /&gt;&amp;nbsp; #R is how y (response) is variable with given mu1-mu2&lt;br /&gt;&amp;nbsp; #y ~ N(mu1-mu2,R)&lt;br /&gt;&amp;nbsp; Z=matrix(c(1,-1),1,2); tZ = t(Z)&lt;br /&gt;&amp;nbsp; Ptt1 = prior.Ptt + Q&lt;br /&gt;&amp;nbsp; xtt1 = prior.xtt&lt;br /&gt;&amp;nbsp; Kt = Ptt1%*%tZ%*%solve(Z%*%Ptt1%*%tZ + R)&lt;br /&gt;&amp;nbsp; xtt = xtt1 + Kt%*%(y-Z%*%xtt1)&lt;br /&gt;&amp;nbsp; Ptt = (diag(1,2)-Kt%*%Z)%*%Ptt1&lt;br /&gt;&amp;nbsp; return(list(post.xtt=xtt,post.Ptt=Ptt))&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;sim.test = function(r=1, n.x=1000, n.trials=10*1000){&lt;br /&gt;#variance of the distribution of the player pool x&#39;s&lt;br /&gt;mean.x = 0&lt;br /&gt;sig2.x = 1&lt;br /&gt;#true.x is what we are trying to estimate&lt;br /&gt;true.x = rnorm(n.x, mean.x, sig2.x)&lt;br /&gt;dat = matrix(0,n.trials,3)&lt;br /&gt;for(i in 1:n.trials){&lt;br /&gt;&amp;nbsp; dat[i,2:3] = sample(1:n.x,2)&lt;br /&gt;&amp;nbsp; dat[i,1] = rnorm(1,true.x[dat[i,2]]-true.x[dat[i,3]],r)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;#start everyone with an estimate and uncertainty&lt;br /&gt;#corresponding to the player pool mean and variance&lt;br /&gt;est.x=matrix(c(mean.x, sig2.x),n.x,2,byrow=TRUE)&lt;br /&gt;for(i in 1:n.trials){&lt;br /&gt;&amp;nbsp; #go through each contest sequentially and update the player x&#39;s&lt;br /&gt;&amp;nbsp; prior.xtt = matrix(est.x[dat[i,2:3],1])&lt;br /&gt;&amp;nbsp; prior.Ptt = diag(est.x[dat[i,2:3],2])&lt;br /&gt;&amp;nbsp; out=simple.update(dat[i,1],prior.xtt=prior.xtt, prior.Ptt=prior.Ptt)&lt;br /&gt;&amp;nbsp; est.x[dat[i,2:3],1]=out$post.xtt&lt;br /&gt;&amp;nbsp; #post.Ptt is not a diagonal matrix! Think about it.&amp;nbsp; It shouldn&#39;t be.&lt;br /&gt;&amp;nbsp; #but I don&#39;t retain the information regarding covariance between player estimates&lt;br /&gt;&amp;nbsp; #this is where this approach loses efficiency relative to an approach that &lt;br /&gt;&amp;nbsp; #analyzes all the data jointly.&amp;nbsp; But I&#39;m assume I never have the data.....&lt;br /&gt;&amp;nbsp; est.x[dat[i,2:3],2]=diag(out$post.Ptt)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;plot(est.x[,1],true.x,xlab=&quot;estimated x&quot;,ylab=&quot;true x&quot;)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;par(mfrow=c(3,3))&lt;br /&gt;r=.1&lt;br /&gt;hist(rnorm(1000,0,sqrt(r)),main=&quot;Dist of contest outcomes\nr=.1&quot;,xlab=&quot;contest outcome&quot;)&lt;br /&gt;sim.test(r=r)&lt;br /&gt;title(&quot;Mean 20 contests\nper player&quot;)&lt;br /&gt;sim.test(r=r,n.trials=5*1000)&lt;br /&gt;title(&quot;Mean 10 contests\nper player&quot;)&lt;br /&gt;&lt;br /&gt;r=1&lt;br /&gt;hist(rnorm(1000,0,sqrt(r)),main=&quot;r=.5&quot;,xlab=&quot;contest outcome&quot;)&lt;br /&gt;sim.test(r=r)&lt;br /&gt;sim.test(r=r,n.trials=5*1000)&lt;br /&gt;&lt;br /&gt;r=2&lt;br /&gt;hist(rnorm(1000,0,sqrt(r)),main=&quot;r=1&quot;,xlab=&quot;contest outcome&quot;)&lt;br /&gt;sim.test(r=r)&lt;br /&gt;sim.test(r=r,n.trials=5*1000)&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Ok, that&#39;s great.&amp;nbsp; This is nothing new.&amp;nbsp; It&#39;s just an implementation of Elo&#39;s idea but&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;&amp;nbsp;in a slightly different context&lt;/li&gt;
&lt;li&gt;different link function between response variable and hidden variables&lt;/li&gt;
&lt;li&gt;players retain information about the uncertainty in their estimated &lt;i&gt;x&lt;/i&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;i&gt;But &lt;/i&gt;it now points me in the direction of an algorithm for a generic contest link function (Bernoulli for a success-fail contest, Poisson for a contest with points or goals, Negative binomial, etc)&lt;i&gt;.&lt;/i&gt; The Gaussian link function is nice since the update equation (kalman filter) is closed form.&amp;nbsp; If I have to resort to a numerical updater (gibbs or mcmc), it&#39;s going to get slow.&lt;br /&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/6578884879276437578'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/6578884879276437578'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/09/toy-example-of-filter-for-computing-2.html' title='Toy example of a filter for computing the 2-player hidden x&#39;s'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEionnJkA5AH2mvqgn_opSvS6l-yert4wsMQOq0bZzKQqShLnZC6YIlkIUZt3Df3OVeUzNeUClKZ6fUh3pv8HFddjH5h5sCtqgyPqnZGo9Q4eduqr_Q-LXzm_m_8wg5tq-L-WhPt-A/s72-c/Sept+25+B.png" height="72" width="72"/></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-3050853044903264380</id><published>2013-09-25T12:21:00.001-07:00</published><updated>2013-10-08T12:17:08.984-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="2-player"/><category scheme="http://www.blogger.com/atom/ns#" term="algorithms"/><category scheme="http://www.blogger.com/atom/ns#" term="Elo"/><category scheme="http://www.blogger.com/atom/ns#" term="interaction strengths"/><category scheme="http://www.blogger.com/atom/ns#" term="logistic regression"/><title type='text'>Relationship of Elo algorithm to logistic regression</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Follow up on &lt;a href=&quot;http://parsimoniouspursuits.blogspot.com/2013/09/strategy-for-asynchronous-update.html&quot;&gt;strategy-for-asynchronous-update&lt;/a&gt;&lt;br /&gt;
See ** at bottom for where this all is going.&lt;br /&gt;
Huh, what&#39;s this have to do with Elo algorithm?&amp;nbsp; The Elo algorithm is a solution to a problem similar to the &lt;i&gt;reverse&lt;/i&gt; 2-player logistic regression described half-way down.&lt;br /&gt;
&lt;br /&gt;
y ~ b, link=f(b)*&lt;br /&gt;
&lt;br /&gt;
y is 0,1 data (success, failure).&amp;nbsp; In a typical logistic regression, we use the logistic function to link &quot;t&quot; to probability of success. &lt;br /&gt;
&lt;br /&gt;
prob of success = p = 1/(1+exp(-t))&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;Then we assume some function that relates our covariate x to t. &amp;nbsp; Vanilla approach is a linear relationship: t = a + bx&lt;br /&gt;
&lt;br /&gt;
* except that we think of this in the inverse (logit).&amp;nbsp; a+bx = g(x) = log(p/(1-p))&amp;nbsp; or log odds is a linear function of x.&lt;br /&gt;
&lt;br /&gt;
The objective of this simple logistic regression is to estimate a and b, given x&#39;s associated with y&#39;s (0,1 data).&amp;nbsp; An iterative algorithm is used where we start with some estimate of a and b, and then keep updating that (e.g. Newton method).&lt;br /&gt;
&lt;br /&gt;
So now let&#39;s reverse the problem.&lt;br /&gt;
&lt;br /&gt;
We know (assume) a and b but we do not know x.&amp;nbsp; We want an algorithm that gets us the x(i) where i is our i-th individual (say).&amp;nbsp; That&#39;s seems easy enough but we need multiple trials for each i.&amp;nbsp; Then we get an estimate of p = successes/trials.&amp;nbsp; We plug in p, a and b into the logistic equation and solve for x.&lt;br /&gt;
&lt;br /&gt;
So that&#39;s not very interesting.&amp;nbsp; It becomes more interesting when we have a 2 players in each trial.&lt;br /&gt;
&lt;br /&gt;
t = a + bx(i) + bx(j)&lt;br /&gt;
&lt;br /&gt;
We want to solve for the x&#39;s .&amp;nbsp; How to do that?&amp;nbsp; First imagine that you have the data** on a bunch of trails.&lt;br /&gt;
&lt;br /&gt;
** Don&#39;t you always have to &#39;have the data&#39;?&amp;nbsp; No.&amp;nbsp; Where this is going is an algorithm where no one has the data.&amp;nbsp; Each player has an estimate of their x and their uncertainty about this estimate.&amp;nbsp; Two players come together and have a trial.&amp;nbsp; Each updates their estimate and uncertainty given their information about both players&#39; x&#39;s.&amp;nbsp; Then they go off and find another player to have a trial with.&amp;nbsp; The &#39;data&#39; is never kept; players only keep their current estimate of their x and their estimate of its uncertainty.&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/3050853044903264380/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/3050853044903264380' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3050853044903264380'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3050853044903264380'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/09/relationship-of-elo-algorithm-to.html' title='Relationship of Elo algorithm to logistic regression'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-3401772399223528329</id><published>2013-09-25T11:05:00.000-07:00</published><updated>2013-10-08T12:17:50.300-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="2-player"/><category scheme="http://www.blogger.com/atom/ns#" term="algorithms"/><category scheme="http://www.blogger.com/atom/ns#" term="bayesian"/><category scheme="http://www.blogger.com/atom/ns#" term="Dixon and Cole"/><category scheme="http://www.blogger.com/atom/ns#" term="Elo"/><category scheme="http://www.blogger.com/atom/ns#" term="fbRanks"/><category scheme="http://www.blogger.com/atom/ns#" term="interaction strengths"/><category scheme="http://www.blogger.com/atom/ns#" term="poisson regression"/><title type='text'>Strategy for asynchronous update algorithm for Dixon and Cole&#39;s model</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Problem: Synchronous updating for Dixon and Cole&#39;s model--speedglm(family=poisson(log)), is ultimately unscalable. So glm(y ~ factor(x)) at some point reaches a limit as the levels in x go to infinity.&lt;br /&gt;
&lt;br /&gt;
It works until one maxes out the RAM.&amp;nbsp; Second it doesn&#39;t not allow parallization.&amp;nbsp; But parallel is not the right idea.&amp;nbsp; Parallel means each agent (agent is analogy for something that does a computation) works on an isolated part of the computation.&amp;nbsp; I want something more like the exercise that Rachel lead at the ISEES workshop.&amp;nbsp; The post-in notes are all on the wall.&amp;nbsp; Many agents come up and move the post-it notes at once.&amp;nbsp; Each messing up the others work.&amp;nbsp; There is no compartmentalization.&amp;nbsp; But there is something like &#39;importance sampling&#39;.&amp;nbsp; The contentious post-it notes are moving more.&amp;nbsp; The non-contentious ones are quickly settled.&amp;nbsp;&amp;nbsp; Idea is to &#39;set loose&#39; many &#39;bugs&#39; in the data and these go to work on the data.&lt;br /&gt;
&lt;br /&gt;
Imagine rating an effectively infinite number of &#39;players&#39;.&amp;nbsp; I&#39;m using &#39;teams&#39; but this isn&#39;t about sports but about estimating a model from enormous 2-player datasets with effectively infinite numbers of players.&amp;nbsp; Players could be cell-phone numbers and the contest&amp;nbsp; something about a call between 2 phones and you are trying to rank some characteristic of the phone numbers.&lt;br /&gt;
&lt;br /&gt;
Relation to EM algorithm.&amp;nbsp; At each step the LL increases.&amp;nbsp; Ultimately the max is reached.&lt;br /&gt;
* compute expected value of hidden state conditioned on all the data&lt;br /&gt;
&amp;nbsp;&amp;nbsp; - forward/backward smoother&lt;br /&gt;
* compute ML of parameters conditioned on data and expected value of hidden state&lt;br /&gt;
&lt;br /&gt;
Relation to bayesian algorithm&lt;br /&gt;
* Start with prior on hidden state&lt;br /&gt;
* Get 1 data point, update to posterior of hidden state&lt;br /&gt;
* &lt;span style=&quot;background-color: yellow;&quot;&gt;Need a closed form update equation&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Relation to MCMC&lt;br /&gt;
* MCMC algorithm is getting the posterior surface&lt;br /&gt;
* Same idea but I want the &#39;strengths surface&#39;.&amp;nbsp; The x-axis is &#39;player&#39;.&amp;nbsp; It is a factor in glm lingo or random effect in glmer lingo.&amp;nbsp; It is discrete, but effectively infinite.&amp;nbsp; The y-axis is strength. &lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3401772399223528329'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3401772399223528329'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2013/09/strategy-for-asynchronous-update.html' title='Strategy for asynchronous update algorithm for Dixon and Cole&#39;s model'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-3003841719539615803</id><published>2007-09-28T12:54:00.000-07:00</published><updated>2007-09-28T13:11:59.630-07:00</updated><title type='text'>Does biological complexity add realism?</title><content type='html'>From a report that will remain unnamed:&lt;br /&gt;&quot;At the other end of the spectrum are formulations such as IBMs which require detailed knowledge of physiological and metabolic processes and how these influence the vital rates of fecundity and survivorship. The realism of these approaches is further enhanced through incorporation of density influences on or stochastic variation in these processes. Such data are difficult to obtain, yet their inclusion into appropriate models permits the most detailed assessments.&quot;&lt;br /&gt;&lt;br /&gt;As usual, addition of biological complexity into a model is equated with adding realism.  Realism is good and permits a better risk assessment.  I completely disagree with this general statement -- BECAUSE details are unknown.  I would argue unknowable, but most would disagree.&lt;br /&gt;&lt;br /&gt;But back to this mechanistic detailed model is better for risk assessment.  Let&#39;s use an analogy.  I am a witness to a crime.  I get a brief glimpse of the perpetrator.  I report the crime and am working with a police artist to create a composite of the criminal.&lt;br /&gt;&lt;br /&gt;Artist:  Male or Female&lt;br /&gt;Me: Female&lt;br /&gt;Artist: Hair?&lt;br /&gt;Me: Black&lt;br /&gt;Artist: Eye color?&lt;br /&gt;Me: I didn&#39;t see that.&lt;br /&gt;Artist: Hmm, well we know that all humans have eye color so to make this realistic we need to pick an eye color.&lt;br /&gt;Me: I didn&#39;t see her eyes.&lt;br /&gt;Artist: Ok, let&#39;s use the maximum likelihood estimate and make them brown.&lt;br /&gt;Artist: Height?&lt;br /&gt;Me: Average&lt;br /&gt;Artist: Hmm, well to make this realistic let&#39;s use the average height of women, 5&#39; 6&quot;.&lt;br /&gt;Artist: Clothing?&lt;br /&gt;Me: Dark pants and light t-shirt.  I didn&#39;t see the shoes.&lt;br /&gt;Artist: Ok, let&#39;s add some realism.  Blue jeans, sound ok?, light t-shirt..hmm, a woman wouldn&#39;t wear a regular t-shirt, let&#39;s make it a v-neck.  Shoes...crocs, everyone is wearing those nowadays.&lt;br /&gt;Me: Well, I really don&#39;t recall the specifics, that could be what she was wearing.&lt;br /&gt;Artist: Ok, I&#39;m going to go off and make a detailed photorealistic picture of this woman.....&lt;br /&gt;&lt;br /&gt;The artist comes back with a photorealistic picture.  It definitely looks like a real human woman, but it does not look like the criminal.  In this case, more realism just hinders the investigation.  It would be better to stick with &quot;black haired average height woman&quot; even though that is vague.  It might not end up being all that useful, but it rules out many suspects.</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/3003841719539615803/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/3003841719539615803' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3003841719539615803'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/3003841719539615803'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2007/09/does-biological-complexity-add-realism.html' title='Does biological complexity add realism?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-6928512225183254362</id><published>2007-02-26T13:26:00.000-08:00</published><updated>2007-03-05T17:51:38.309-08:00</updated><title type='text'>neutral models of metapopulation dynamics</title><content type='html'>Discuss the population patterns that occur via neutral models of dispersal.  Illustrate that these patterns occur in large collections of spatially-structured populations.  Illustrate that complex patterns of population density can occur via patterns of dispersal.  Analogous to Hubbell&#39;s work on neutral models of diversity.&lt;br /&gt;&lt;br /&gt;Neutral models of population distributions&lt;br /&gt;&lt;br /&gt;Colloquially people think of different rates of population growth or decline as an indication of population robustness?  However Can we see what is going on?&lt;br /&gt;&lt;br /&gt;Is it possible to detect habitat heterogeneity?  At low dispersal, we see the effect of heterogeneity but as dispersal increases, &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Within a metapopulation, there is a canonical relationship between the year-to-year variability within the total population and the variability in growth rates between sub-populations.</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/6928512225183254362/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/6928512225183254362' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/6928512225183254362'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/6928512225183254362'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2007/02/neutral-models-of-metapopulation.html' title='neutral models of metapopulation dynamics'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-116051534170599452</id><published>2006-10-10T14:06:00.000-07:00</published><updated>2006-10-17T18:41:33.438-07:00</updated><title type='text'>Rweb</title><content type='html'>An example of folks with a R server up and running&lt;br /&gt;&lt;br /&gt;http://www.stat.umn.edu/geyer/old03/5601/examp/parm.html&lt;br /&gt;&lt;br /&gt;http://www.math.montana.edu/Rweb/&lt;br /&gt;&lt;br /&gt;http://bayes.math.montana.edu/Rweb/Resources.html</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/116051534170599452/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/116051534170599452' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/116051534170599452'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/116051534170599452'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2006/10/rweb.html' title='Rweb'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-115100756238909495</id><published>2006-06-22T13:19:00.000-07:00</published><updated>2006-10-17T18:41:32.937-07:00</updated><title type='text'>prediction error</title><content type='html'>Efron, B. 2004. The estimation of prediction error: covariance penalties and cross-validation. &lt;br /&gt;Journal of the American Statistical Association 99: 619-632.</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/115100756238909495/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/115100756238909495' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/115100756238909495'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/115100756238909495'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2006/06/prediction-error.html' title='prediction error'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-114936986361944855</id><published>2006-06-03T14:22:00.000-07:00</published><updated>2006-10-17T18:41:32.851-07:00</updated><title type='text'>predictive vs interpolative accuracy</title><content type='html'>Predictive Accuracy as an&lt;br /&gt;Achievable Goal of Science&lt;br /&gt;Malcolm R. Forster†‡&lt;br /&gt;University of Wisconsin-Madison&lt;br /&gt;&lt;br /&gt;What has science actually achieved? A theory of achievement should (1) define what has been achieved, (2) describe the means or methods used in science, and (3) explain how such methods lead to such achievements. Predictive accuracy is one truth-related achievement of science, and there is an explanation of why common scientific practices (of trading off simplicity and fit) tend to increase predictive accuracy. Akaike’s explanation for the success of AIC is limited to interpolative predictive accuracy. But therein lies the strength of the general framework, for it also provides a clear formulation of many open problems of research.&lt;br /&gt;&lt;br /&gt;http://philosophy.wisc.edu/forster/papers/PSA2000.pdf</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/114936986361944855/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/114936986361944855' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/114936986361944855'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/114936986361944855'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2006/06/predictive-vs-interpolative-accuracy.html' title='predictive vs interpolative accuracy'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-113994174129044840</id><published>2006-02-14T10:28:00.000-08:00</published><updated>2006-10-17T18:41:32.544-07:00</updated><title type='text'>ok so LR depends on nested-ness</title><content type='html'>since the models are not nested, the usual LR test statistic will not have an asymptotic Chi-square distribution and hence the statistic you compute will not have a meaningful interpretation.&lt;br /&gt;&lt;br /&gt;http://www.biostat.wustl.edu/archives/html/s-news/2004-03/msg00200.html&lt;br /&gt;&lt;br /&gt;However, Burnham and Anderson argue that the ranking of models with AICc is not limited by this pg 88.&lt;br /&gt;&lt;br /&gt;page 61 in PRNN&lt;br /&gt;&lt;br /&gt;Ripley says that NIC criterion is based on penalty&lt;br /&gt;&lt;br /&gt;2p* = trace[KJ^-1]&lt;br /&gt;&lt;br /&gt;If the model is adequate (or true), J=K, and p* is the number of parameters and NIC becomes AIC.  These results are based on asymptotic normality of the parameter estimates.&lt;br /&gt;&lt;br /&gt;Moody 1991, 1992 (uses effective number of parameters)&lt;br /&gt;Murata et al 1991 (on the effective number of parameters)&lt;br /&gt;cf. maybe first Draper 1995  JRSS&lt;br /&gt;&lt;br /&gt;Fisher information&lt;br /&gt;http://en.wikipedia.org/wiki/Fisher_information_matrix</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/113994174129044840/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/113994174129044840' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/113994174129044840'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/113994174129044840'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2006/02/ok-so-lr-depends-on-nested-ness.html' title='ok so LR depends on nested-ness'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-18535412.post-113994151029746783</id><published>2006-02-14T10:17:00.000-08:00</published><updated>2006-10-17T18:41:32.477-07:00</updated><title type='text'>Determining correct model complexity</title><content type='html'>x  X (X is the set of possible data)&lt;br /&gt;&lt;br /&gt;Let&#39;s specify some statistic t(x)&lt;br /&gt;&lt;br /&gt;from x estimate the deviance [t(X)-t(x)]^2 = s^hat&lt;br /&gt;&lt;br /&gt;On average how big is this deviance?&lt;br /&gt;&lt;br /&gt;Akaike -&gt; 2p&lt;br /&gt;&lt;br /&gt;http://www.stat.columbia.edu/~cook/movabletype/archives/2004/12/against_parsimo.html&lt;br /&gt;&lt;a href=&quot;http://www.stat.columbia.edu/~gelman/stuff_for_blog/hirschman.pdf&quot;&gt;Against parsimony&lt;/a&gt;&lt;br /&gt;&lt;a href=&quot;http://philosophy.wisc.edu/forster/&quot;&gt;Occam’s Razor and the Relational Nature of Evidence&lt;/a&gt;&lt;br /&gt;Tutorial&lt;br /&gt;ftp://ftp.cs.utoronto.ca/pub/radford/bayes-tut.ps</content><link rel='replies' type='application/atom+xml' href='http://parsimoniouspursuits.blogspot.com/feeds/113994151029746783/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/18535412/113994151029746783' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/113994151029746783'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/18535412/posts/default/113994151029746783'/><link rel='alternate' type='text/html' href='http://parsimoniouspursuits.blogspot.com/2006/02/determining-correct-model-complexity.html' title='Determining correct model complexity'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>