idx
int64
1
56k
question
stringlengths
15
155
answer
stringlengths
2
29.2k
question_cut
stringlengths
15
100
answer_cut
stringlengths
2
200
conversation
stringlengths
47
29.3k
conversation_cut
stringlengths
47
301
25,701
How best to analyze length of stay data in a hospital-based RCT?
I favor the Cox proportional hazards model, which will also handle censored length of stay (death before successful hospital discharge). A relevant handout may be found at http://biostat.app.vumc.org/wiki/pub/Main/FHHandouts/slide.pdf with code here: http://biostat.app.vumc.org/wiki/pub/Main/FHHandouts/model.s
How best to analyze length of stay data in a hospital-based RCT?
I favor the Cox proportional hazards model, which will also handle censored length of stay (death before successful hospital discharge). A relevant handout may be found at http://biostat.app.vumc.org
How best to analyze length of stay data in a hospital-based RCT? I favor the Cox proportional hazards model, which will also handle censored length of stay (death before successful hospital discharge). A relevant handout may be found at http://biostat.app.vumc.org/wiki/pub/Main/FHHandouts/slide.pdf with code here: http://biostat.app.vumc.org/wiki/pub/Main/FHHandouts/model.s
How best to analyze length of stay data in a hospital-based RCT? I favor the Cox proportional hazards model, which will also handle censored length of stay (death before successful hospital discharge). A relevant handout may be found at http://biostat.app.vumc.org
25,702
How best to analyze length of stay data in a hospital-based RCT?
I recommend logrank test for testing for differences between groups and for each independent variable. Maybe you will need to adjust for several variables (at least for those significant in the logrank test) in a Cox proportional hazards model. Gamma generalized model (parametric) could be an alternative to Cox if you will need baseline (hazard) risk estimation.
How best to analyze length of stay data in a hospital-based RCT?
I recommend logrank test for testing for differences between groups and for each independent variable. Maybe you will need to adjust for several variables (at least for those significant in the logran
How best to analyze length of stay data in a hospital-based RCT? I recommend logrank test for testing for differences between groups and for each independent variable. Maybe you will need to adjust for several variables (at least for those significant in the logrank test) in a Cox proportional hazards model. Gamma generalized model (parametric) could be an alternative to Cox if you will need baseline (hazard) risk estimation.
How best to analyze length of stay data in a hospital-based RCT? I recommend logrank test for testing for differences between groups and for each independent variable. Maybe you will need to adjust for several variables (at least for those significant in the logran
25,703
How best to analyze length of stay data in a hospital-based RCT?
death is a competing event with discharge. Censoring the deaths would not be censoring missing data at random. Examining the cumulative incidence of death and discharge and comparing the subdistribution hazards might be more appropriate.
How best to analyze length of stay data in a hospital-based RCT?
death is a competing event with discharge. Censoring the deaths would not be censoring missing data at random. Examining the cumulative incidence of death and discharge and comparing the subdistributi
How best to analyze length of stay data in a hospital-based RCT? death is a competing event with discharge. Censoring the deaths would not be censoring missing data at random. Examining the cumulative incidence of death and discharge and comparing the subdistribution hazards might be more appropriate.
How best to analyze length of stay data in a hospital-based RCT? death is a competing event with discharge. Censoring the deaths would not be censoring missing data at random. Examining the cumulative incidence of death and discharge and comparing the subdistributi
25,704
Predicting response from new curves using fda package in R
I don't care for fda's use of Inception-like list-within-list-within-list object structures, but my response will abide by the system the package writers have created. I think it's instructive to first think about what we're doing exactly. Based on your description of what you've done so far, this is what I believe you're doing (let me know if I have misinterpreted something). I'll be continuing using notation and, due to lack of real data, an example from Ramsay and Silverman's Functional Data Analysis and Ramsay, Hooker, and Graves's Functional Data Analysis with R and MATLAB (Some of the following equations and code are lifted directly from these books). We are modelling a scalar response via a functional linear model, i.e. $y_i = \beta_0 + \int_0^T X_i(s)\beta(s)ds + \epsilon_i$ We expand the $\beta$ in some basis. We use, say, $K$ basis functions. So, $\beta(s) = \sum\limits_{k=1}^K b_k\theta_k (s)$ In matrix notation, this is $\beta (s)=\boldsymbol{\theta}'(s)\mathbf{b}$. We also expand the covariate functions in some basis, as well (say $L$ basis functions). So, $X_i(s) = \sum\limits_{k=1}^L c_{ik}\psi_k (s)$ Again, in matrix notation, this is $X(s)=\mathbf{C}\boldsymbol{\psi}(s)$. And thus, if we let $\mathbf{J}=\int\boldsymbol{\psi}(s)\boldsymbol{\theta}'(s)ds$, our model can be expressed as $y = \beta_0 + \mathbf{CJb}$. And if we let $\mathbf{Z} = [\mathbf{1}\quad \mathbf{CJ}]$ and $\boldsymbol{\xi} = [\beta_0\quad \mathbf{b}']'$, our model is $\mathbf{y} = \mathbf{Z}\boldsymbol{\xi}$ And this looks much more familiar to us. Now I see you're adding some sort of regularization. The fda package works with roughness penalties of the form $P = \lambda\int[L\beta(s)]^2 ds$ for some linear differential operator $L$. Now it can be shown (details left out here -- it's really not hard to show this) that if we define the penalty matrix $\mathbf{R}$ as $\mathbf{R}= \lambda\left(\begin{array}{cccc} 0 & 0 & \cdots & 0 \\ 0 & R_1 & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & R_K \end{array}\right) $ where $R_i$ is in terms of the basis expansion of $\beta_i$, then we minimize the penalized sum of squares: $\left(\mathbf{y}-\mathbf{Z}\boldsymbol{\xi}\right)'\left(\mathbf{y}-\mathbf{Z}\boldsymbol{\xi}\right) + \lambda\boldsymbol{\xi}'\mathbf{R}\boldsymbol{\xi}$, and so our problem is merely a ridge regression with solution: $\hat{\boldsymbol{\xi}}=(\mathbf{Z}'\mathbf{Z}+\lambda\mathbf{R})^{-1}\mathbf{Z}'\mathbf{y}$. I walked through the above because, (1) I think it's important we understand what we're doing, and (2) some of the above is necessary to understand some of the code I'll use later on. On to the code... Here's a data example with R code. I'm using the Canadian weather dataset provided in the fda package. We'll model the log annual precipitation for a number of weather stations via a functional linear model and we'll use temperature profiles (temperatures were recorded once a day for 365 days) from each station as functional covariates. We'll proceed similarly to the way you describe in your situation. Data was recorded at 35 stations. I'll break the dataset up into 34 stations, which will be used as my data, and the last station, which will be my "new" dataset. I continue via R code and comments (I assume you are familiar enough with the fda package such that nothing in the following is too surprising -- if this isn't the case, please let me know): # pick out data and 'new data' dailydat <- daily$precav[,2:35] dailytemp <- daily$tempav[,2:35] dailydatNew <- daily$precav[,1] dailytempNew <- daily$tempav[,1] # set up response variable annualprec <- log10(apply(dailydat,2,sum)) # create basis objects for and smooth covariate functions tempbasis <- create.fourier.basis(c(0,365),65) tempSmooth <- smooth.basis(day.5,dailytemp,tempbasis) tempfd <- tempSmooth$fd # create design matrix object templist <- vector("list",2) templist[[1]] <- rep(1,34) templist[[2]] <- tempfd # create constant basis (for intercept) and # fourier basis objects for remaining betas conbasis <- create.constant.basis(c(0,365)) betabasis <- create.fourier.basis(c(0,365),35) betalist <- vector("list",2) betalist[[1]] <- conbasis betalist[[2]] <- betabasis # set roughness penalty for betas Lcoef <- c(0,(2*pi/365)^2,0) harmaccelLfd <- vec2Lfd(Lcoef, c(0,365)) lambda <- 10^12.5 betafdPar <- fdPar(betabasis, harmaccelLfd, lambda) betalist[[2]] <- betafdPar # regress annPrecTemp <- fRegress(annualprec, templist, betalist) Now when I was first taught about functional data a year or so ago, I played around with this package. I was also unable to get predict.fRegress to give me what I wanted. Looking back at it now, I still don't know how to make it behave. So, we'll just have to get the predictions semi-manually. I'll be using pieces that I pulled straight out of the code for fRegress(). Again, I continue via code and comments. First, the set-up: # create basis objects for and smooth covariate functions for new data tempSmoothNew <- smooth.basis(day.5,dailytempNew,tempbasis) tempfdNew <- tempSmoothNew$fd # create design matrix object for new data templistNew <- vector("list",2) templistNew[[1]] <- rep(1,1) templistNew[[2]] <- tempfdNew # convert the intercept into an fd object onebasis <- create.constant.basis(c(0,365)) templistNew[[1]] <- fd(matrix(templistNew[[1]],1,1), onebasis) Now to get the predictions $\hat{\mathbf{y}}_{\mathrm{new}}=\mathbf{Z}_{\mathrm{new}}\hat{\boldsymbol{\xi}}$ I just take the code that fRegress uses to calculate yhatfdobj and edit it slightly. fRegress calculates yhatfdobj by estimating the integral $\int_0^T X_i (s) \beta(s)$ via the trapezoid rule (with $X_i$ and $\beta$ expanded in their respective bases). Normally, fRegress calculates the fitted values by looping through the covariates stored in annPrecTemp$xfdlist. So for our problem, we replace this covariate list with the corresponding one in our new covariate list, i.e., templistNew. Here's the code (identical to the code found in fRegress with two edits, some deletions of unneeded code, and a couple comments added): # set up yhat matrix (in our case it's 1x1) yhatmat <- matrix(0,1,1) # loop through covariates p <- length(templistNew) for(j in 1:p){ xfdj <- templistNew[[j]] xbasis <- xfdj$basis xnbasis <- xbasis$nbasis xrng <- xbasis$rangeval nfine <- max(501,10*xnbasis+1) tfine <- seq(xrng[1], xrng[2], len=nfine) deltat <- tfine[2]-tfine[1] xmat <- eval.fd(tfine, xfdj) betafdParj <- annPrecTemp$betaestlist[[j]] betafdj <- betafdParj$fd betamat <- eval.fd(tfine, betafdj) # estimate int(x*beta) via trapezoid rule fitj <- deltat*(crossprod(xmat,betamat) - 0.5*(outer(xmat[1,],betamat[1,]) + outer(xmat[nfine,],betamat[nfine,]))) yhatmat <- yhatmat + fitj } (note: if you look at this chunk and surrounding code in fRegress, you'll see the steps I outlined above). I tested the code by re-running the weather example using all 35 stations as our data and compared the output from the above loop to annPrecTemp$yhatfdobj and everything matches up. I also ran it a couple times using different stations as my "new" data and everything seems reasonable. Let me know if any of the above is unclear or if anything is not working correctly. Sorry for the overly detailed response. I couldn't help myself :) And if you don't already own them, check out the two books I used to write up this response. They are really good books.
Predicting response from new curves using fda package in R
I don't care for fda's use of Inception-like list-within-list-within-list object structures, but my response will abide by the system the package writers have created. I think it's instructive to firs
Predicting response from new curves using fda package in R I don't care for fda's use of Inception-like list-within-list-within-list object structures, but my response will abide by the system the package writers have created. I think it's instructive to first think about what we're doing exactly. Based on your description of what you've done so far, this is what I believe you're doing (let me know if I have misinterpreted something). I'll be continuing using notation and, due to lack of real data, an example from Ramsay and Silverman's Functional Data Analysis and Ramsay, Hooker, and Graves's Functional Data Analysis with R and MATLAB (Some of the following equations and code are lifted directly from these books). We are modelling a scalar response via a functional linear model, i.e. $y_i = \beta_0 + \int_0^T X_i(s)\beta(s)ds + \epsilon_i$ We expand the $\beta$ in some basis. We use, say, $K$ basis functions. So, $\beta(s) = \sum\limits_{k=1}^K b_k\theta_k (s)$ In matrix notation, this is $\beta (s)=\boldsymbol{\theta}'(s)\mathbf{b}$. We also expand the covariate functions in some basis, as well (say $L$ basis functions). So, $X_i(s) = \sum\limits_{k=1}^L c_{ik}\psi_k (s)$ Again, in matrix notation, this is $X(s)=\mathbf{C}\boldsymbol{\psi}(s)$. And thus, if we let $\mathbf{J}=\int\boldsymbol{\psi}(s)\boldsymbol{\theta}'(s)ds$, our model can be expressed as $y = \beta_0 + \mathbf{CJb}$. And if we let $\mathbf{Z} = [\mathbf{1}\quad \mathbf{CJ}]$ and $\boldsymbol{\xi} = [\beta_0\quad \mathbf{b}']'$, our model is $\mathbf{y} = \mathbf{Z}\boldsymbol{\xi}$ And this looks much more familiar to us. Now I see you're adding some sort of regularization. The fda package works with roughness penalties of the form $P = \lambda\int[L\beta(s)]^2 ds$ for some linear differential operator $L$. Now it can be shown (details left out here -- it's really not hard to show this) that if we define the penalty matrix $\mathbf{R}$ as $\mathbf{R}= \lambda\left(\begin{array}{cccc} 0 & 0 & \cdots & 0 \\ 0 & R_1 & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & R_K \end{array}\right) $ where $R_i$ is in terms of the basis expansion of $\beta_i$, then we minimize the penalized sum of squares: $\left(\mathbf{y}-\mathbf{Z}\boldsymbol{\xi}\right)'\left(\mathbf{y}-\mathbf{Z}\boldsymbol{\xi}\right) + \lambda\boldsymbol{\xi}'\mathbf{R}\boldsymbol{\xi}$, and so our problem is merely a ridge regression with solution: $\hat{\boldsymbol{\xi}}=(\mathbf{Z}'\mathbf{Z}+\lambda\mathbf{R})^{-1}\mathbf{Z}'\mathbf{y}$. I walked through the above because, (1) I think it's important we understand what we're doing, and (2) some of the above is necessary to understand some of the code I'll use later on. On to the code... Here's a data example with R code. I'm using the Canadian weather dataset provided in the fda package. We'll model the log annual precipitation for a number of weather stations via a functional linear model and we'll use temperature profiles (temperatures were recorded once a day for 365 days) from each station as functional covariates. We'll proceed similarly to the way you describe in your situation. Data was recorded at 35 stations. I'll break the dataset up into 34 stations, which will be used as my data, and the last station, which will be my "new" dataset. I continue via R code and comments (I assume you are familiar enough with the fda package such that nothing in the following is too surprising -- if this isn't the case, please let me know): # pick out data and 'new data' dailydat <- daily$precav[,2:35] dailytemp <- daily$tempav[,2:35] dailydatNew <- daily$precav[,1] dailytempNew <- daily$tempav[,1] # set up response variable annualprec <- log10(apply(dailydat,2,sum)) # create basis objects for and smooth covariate functions tempbasis <- create.fourier.basis(c(0,365),65) tempSmooth <- smooth.basis(day.5,dailytemp,tempbasis) tempfd <- tempSmooth$fd # create design matrix object templist <- vector("list",2) templist[[1]] <- rep(1,34) templist[[2]] <- tempfd # create constant basis (for intercept) and # fourier basis objects for remaining betas conbasis <- create.constant.basis(c(0,365)) betabasis <- create.fourier.basis(c(0,365),35) betalist <- vector("list",2) betalist[[1]] <- conbasis betalist[[2]] <- betabasis # set roughness penalty for betas Lcoef <- c(0,(2*pi/365)^2,0) harmaccelLfd <- vec2Lfd(Lcoef, c(0,365)) lambda <- 10^12.5 betafdPar <- fdPar(betabasis, harmaccelLfd, lambda) betalist[[2]] <- betafdPar # regress annPrecTemp <- fRegress(annualprec, templist, betalist) Now when I was first taught about functional data a year or so ago, I played around with this package. I was also unable to get predict.fRegress to give me what I wanted. Looking back at it now, I still don't know how to make it behave. So, we'll just have to get the predictions semi-manually. I'll be using pieces that I pulled straight out of the code for fRegress(). Again, I continue via code and comments. First, the set-up: # create basis objects for and smooth covariate functions for new data tempSmoothNew <- smooth.basis(day.5,dailytempNew,tempbasis) tempfdNew <- tempSmoothNew$fd # create design matrix object for new data templistNew <- vector("list",2) templistNew[[1]] <- rep(1,1) templistNew[[2]] <- tempfdNew # convert the intercept into an fd object onebasis <- create.constant.basis(c(0,365)) templistNew[[1]] <- fd(matrix(templistNew[[1]],1,1), onebasis) Now to get the predictions $\hat{\mathbf{y}}_{\mathrm{new}}=\mathbf{Z}_{\mathrm{new}}\hat{\boldsymbol{\xi}}$ I just take the code that fRegress uses to calculate yhatfdobj and edit it slightly. fRegress calculates yhatfdobj by estimating the integral $\int_0^T X_i (s) \beta(s)$ via the trapezoid rule (with $X_i$ and $\beta$ expanded in their respective bases). Normally, fRegress calculates the fitted values by looping through the covariates stored in annPrecTemp$xfdlist. So for our problem, we replace this covariate list with the corresponding one in our new covariate list, i.e., templistNew. Here's the code (identical to the code found in fRegress with two edits, some deletions of unneeded code, and a couple comments added): # set up yhat matrix (in our case it's 1x1) yhatmat <- matrix(0,1,1) # loop through covariates p <- length(templistNew) for(j in 1:p){ xfdj <- templistNew[[j]] xbasis <- xfdj$basis xnbasis <- xbasis$nbasis xrng <- xbasis$rangeval nfine <- max(501,10*xnbasis+1) tfine <- seq(xrng[1], xrng[2], len=nfine) deltat <- tfine[2]-tfine[1] xmat <- eval.fd(tfine, xfdj) betafdParj <- annPrecTemp$betaestlist[[j]] betafdj <- betafdParj$fd betamat <- eval.fd(tfine, betafdj) # estimate int(x*beta) via trapezoid rule fitj <- deltat*(crossprod(xmat,betamat) - 0.5*(outer(xmat[1,],betamat[1,]) + outer(xmat[nfine,],betamat[nfine,]))) yhatmat <- yhatmat + fitj } (note: if you look at this chunk and surrounding code in fRegress, you'll see the steps I outlined above). I tested the code by re-running the weather example using all 35 stations as our data and compared the output from the above loop to annPrecTemp$yhatfdobj and everything matches up. I also ran it a couple times using different stations as my "new" data and everything seems reasonable. Let me know if any of the above is unclear or if anything is not working correctly. Sorry for the overly detailed response. I couldn't help myself :) And if you don't already own them, check out the two books I used to write up this response. They are really good books.
Predicting response from new curves using fda package in R I don't care for fda's use of Inception-like list-within-list-within-list object structures, but my response will abide by the system the package writers have created. I think it's instructive to firs
25,705
Finding number of gaussians in a finite mixture with Wilks' theorem?
With a careful specification of how the null hypothesis is contained in the two-component mixture model, it is possible to see what the problem could be. If the five parameters in the mixture model are $\mu_1, \mu_2, \sigma_1, \sigma_2, \rho$, then $$H_0: (\mu_1 = \mu_2 \text{ and } \sigma_1 = \sigma_2) \text{ or } \rho \in \{0, 1\}.$$ because either the two normal mixture components are equal, in which case the mixture proportion $\rho$ is irrelevant, or the mixture proportion $\rho$ is 0 or 1, in which case one of the mixture components is irrelevant. The conclusion is that the null hypothesis can not be specified, not even locally, as a simple parameter restriction that drops the dimension of the parameter space from 5 to 2. The null hypothesis is a complicated subset of the full parameter space, and under the null the parameters are not even identifiable. The usual assumptions needed to obtain Wilk's theorem break down, most notably it is not possible to construct a proper Taylor expansion of the log-likelihood. I don't have any personal experience with this particular problem, but I know of other cases where parameters "disappear" under the null, which seems to be the case here as well, and in these cases the conclusions of Wilk's theorem break down too. A quick search gave, among other things, this paper that looks relevant, and where you might be able to find further references on the use of the likelihood ratio test in relation to mixture models.
Finding number of gaussians in a finite mixture with Wilks' theorem?
With a careful specification of how the null hypothesis is contained in the two-component mixture model, it is possible to see what the problem could be. If the five parameters in the mixture model ar
Finding number of gaussians in a finite mixture with Wilks' theorem? With a careful specification of how the null hypothesis is contained in the two-component mixture model, it is possible to see what the problem could be. If the five parameters in the mixture model are $\mu_1, \mu_2, \sigma_1, \sigma_2, \rho$, then $$H_0: (\mu_1 = \mu_2 \text{ and } \sigma_1 = \sigma_2) \text{ or } \rho \in \{0, 1\}.$$ because either the two normal mixture components are equal, in which case the mixture proportion $\rho$ is irrelevant, or the mixture proportion $\rho$ is 0 or 1, in which case one of the mixture components is irrelevant. The conclusion is that the null hypothesis can not be specified, not even locally, as a simple parameter restriction that drops the dimension of the parameter space from 5 to 2. The null hypothesis is a complicated subset of the full parameter space, and under the null the parameters are not even identifiable. The usual assumptions needed to obtain Wilk's theorem break down, most notably it is not possible to construct a proper Taylor expansion of the log-likelihood. I don't have any personal experience with this particular problem, but I know of other cases where parameters "disappear" under the null, which seems to be the case here as well, and in these cases the conclusions of Wilk's theorem break down too. A quick search gave, among other things, this paper that looks relevant, and where you might be able to find further references on the use of the likelihood ratio test in relation to mixture models.
Finding number of gaussians in a finite mixture with Wilks' theorem? With a careful specification of how the null hypothesis is contained in the two-component mixture model, it is possible to see what the problem could be. If the five parameters in the mixture model ar
25,706
Finding number of gaussians in a finite mixture with Wilks' theorem?
Inference on the number of mixing components does not satisfy the needed regularity conditions for Wilks theorem since (a) the parameter $\rho$ is on the boundary of the parameter space and (b) the parametrisation is unidentifiable under the null. This is not to say that the distribution of the generalized likelihood ratio is unknown! If all the 5 parameters in your setup are unknown, and more importantly- unbounded- then the distribution of the LR statistic does not converge. If all the unidentifiable parameters are bounded, then the LR statistic is monotone in the supremum of a truncated Gaussian process. The covariance of which is not easy to compute in the general (5 parameter) case, and even when you have it- the distribution of the supremum of such a process is not easily approximated. For some practical results regarding the two-component mixture see here. Interestingly, the paper shows that in rather simple setups, the LR statistic is actually less powerful than some simpler statistics. For the seminal paper on deriving the asymptotic distribution in such problems see here. For all practical purposes, you can fit the mixture using an EM, and then Bootstrap the distribution of the LR statistic. This might take some time as the EM is known to be slow, and you need many replication to capture the effect of the sample size. See here for details.
Finding number of gaussians in a finite mixture with Wilks' theorem?
Inference on the number of mixing components does not satisfy the needed regularity conditions for Wilks theorem since (a) the parameter $\rho$ is on the boundary of the parameter space and (b) the pa
Finding number of gaussians in a finite mixture with Wilks' theorem? Inference on the number of mixing components does not satisfy the needed regularity conditions for Wilks theorem since (a) the parameter $\rho$ is on the boundary of the parameter space and (b) the parametrisation is unidentifiable under the null. This is not to say that the distribution of the generalized likelihood ratio is unknown! If all the 5 parameters in your setup are unknown, and more importantly- unbounded- then the distribution of the LR statistic does not converge. If all the unidentifiable parameters are bounded, then the LR statistic is monotone in the supremum of a truncated Gaussian process. The covariance of which is not easy to compute in the general (5 parameter) case, and even when you have it- the distribution of the supremum of such a process is not easily approximated. For some practical results regarding the two-component mixture see here. Interestingly, the paper shows that in rather simple setups, the LR statistic is actually less powerful than some simpler statistics. For the seminal paper on deriving the asymptotic distribution in such problems see here. For all practical purposes, you can fit the mixture using an EM, and then Bootstrap the distribution of the LR statistic. This might take some time as the EM is known to be slow, and you need many replication to capture the effect of the sample size. See here for details.
Finding number of gaussians in a finite mixture with Wilks' theorem? Inference on the number of mixing components does not satisfy the needed regularity conditions for Wilks theorem since (a) the parameter $\rho$ is on the boundary of the parameter space and (b) the pa
25,707
Apriori algorithm in plain English?
The Wikipedia article is not particularly impressive. You might find these slides more helpful: 1, 2, 3. At each level $k$, you have $k$-item sets which are frequent (have sufficent support). At the next level, the $k$+$1$-item sets you need to consider must have the property that each of their subsets must be frequent (have sufficent support). This is the apriori property: any subset of frequent itemset must be frequent. So if you know at level 2 that the sets $\{1,2\}$, $\{1,3\}$, $\{1,5\}$ and $\{3,5\}$ are the only sets with sufficient support, then at level 3 you join these with each other to produce $\{1,2,3\}$, $\{1,2,5\}$, $\{1,3,5\}$ and $\{2,3,5\}$ but you need only consider $\{1,3,5\}$ further: the others each have subsets with insufficent support (such as $\{2,3\}$ or $\{2,5\}$ ).
Apriori algorithm in plain English?
The Wikipedia article is not particularly impressive. You might find these slides more helpful: 1, 2, 3. At each level $k$, you have $k$-item sets which are frequent (have sufficent support). At th
Apriori algorithm in plain English? The Wikipedia article is not particularly impressive. You might find these slides more helpful: 1, 2, 3. At each level $k$, you have $k$-item sets which are frequent (have sufficent support). At the next level, the $k$+$1$-item sets you need to consider must have the property that each of their subsets must be frequent (have sufficent support). This is the apriori property: any subset of frequent itemset must be frequent. So if you know at level 2 that the sets $\{1,2\}$, $\{1,3\}$, $\{1,5\}$ and $\{3,5\}$ are the only sets with sufficient support, then at level 3 you join these with each other to produce $\{1,2,3\}$, $\{1,2,5\}$, $\{1,3,5\}$ and $\{2,3,5\}$ but you need only consider $\{1,3,5\}$ further: the others each have subsets with insufficent support (such as $\{2,3\}$ or $\{2,5\}$ ).
Apriori algorithm in plain English? The Wikipedia article is not particularly impressive. You might find these slides more helpful: 1, 2, 3. At each level $k$, you have $k$-item sets which are frequent (have sufficent support). At th
25,708
Apriori algorithm in plain English?
Apriori algorithm is an association rule mining algorithm used in data mining. It is used to find the frequent itemset among the given number of transactions. It consists of basically two steps Self-Join Pruning Repeating these steps k times, where k is the number of items, in the last iteration you get frequent item sets containing k items. Look here for a very simple explanation with a detailed example http://nikhilvithlani.blogspot.com/2012/03/apriori-algorithm-for-data-mining-made.html. It has a simple explanation without any complicated equations.
Apriori algorithm in plain English?
Apriori algorithm is an association rule mining algorithm used in data mining. It is used to find the frequent itemset among the given number of transactions. It consists of basically two steps Self
Apriori algorithm in plain English? Apriori algorithm is an association rule mining algorithm used in data mining. It is used to find the frequent itemset among the given number of transactions. It consists of basically two steps Self-Join Pruning Repeating these steps k times, where k is the number of items, in the last iteration you get frequent item sets containing k items. Look here for a very simple explanation with a detailed example http://nikhilvithlani.blogspot.com/2012/03/apriori-algorithm-for-data-mining-made.html. It has a simple explanation without any complicated equations.
Apriori algorithm in plain English? Apriori algorithm is an association rule mining algorithm used in data mining. It is used to find the frequent itemset among the given number of transactions. It consists of basically two steps Self
25,709
Apriori algorithm in plain English?
Apriori in plain English. Apriori employs an iterative approach known as level-wise search, where k-itemsets are used to explore (k+1)-itemsets. First, the set of frequent 1-itemsets is found by scanning the database to accumulate the count for each item, and collecting those items that satisfy minimum support. The resulting set is denoted as L1. Next, L1 is used to find L2, the set of frequent 2-itemsets, which is used to find L3, and so on, until no more frequent k-itemsets can be found. The finding of each Lk requires one full scan of the database. At final iteration you will end up with many k-itemsets which is basically called association rules. To select interesting rules from the set of all possible rules various constraint measures such as support and confidence is applied. Terms & Terminologies 1-itemsets means {a} , {b} , {c} 2-itemsets means {a, b} , {d, d} , {a, c} K-itemsets means {i1, i2, i3,... ik}, {j1, j2, j3, .... jk} Join step : meaning 1-itemset is made to self join with itself to generate 2-itemsets. Prune step : here resulting set from join is filtered with minimum support threshold. cardinality set : resulting set from Prune step . Support = no.of transcations containing 'a' and 'b' / total no of transaction. Support => supp(a,b) => p(a U b) Confident = No.of transactions containing 'a' and 'b' / no of transaction containing 'a'. Confident => con (a, b) == > P (b|a) nothing but conditional probability.
Apriori algorithm in plain English?
Apriori in plain English. Apriori employs an iterative approach known as level-wise search, where k-itemsets are used to explore (k+1)-itemsets. First, the set of frequent 1-itemsets is found by scann
Apriori algorithm in plain English? Apriori in plain English. Apriori employs an iterative approach known as level-wise search, where k-itemsets are used to explore (k+1)-itemsets. First, the set of frequent 1-itemsets is found by scanning the database to accumulate the count for each item, and collecting those items that satisfy minimum support. The resulting set is denoted as L1. Next, L1 is used to find L2, the set of frequent 2-itemsets, which is used to find L3, and so on, until no more frequent k-itemsets can be found. The finding of each Lk requires one full scan of the database. At final iteration you will end up with many k-itemsets which is basically called association rules. To select interesting rules from the set of all possible rules various constraint measures such as support and confidence is applied. Terms & Terminologies 1-itemsets means {a} , {b} , {c} 2-itemsets means {a, b} , {d, d} , {a, c} K-itemsets means {i1, i2, i3,... ik}, {j1, j2, j3, .... jk} Join step : meaning 1-itemset is made to self join with itself to generate 2-itemsets. Prune step : here resulting set from join is filtered with minimum support threshold. cardinality set : resulting set from Prune step . Support = no.of transcations containing 'a' and 'b' / total no of transaction. Support => supp(a,b) => p(a U b) Confident = No.of transactions containing 'a' and 'b' / no of transaction containing 'a'. Confident => con (a, b) == > P (b|a) nothing but conditional probability.
Apriori algorithm in plain English? Apriori in plain English. Apriori employs an iterative approach known as level-wise search, where k-itemsets are used to explore (k+1)-itemsets. First, the set of frequent 1-itemsets is found by scann
25,710
Improving the SVM classification of diabetes
I have 4 suggestions: How are you choosing the variables to include in your model? Maybe you are missing some the key indicators from the larger dataset. Almost all of the indicators you are using (such as sex, smoker, etc.) should be treated as factors. Treating these variables as numeric is wrong, and is probably contributing to the error in your model. Why are you using an SVM? Did you try any simpler methods, such as linear discriminant analysis or even linear regression? Maybe a simple approach on a larger dataset will yield a better result. Try the caret package. It will help you cross-validate model accuracy, it is parallelized which will let you work faster, and it makes it easy to explore different types of models. Here is some example code for caret: library(caret) #Parallize library(doSMP) w <- startWorkers() registerDoSMP(w) #Build model X <- train.set[,-1] Y <- factor(train.set[,1],levels=c('N','Y')) model <- train(X,Y,method='lda') #Evaluate model on test set print(model) predY <- predict(model,test.set[,-1]) confusionMatrix(predY,test.set[,1]) stopWorkers(w) This LDA model beats your SVM, and I didn't even fix your factors. I'm sure if you recode Sex, Smoker, etc. as factors, you will get better results.
Improving the SVM classification of diabetes
I have 4 suggestions: How are you choosing the variables to include in your model? Maybe you are missing some the key indicators from the larger dataset. Almost all of the indicators you are using (
Improving the SVM classification of diabetes I have 4 suggestions: How are you choosing the variables to include in your model? Maybe you are missing some the key indicators from the larger dataset. Almost all of the indicators you are using (such as sex, smoker, etc.) should be treated as factors. Treating these variables as numeric is wrong, and is probably contributing to the error in your model. Why are you using an SVM? Did you try any simpler methods, such as linear discriminant analysis or even linear regression? Maybe a simple approach on a larger dataset will yield a better result. Try the caret package. It will help you cross-validate model accuracy, it is parallelized which will let you work faster, and it makes it easy to explore different types of models. Here is some example code for caret: library(caret) #Parallize library(doSMP) w <- startWorkers() registerDoSMP(w) #Build model X <- train.set[,-1] Y <- factor(train.set[,1],levels=c('N','Y')) model <- train(X,Y,method='lda') #Evaluate model on test set print(model) predY <- predict(model,test.set[,-1]) confusionMatrix(predY,test.set[,1]) stopWorkers(w) This LDA model beats your SVM, and I didn't even fix your factors. I'm sure if you recode Sex, Smoker, etc. as factors, you will get better results.
Improving the SVM classification of diabetes I have 4 suggestions: How are you choosing the variables to include in your model? Maybe you are missing some the key indicators from the larger dataset. Almost all of the indicators you are using (
25,711
Improving the SVM classification of diabetes
If you are using a linear kernel, then it is possible that feature selection is a bad idea, and that regularisation can prevent over-fitting more effectively than feature selection can. Note that the performance bounds that the SVM approximately implements are independent of the dimension of the feature space, which was one of the selling points of the SVM.
Improving the SVM classification of diabetes
If you are using a linear kernel, then it is possible that feature selection is a bad idea, and that regularisation can prevent over-fitting more effectively than feature selection can. Note that the
Improving the SVM classification of diabetes If you are using a linear kernel, then it is possible that feature selection is a bad idea, and that regularisation can prevent over-fitting more effectively than feature selection can. Note that the performance bounds that the SVM approximately implements are independent of the dimension of the feature space, which was one of the selling points of the SVM.
Improving the SVM classification of diabetes If you are using a linear kernel, then it is possible that feature selection is a bad idea, and that regularisation can prevent over-fitting more effectively than feature selection can. Note that the
25,712
Improving the SVM classification of diabetes
I've had this problem recently and found a couple of things that help. First, try out a Naive Bayes model (package klaR) which sometimes gives you better results when the minority class in a classification problem is tiny. Also, if you do choose to stick with an SVM you might want to try oversampling the minority class. Essentially you'll want to include more examples of the minority class or synthetically create cases for the minority class This paper :http://www.it.iitb.ac.in/~kamlesh/Page/Reports/highlySkewed.pdf Has some discussion and examples of these techniques implemented in Weka, but implimenting them yourself in R is possible too.
Improving the SVM classification of diabetes
I've had this problem recently and found a couple of things that help. First, try out a Naive Bayes model (package klaR) which sometimes gives you better results when the minority class in a classific
Improving the SVM classification of diabetes I've had this problem recently and found a couple of things that help. First, try out a Naive Bayes model (package klaR) which sometimes gives you better results when the minority class in a classification problem is tiny. Also, if you do choose to stick with an SVM you might want to try oversampling the minority class. Essentially you'll want to include more examples of the minority class or synthetically create cases for the minority class This paper :http://www.it.iitb.ac.in/~kamlesh/Page/Reports/highlySkewed.pdf Has some discussion and examples of these techniques implemented in Weka, but implimenting them yourself in R is possible too.
Improving the SVM classification of diabetes I've had this problem recently and found a couple of things that help. First, try out a Naive Bayes model (package klaR) which sometimes gives you better results when the minority class in a classific
25,713
Improving the SVM classification of diabetes
In addition to what has already been mentioned, you are fixing your best model to use a linear kernel. You should predict using the best model that was tuned, including the same kernel that was used/found in your tuning stage (which I assume is RBF since your are tuning gamma).
Improving the SVM classification of diabetes
In addition to what has already been mentioned, you are fixing your best model to use a linear kernel. You should predict using the best model that was tuned, including the same kernel that was used/f
Improving the SVM classification of diabetes In addition to what has already been mentioned, you are fixing your best model to use a linear kernel. You should predict using the best model that was tuned, including the same kernel that was used/found in your tuning stage (which I assume is RBF since your are tuning gamma).
Improving the SVM classification of diabetes In addition to what has already been mentioned, you are fixing your best model to use a linear kernel. You should predict using the best model that was tuned, including the same kernel that was used/f
25,714
What kind of residuals and Cook's distance are used for GLM?
If you take a look at the code (simple type plot.lm, without parenthesis, or edit(plot.lm) at the R prompt), you'll see that Cook's distances are defined line 44, with the cooks.distance() function. To see what it does, type stats:::cooks.distance.glm at the R prompt. There you see that it is defined as (res/(1 - hat))^2 * hat/(dispersion * p) where res are Pearson residuals (as returned by the influence() function), hat is the hat matrix, p is the number of parameters in the model, and dispersion is the dispersion considered for the current model (fixed at one for logistic and Poisson regression, see help(glm)). In sum, it is computed as a function of the leverage of the observations and their standardized residuals. (Compare with stats:::cooks.distance.lm.) For a more formal reference you can follow references in the plot.lm() function, namely Belsley, D. A., Kuh, E. and Welsch, R. E. (1980). Regression Diagnostics. New York: Wiley. Moreover, about the additional information displayed in the graphics, we can look further and see that R uses plot(xx, rsp, ... # line 230 panel(xx, rsp, ...) # line 233 cl.h <- sqrt(crit * p * (1 - hh)/hh) # line 243 lines(hh, cl.h, lty = 2, col = 2) # lines(hh, -cl.h, lty = 2, col = 2) # where rsp is labeled as Std. Pearson resid. in case of a GLM, Std. residuals otherwise (line 172); in both cases, however, the formula used by R is (lines 175 and 178) residuals(x, "pearson") / s * sqrt(1 - hii) where hii is the hat matrix returned by the generic function lm.influence(). This is the usual formula for std. residuals: $$rs_j=\frac{r_j}{\sqrt{1-\hat h_j}}$$ where $j$ here denotes the $j$th covariate of interest. See e.g., Agresti Categorical Data Analysis, §4.5.5. The next lines of R code draw a smoother for Cook's distance (add.smooth=TRUE in plot.lm() by default, see getOption("add.smooth")) and contour lines (not visible in your plot) for critical standardized residuals (see the cook.levels= option).
What kind of residuals and Cook's distance are used for GLM?
If you take a look at the code (simple type plot.lm, without parenthesis, or edit(plot.lm) at the R prompt), you'll see that Cook's distances are defined line 44, with the cooks.distance() function. T
What kind of residuals and Cook's distance are used for GLM? If you take a look at the code (simple type plot.lm, without parenthesis, or edit(plot.lm) at the R prompt), you'll see that Cook's distances are defined line 44, with the cooks.distance() function. To see what it does, type stats:::cooks.distance.glm at the R prompt. There you see that it is defined as (res/(1 - hat))^2 * hat/(dispersion * p) where res are Pearson residuals (as returned by the influence() function), hat is the hat matrix, p is the number of parameters in the model, and dispersion is the dispersion considered for the current model (fixed at one for logistic and Poisson regression, see help(glm)). In sum, it is computed as a function of the leverage of the observations and their standardized residuals. (Compare with stats:::cooks.distance.lm.) For a more formal reference you can follow references in the plot.lm() function, namely Belsley, D. A., Kuh, E. and Welsch, R. E. (1980). Regression Diagnostics. New York: Wiley. Moreover, about the additional information displayed in the graphics, we can look further and see that R uses plot(xx, rsp, ... # line 230 panel(xx, rsp, ...) # line 233 cl.h <- sqrt(crit * p * (1 - hh)/hh) # line 243 lines(hh, cl.h, lty = 2, col = 2) # lines(hh, -cl.h, lty = 2, col = 2) # where rsp is labeled as Std. Pearson resid. in case of a GLM, Std. residuals otherwise (line 172); in both cases, however, the formula used by R is (lines 175 and 178) residuals(x, "pearson") / s * sqrt(1 - hii) where hii is the hat matrix returned by the generic function lm.influence(). This is the usual formula for std. residuals: $$rs_j=\frac{r_j}{\sqrt{1-\hat h_j}}$$ where $j$ here denotes the $j$th covariate of interest. See e.g., Agresti Categorical Data Analysis, §4.5.5. The next lines of R code draw a smoother for Cook's distance (add.smooth=TRUE in plot.lm() by default, see getOption("add.smooth")) and contour lines (not visible in your plot) for critical standardized residuals (see the cook.levels= option).
What kind of residuals and Cook's distance are used for GLM? If you take a look at the code (simple type plot.lm, without parenthesis, or edit(plot.lm) at the R prompt), you'll see that Cook's distances are defined line 44, with the cooks.distance() function. T
25,715
References on numerical optimization for statisticians
James Gentle's Computational Statistics (2009). James Gentle's Matrix algebra: theory, computations, and applications in statistics‎ (2007), more so towards the end of the book, the beginning is great too but it's not exactly what you're looking for. Christopher M. Bishop's Pattern Recognition (2006). Hastie et al.'s The elements of statistical learning: data mining, inference, and prediction‎ (2009). Are you looking for something as low-level as a text that will answer a question such as: "Why is it more efficient to store matrices and higher dimensional arrays as a 1-D array, and how can I index them in the usual M(0, 1, 3, ...) way?" or something like "What are some common techniques used to optimize standard algorithms such as gradient descent, EM, etc.?"? Most texts on machine learning will provide in-depth discussions of the topic(s) you're looking for.
References on numerical optimization for statisticians
James Gentle's Computational Statistics (2009). James Gentle's Matrix algebra: theory, computations, and applications in statistics‎ (2007), more so towards the end of the book, the beginning is great
References on numerical optimization for statisticians James Gentle's Computational Statistics (2009). James Gentle's Matrix algebra: theory, computations, and applications in statistics‎ (2007), more so towards the end of the book, the beginning is great too but it's not exactly what you're looking for. Christopher M. Bishop's Pattern Recognition (2006). Hastie et al.'s The elements of statistical learning: data mining, inference, and prediction‎ (2009). Are you looking for something as low-level as a text that will answer a question such as: "Why is it more efficient to store matrices and higher dimensional arrays as a 1-D array, and how can I index them in the usual M(0, 1, 3, ...) way?" or something like "What are some common techniques used to optimize standard algorithms such as gradient descent, EM, etc.?"? Most texts on machine learning will provide in-depth discussions of the topic(s) you're looking for.
References on numerical optimization for statisticians James Gentle's Computational Statistics (2009). James Gentle's Matrix algebra: theory, computations, and applications in statistics‎ (2007), more so towards the end of the book, the beginning is great
25,716
References on numerical optimization for statisticians
Nocedal and Wrights book http://users.eecs.northwestern.edu/~nocedal/book/ is a good reference for optimization in general, and many things in their book are of interest to a statistician. There is also a whole chapter on non-linear least squares.
References on numerical optimization for statisticians
Nocedal and Wrights book http://users.eecs.northwestern.edu/~nocedal/book/ is a good reference for optimization in general, and many things in their book are of interest to a statistician. There is al
References on numerical optimization for statisticians Nocedal and Wrights book http://users.eecs.northwestern.edu/~nocedal/book/ is a good reference for optimization in general, and many things in their book are of interest to a statistician. There is also a whole chapter on non-linear least squares.
References on numerical optimization for statisticians Nocedal and Wrights book http://users.eecs.northwestern.edu/~nocedal/book/ is a good reference for optimization in general, and many things in their book are of interest to a statistician. There is al
25,717
References on numerical optimization for statisticians
Optimization, by Kenneth Lange (Springer, 2004), reviewed in JASA by Russell Steele. It's a good textbook with Gentle's Matrix algebra for an introductory course on Matrix Calculus and Optimization, like the one by Jan de Leeuw (courses/202B).
References on numerical optimization for statisticians
Optimization, by Kenneth Lange (Springer, 2004), reviewed in JASA by Russell Steele. It's a good textbook with Gentle's Matrix algebra for an introductory course on Matrix Calculus and Optimization, l
References on numerical optimization for statisticians Optimization, by Kenneth Lange (Springer, 2004), reviewed in JASA by Russell Steele. It's a good textbook with Gentle's Matrix algebra for an introductory course on Matrix Calculus and Optimization, like the one by Jan de Leeuw (courses/202B).
References on numerical optimization for statisticians Optimization, by Kenneth Lange (Springer, 2004), reviewed in JASA by Russell Steele. It's a good textbook with Gentle's Matrix algebra for an introductory course on Matrix Calculus and Optimization, l
25,718
References on numerical optimization for statisticians
As a supplement to these, you may find Magnus, J. R., and H. Neudecker (2007). Matrix Calculus with Applications in Statistics and Econometrics, 3rd ed useful albeit heavy. It develops a full treatment of infinitesimal operations with matrices, and then applies them on a number of typical statistical tasks such as optimization, MLE and non-linear least squares. If in the end of the day you will end up figuring out backward stability of your matrix algorithms, good grasp of matrix calculus will be indispensable. I personally used the tools of matrix calculus in deriving asymptotic results in spatial statistics and multivariate parametric models.
References on numerical optimization for statisticians
As a supplement to these, you may find Magnus, J. R., and H. Neudecker (2007). Matrix Calculus with Applications in Statistics and Econometrics, 3rd ed useful albeit heavy. It develops a full treatmen
References on numerical optimization for statisticians As a supplement to these, you may find Magnus, J. R., and H. Neudecker (2007). Matrix Calculus with Applications in Statistics and Econometrics, 3rd ed useful albeit heavy. It develops a full treatment of infinitesimal operations with matrices, and then applies them on a number of typical statistical tasks such as optimization, MLE and non-linear least squares. If in the end of the day you will end up figuring out backward stability of your matrix algorithms, good grasp of matrix calculus will be indispensable. I personally used the tools of matrix calculus in deriving asymptotic results in spatial statistics and multivariate parametric models.
References on numerical optimization for statisticians As a supplement to these, you may find Magnus, J. R., and H. Neudecker (2007). Matrix Calculus with Applications in Statistics and Econometrics, 3rd ed useful albeit heavy. It develops a full treatmen
25,719
How do you tell whether good performances come in streaks?
The Wald-Wolfowitz Runs Test seems to be a possible candidate, where a "run" is what you called a "streak". It requires dichotomous data, so you'd have to label each solve as "bad" vs. "good" according to some threshold - like the median time as you suggested. The null hypothesis is that "good" and "bad" solves alternate randomly. A one-sided alternative hypothesis corresponding to your intuition is that "good" solves clump together in long streaks, implying that there are fewer runs than expected with random data. Test statistic is the number of runs. In R: > N <- 200 # number of solves > DV <- round(runif(N, 15, 30), 1) # simulate some uniform data > thresh <- median(DV) # threshold for binary classification # do the binary classification > DVfac <- cut(DV, breaks=c(-Inf, thresh, Inf), labels=c("good", "bad")) > Nj <- table(DVfac) # number of "good" and "bad" solves > n1 <- Nj[1] # number of "good" solves > n2 <- Nj[2] # number of "bad" solves > (runs <- rle(as.character(DVfac))) # analysis of runs Run Length Encoding lengths: int [1:92] 2 1 2 4 1 4 3 4 2 5 ... values : chr [1:92] "bad" "good" "bad" "good" "bad" "good" "bad" ... > (nRuns <- length(runs$lengths)) # test statistic: observed number of runs [1] 92 # theoretical maximum of runs for given n1, n2 > (rMax <- ifelse(n1 == n2, N, 2*min(n1, n2) + 1)) 199 When you only have a few observations, you can calculate the exact probabilities for each number of runs under the null hypothesis. Otherwise, the distribution of "number of runs" can be approximated by a standard normal distribution. > (muR <- 1 + ((2*n1*n2) / N)) # expected value 100.99 > varR <- (2*n1*n2*(2*n1*n2 - N)) / (N^2 * (N-1)) # theoretical variance > rZ <- (nRuns-muR) / sqrt(varR) # z-score > (pVal <- pnorm(rZ, mean=0, sd=1)) # one-sided p-value 0.1012055 The p-value is for the one-sided alternative hypothesis that "good" solves come in streaks.
How do you tell whether good performances come in streaks?
The Wald-Wolfowitz Runs Test seems to be a possible candidate, where a "run" is what you called a "streak". It requires dichotomous data, so you'd have to label each solve as "bad" vs. "good" accordin
How do you tell whether good performances come in streaks? The Wald-Wolfowitz Runs Test seems to be a possible candidate, where a "run" is what you called a "streak". It requires dichotomous data, so you'd have to label each solve as "bad" vs. "good" according to some threshold - like the median time as you suggested. The null hypothesis is that "good" and "bad" solves alternate randomly. A one-sided alternative hypothesis corresponding to your intuition is that "good" solves clump together in long streaks, implying that there are fewer runs than expected with random data. Test statistic is the number of runs. In R: > N <- 200 # number of solves > DV <- round(runif(N, 15, 30), 1) # simulate some uniform data > thresh <- median(DV) # threshold for binary classification # do the binary classification > DVfac <- cut(DV, breaks=c(-Inf, thresh, Inf), labels=c("good", "bad")) > Nj <- table(DVfac) # number of "good" and "bad" solves > n1 <- Nj[1] # number of "good" solves > n2 <- Nj[2] # number of "bad" solves > (runs <- rle(as.character(DVfac))) # analysis of runs Run Length Encoding lengths: int [1:92] 2 1 2 4 1 4 3 4 2 5 ... values : chr [1:92] "bad" "good" "bad" "good" "bad" "good" "bad" ... > (nRuns <- length(runs$lengths)) # test statistic: observed number of runs [1] 92 # theoretical maximum of runs for given n1, n2 > (rMax <- ifelse(n1 == n2, N, 2*min(n1, n2) + 1)) 199 When you only have a few observations, you can calculate the exact probabilities for each number of runs under the null hypothesis. Otherwise, the distribution of "number of runs" can be approximated by a standard normal distribution. > (muR <- 1 + ((2*n1*n2) / N)) # expected value 100.99 > varR <- (2*n1*n2*(2*n1*n2 - N)) / (N^2 * (N-1)) # theoretical variance > rZ <- (nRuns-muR) / sqrt(varR) # z-score > (pVal <- pnorm(rZ, mean=0, sd=1)) # one-sided p-value 0.1012055 The p-value is for the one-sided alternative hypothesis that "good" solves come in streaks.
How do you tell whether good performances come in streaks? The Wald-Wolfowitz Runs Test seems to be a possible candidate, where a "run" is what you called a "streak". It requires dichotomous data, so you'd have to label each solve as "bad" vs. "good" accordin
25,720
How do you tell whether good performances come in streaks?
A few thoughts: Plot the distribution of times. My guess is that they will be positively skewed, such that some solution times are really slow. In that case you might want to consider a log or some other transformation of solution times. Create a scatter plot of trial on the x axis and solution time (or log solution time on the y-axis). This should give you an intuitive understanding of the data. It may also reveal other kinds of trends besides the "hot streak". Consider whether there is a learning effect over time. With most puzzles, you get quicker with practice. The plot should help to reveal whether this is the case. Such an effect is different to a "hot streak" effect. It will lead to correlation between trials because when you are first learning, slow trials will co-occur with other slow trials, and as you get more experienced, faster trials will co-occur with faster trials. Consider your conceptual definition of "hot streaks". For example, does it only apply to trials that are proximate in time or is about proximity of order. Say you solved the cube quickly on Tuesday, and then had a break and on the next Friday you solved it quickly. Is this a hot streak, or does it only count if you do it on the same day? Are there other effects that might be distinct from a hot streak effect? E.g., time of day that you solve the puzzle (e.g., fatigue), degree to which you are actually trying hard? etc. Once the alternative systematic effects have been understood, you could develop a model that includes as many of them as possible. You could plot the residual on the y axis and trial on the x-axis. Then you could see whether there are auto-correlations in the residuals in the model. This auto-correlation would provide some evidence of hot streaks. However, an alternative interpretation is that there is some other systematic effect that you have not excluded.
How do you tell whether good performances come in streaks?
A few thoughts: Plot the distribution of times. My guess is that they will be positively skewed, such that some solution times are really slow. In that case you might want to consider a log or some o
How do you tell whether good performances come in streaks? A few thoughts: Plot the distribution of times. My guess is that they will be positively skewed, such that some solution times are really slow. In that case you might want to consider a log or some other transformation of solution times. Create a scatter plot of trial on the x axis and solution time (or log solution time on the y-axis). This should give you an intuitive understanding of the data. It may also reveal other kinds of trends besides the "hot streak". Consider whether there is a learning effect over time. With most puzzles, you get quicker with practice. The plot should help to reveal whether this is the case. Such an effect is different to a "hot streak" effect. It will lead to correlation between trials because when you are first learning, slow trials will co-occur with other slow trials, and as you get more experienced, faster trials will co-occur with faster trials. Consider your conceptual definition of "hot streaks". For example, does it only apply to trials that are proximate in time or is about proximity of order. Say you solved the cube quickly on Tuesday, and then had a break and on the next Friday you solved it quickly. Is this a hot streak, or does it only count if you do it on the same day? Are there other effects that might be distinct from a hot streak effect? E.g., time of day that you solve the puzzle (e.g., fatigue), degree to which you are actually trying hard? etc. Once the alternative systematic effects have been understood, you could develop a model that includes as many of them as possible. You could plot the residual on the y axis and trial on the x-axis. Then you could see whether there are auto-correlations in the residuals in the model. This auto-correlation would provide some evidence of hot streaks. However, an alternative interpretation is that there is some other systematic effect that you have not excluded.
How do you tell whether good performances come in streaks? A few thoughts: Plot the distribution of times. My guess is that they will be positively skewed, such that some solution times are really slow. In that case you might want to consider a log or some o
25,721
How do you tell whether good performances come in streaks?
Calculate correlogram for your process. If your process is gaussian (by the looks of your sample it is) you can establish lower/upper bounds (B) and check if the correlations at given lag are significant. Positive autocorrelation at lag 1 would indicate existence of "streaks of luck".
How do you tell whether good performances come in streaks?
Calculate correlogram for your process. If your process is gaussian (by the looks of your sample it is) you can establish lower/upper bounds (B) and check if the correlations at given lag are signific
How do you tell whether good performances come in streaks? Calculate correlogram for your process. If your process is gaussian (by the looks of your sample it is) you can establish lower/upper bounds (B) and check if the correlations at given lag are significant. Positive autocorrelation at lag 1 would indicate existence of "streaks of luck".
How do you tell whether good performances come in streaks? Calculate correlogram for your process. If your process is gaussian (by the looks of your sample it is) you can establish lower/upper bounds (B) and check if the correlations at given lag are signific
25,722
How do you tell whether good performances come in streaks?
Before looking at any formal tests, I would suggest you begin by looking at an autocorrelation plot for your data, to see if the solve-time is correlated with previous solve-times at past lag values. If you get "hot streaks" in your performance then this should manifest as positive autocorrelation over at least one lag, and possibly a few more. You might be able to model your solve-times with some kind of time-series process with one or more auto-correlation terms, and then formally test for "hot streaks" by testing for non-zero autocorrelation in the process.
How do you tell whether good performances come in streaks?
Before looking at any formal tests, I would suggest you begin by looking at an autocorrelation plot for your data, to see if the solve-time is correlated with previous solve-times at past lag values.
How do you tell whether good performances come in streaks? Before looking at any formal tests, I would suggest you begin by looking at an autocorrelation plot for your data, to see if the solve-time is correlated with previous solve-times at past lag values. If you get "hot streaks" in your performance then this should manifest as positive autocorrelation over at least one lag, and possibly a few more. You might be able to model your solve-times with some kind of time-series process with one or more auto-correlation terms, and then formally test for "hot streaks" by testing for non-zero autocorrelation in the process.
How do you tell whether good performances come in streaks? Before looking at any formal tests, I would suggest you begin by looking at an autocorrelation plot for your data, to see if the solve-time is correlated with previous solve-times at past lag values.
25,723
How do you tell whether good performances come in streaks?
I think there are several issues here the most pertinent being that presumably the gap between individual solves isn't the same. You may have to define a "maximum gap" so that you can treat the data as if it is sequential, however that will probably create a whole bunch of partitions in your data. I.e. instead of having one long sequence of solve times, you'd have a whole bunch of separate sequences. I think what you're asking essential is if the the present solve time is conditionally independent to the one before it. There are myriad ways to test for that specific condition. Here is a few Bayesian approaches: https://www.bnlearn.com/examples/ci.test/
How do you tell whether good performances come in streaks?
I think there are several issues here the most pertinent being that presumably the gap between individual solves isn't the same. You may have to define a "maximum gap" so that you can treat the data a
How do you tell whether good performances come in streaks? I think there are several issues here the most pertinent being that presumably the gap between individual solves isn't the same. You may have to define a "maximum gap" so that you can treat the data as if it is sequential, however that will probably create a whole bunch of partitions in your data. I.e. instead of having one long sequence of solve times, you'd have a whole bunch of separate sequences. I think what you're asking essential is if the the present solve time is conditionally independent to the one before it. There are myriad ways to test for that specific condition. Here is a few Bayesian approaches: https://www.bnlearn.com/examples/ci.test/
How do you tell whether good performances come in streaks? I think there are several issues here the most pertinent being that presumably the gap between individual solves isn't the same. You may have to define a "maximum gap" so that you can treat the data a
25,724
Why vertical distances?
OLS (ordinary least squares) assumes that the values represented by the horizontal distances are either predetermined by the experimenter or measured with high accuracy (relative to the vertical distances). When there is a question of uncertainty in the horizontal distances, you shouldn't be using OLS, but instead should look into errors-in-variables models or, possibly, principal components analysis.
Why vertical distances?
OLS (ordinary least squares) assumes that the values represented by the horizontal distances are either predetermined by the experimenter or measured with high accuracy (relative to the vertical dista
Why vertical distances? OLS (ordinary least squares) assumes that the values represented by the horizontal distances are either predetermined by the experimenter or measured with high accuracy (relative to the vertical distances). When there is a question of uncertainty in the horizontal distances, you shouldn't be using OLS, but instead should look into errors-in-variables models or, possibly, principal components analysis.
Why vertical distances? OLS (ordinary least squares) assumes that the values represented by the horizontal distances are either predetermined by the experimenter or measured with high accuracy (relative to the vertical dista
25,725
Why vertical distances?
Interesting Question. My answer would be that when we are fitting an OLS model we are implicitly and primarily trying to predict/explain the dependent variable at hand - the "Y" in the "Y vs X." As such, our main concern would be to minimize the distance from our fitted line to the actual observations with respect to the outcome, which means minimizing the vertical distance. This of course defines the residuals. Also, least squares formulas are easier to derive than most other competing methods, which is perhaps why it came around first. :P As 'whuber' alludes to above, there are other approaches that treat X and Y with equal emphasis when fitting a best-fit line. One such approach that I'm aware of is "principal lines" or "principal curves" regression, which minimizes the orthogonal distances between the points and the line (instead of a vertical error lines you have ones at 90 degrees to the fitted line). I post one reference below for your reading. It's lengthy but very accessible and enlightening. Hope this helps, Brenden Trevor Hastie. Principal Curves and Surfaces, PhD thesis, Stanford University; 1984
Why vertical distances?
Interesting Question. My answer would be that when we are fitting an OLS model we are implicitly and primarily trying to predict/explain the dependent variable at hand - the "Y" in the "Y vs X." As su
Why vertical distances? Interesting Question. My answer would be that when we are fitting an OLS model we are implicitly and primarily trying to predict/explain the dependent variable at hand - the "Y" in the "Y vs X." As such, our main concern would be to minimize the distance from our fitted line to the actual observations with respect to the outcome, which means minimizing the vertical distance. This of course defines the residuals. Also, least squares formulas are easier to derive than most other competing methods, which is perhaps why it came around first. :P As 'whuber' alludes to above, there are other approaches that treat X and Y with equal emphasis when fitting a best-fit line. One such approach that I'm aware of is "principal lines" or "principal curves" regression, which minimizes the orthogonal distances between the points and the line (instead of a vertical error lines you have ones at 90 degrees to the fitted line). I post one reference below for your reading. It's lengthy but very accessible and enlightening. Hope this helps, Brenden Trevor Hastie. Principal Curves and Surfaces, PhD thesis, Stanford University; 1984
Why vertical distances? Interesting Question. My answer would be that when we are fitting an OLS model we are implicitly and primarily trying to predict/explain the dependent variable at hand - the "Y" in the "Y vs X." As su
25,726
Why vertical distances?
It possibly also relates to designed experiments - if x is a controlled quantity that is part of the experimental design, it is treated as deterministic; whilst y is the outcome, and is a random quantity. x might be a continuous quantity (eg concentration of some drug) but could be a 0/1 split (leading to a 2 sample t-test assuming y is Gaussian). If x is a continuous quantity there may be some measurement error, but typically if this is much smaller than the variability of y then this is ignored.
Why vertical distances?
It possibly also relates to designed experiments - if x is a controlled quantity that is part of the experimental design, it is treated as deterministic; whilst y is the outcome, and is a random qua
Why vertical distances? It possibly also relates to designed experiments - if x is a controlled quantity that is part of the experimental design, it is treated as deterministic; whilst y is the outcome, and is a random quantity. x might be a continuous quantity (eg concentration of some drug) but could be a 0/1 split (leading to a 2 sample t-test assuming y is Gaussian). If x is a continuous quantity there may be some measurement error, but typically if this is much smaller than the variability of y then this is ignored.
Why vertical distances? It possibly also relates to designed experiments - if x is a controlled quantity that is part of the experimental design, it is treated as deterministic; whilst y is the outcome, and is a random qua
25,727
How do I order or rank a set of experts?
People have invented numerous systems for rating things (like experts) on multiple criteria: visit the Wikipedia page on Multi-criteria decision analysis for a list. Not well represented there, though, is one of the most defensible methods out there: Multi attribute valuation theory. This includes a set of methods to evaluate trade-offs among sets of criteria in order to (a) determine an appropriate way to re-express values of the individual variables and (b) weight the re-expressed values to obtain a score for ranking. The principles are simple and defensible, the mathematics is unimpeachable, and there's nothing fancy about the theory. More people should know and practice these methods rather than inventing arbitrary scoring systems.
How do I order or rank a set of experts?
People have invented numerous systems for rating things (like experts) on multiple criteria: visit the Wikipedia page on Multi-criteria decision analysis for a list. Not well represented there, thoug
How do I order or rank a set of experts? People have invented numerous systems for rating things (like experts) on multiple criteria: visit the Wikipedia page on Multi-criteria decision analysis for a list. Not well represented there, though, is one of the most defensible methods out there: Multi attribute valuation theory. This includes a set of methods to evaluate trade-offs among sets of criteria in order to (a) determine an appropriate way to re-express values of the individual variables and (b) weight the re-expressed values to obtain a score for ranking. The principles are simple and defensible, the mathematics is unimpeachable, and there's nothing fancy about the theory. More people should know and practice these methods rather than inventing arbitrary scoring systems.
How do I order or rank a set of experts? People have invented numerous systems for rating things (like experts) on multiple criteria: visit the Wikipedia page on Multi-criteria decision analysis for a list. Not well represented there, thoug
25,728
How do I order or rank a set of experts?
Ultimately this may not be solely a statistical exercise. PCA is a very powerful quantitative method that will allow you to generate a score or weights on its first few principal components that you can use for ranking. However, explaining what the principal components are is very challenging. They are quantitative constructs. They are not dialectic ones. Thus, to explain what they truly mean is sometimes not possible. This is especially true if you have an audience that is not quantitative. They will have no idea what you are talking about. And, will think of your PCA as some cryptic black box. Instead, I would simply line up all the relevant variables and use a weighting system based on what one thinks the weighting should be. I think if you develop this for outsiders, customers, users, it would be great if you could embed the flexibility of deciding on the weighting to the users. Some users may value years of experience much more than certification and vice verse. If you can leave that decision to them. This way your algorithm is not a black box they don't understand and they are not comfortable with. You keep it totally transparent and up to them based on their own relative valuation of what matters.
How do I order or rank a set of experts?
Ultimately this may not be solely a statistical exercise. PCA is a very powerful quantitative method that will allow you to generate a score or weights on its first few principal components that you
How do I order or rank a set of experts? Ultimately this may not be solely a statistical exercise. PCA is a very powerful quantitative method that will allow you to generate a score or weights on its first few principal components that you can use for ranking. However, explaining what the principal components are is very challenging. They are quantitative constructs. They are not dialectic ones. Thus, to explain what they truly mean is sometimes not possible. This is especially true if you have an audience that is not quantitative. They will have no idea what you are talking about. And, will think of your PCA as some cryptic black box. Instead, I would simply line up all the relevant variables and use a weighting system based on what one thinks the weighting should be. I think if you develop this for outsiders, customers, users, it would be great if you could embed the flexibility of deciding on the weighting to the users. Some users may value years of experience much more than certification and vice verse. If you can leave that decision to them. This way your algorithm is not a black box they don't understand and they are not comfortable with. You keep it totally transparent and up to them based on their own relative valuation of what matters.
How do I order or rank a set of experts? Ultimately this may not be solely a statistical exercise. PCA is a very powerful quantitative method that will allow you to generate a score or weights on its first few principal components that you
25,729
How do I order or rank a set of experts?
Do you think that you could quantify all those attributes? If yes, I would suggest performing a principal component analysis. In the general case where all the correlations are positive (and if they aren't, you can easily get there using some transformation), the first principal component can be considered as a measure of the total importance of the expert, since it's a weighted average of all the attributes (and the weights would be the corresponding contributions of the variables - Under this perspective, the method itself will reveal the importance of each attribute). The score that each expert achieves in the first principal component is what you need to rank them.
How do I order or rank a set of experts?
Do you think that you could quantify all those attributes? If yes, I would suggest performing a principal component analysis. In the general case where all the correlations are positive (and if they
How do I order or rank a set of experts? Do you think that you could quantify all those attributes? If yes, I would suggest performing a principal component analysis. In the general case where all the correlations are positive (and if they aren't, you can easily get there using some transformation), the first principal component can be considered as a measure of the total importance of the expert, since it's a weighted average of all the attributes (and the weights would be the corresponding contributions of the variables - Under this perspective, the method itself will reveal the importance of each attribute). The score that each expert achieves in the first principal component is what you need to rank them.
How do I order or rank a set of experts? Do you think that you could quantify all those attributes? If yes, I would suggest performing a principal component analysis. In the general case where all the correlations are positive (and if they
25,730
Is quantile regression a maximum likelihood method?
You seem to confuse two closely-related yet very different concepts: a regression model (which is a specification of a statistical model) and a parameter estimation method (which essentially is a data-based objective function formulation and subsequent numerical procedures). For simplicity, we restrict ourselves to the linear parametric family. A quantile regression (model) models (i.e., approximates) the $\tau$-th conditional quantile of the response $y$ given predictors $x$ as a linear function of parameters: \begin{align} Q_\tau(y|x) = \alpha + \beta'x. \tag{1} \end{align} Likewise, a mean regression (model) models the conditional mean of the response $y$ given predictors $x$ as a linear function of parameters: \begin{align} E(y|x) = \alpha + \beta'x. \tag{2} \end{align} In principle (of course, it is somewhat a quite narrow view), $(1)$ standalone is the heart of "quantile regression" -- we do not need to understand how parameters $\alpha$ and $\beta$ will be estimated to specify a quantile regression model. The parameter estimation problem kicks in when a sample $\{(y_i, x_i): i = 1, \ldots, n\}$ is observed. As you may have already known, typically $\alpha$ and $\beta$ are estimated by minimizing the sum of check function: \begin{align} (\hat{\alpha}, \hat{\beta}) = \operatorname{argmin}_{\alpha, \beta}\sum_{i = 1}^n \rho_\tau(y_i - \alpha - \beta'x_i), \tag{3} \end{align} which is numerically implemented by the linear programming or interior point algorithm. Of course, this is one of many parameter estimation methods (when $\tau = 0.5$, this is usually referred to as Least Absolute Deviation Estimation), which, as you stated, does not require any distributional assumption of $y$. The MLE, as another parameter estimation method, on the other hand, can be carried out only if one specifies the complete conditional distribution of $y$. That means, to do maximum likelihood estimation, you will need to specify a statistical model that is more granular than regression models such as $(1)$ or $(2)$ (it is more granular because the complete distribution function contains much more information than the quantile function or the mean function only. In fact, both $Q_\tau(y|x)$ and $E(y|x)$ can be derived probabilistically from the distribution of $y|x$). For example, a statistical model like \begin{align} y | x \sim f(\alpha + \beta'x; \theta), \tag{4} \end{align} where $f$ is some known density function with additional parameter $\theta$. Model $(4)$ then entails the likelihood function (assuming the observations are i.i.d.) \begin{align} L(\alpha, \beta; \theta) = \prod_{i = 1}^nf(\alpha + \beta x_i; \theta), \end{align} which can be maximized over the parameter space to determine MLE. It is well-known that when $f$ is Gaussian, Model $(4)$ implies the mean regression model $(2)$, and when $f$ is (asymmetrical) Laplacian, Model $(4)$ implies the quantile regression model $(1)$. For other conditional distributions $f$, in general $(1)$ or $(2)$ are not nested in $(4)$ (that is, neither $Q_\tau(y|x)$ nor $E(y|x)$ admits the simple linear form $\alpha + \beta'x$ under $(4)$). In summary, the question "Is quantile regression a maximum likelihood method?" is somewhat ill-posed because the former is a statistical model while the latter is a parameter estimation method that depends on a more granular statistical model than the quantile regression model. In this sense, I do not think these two concepts are comparable. If by "what is the broader term for methods like quantile regression?", you meant "what is the parameter estimation method typically used to estimate $(\alpha, \beta)$ in $(1)$?", then the answer is $(3)$ -- I am not sure if there is a universally accepted term for this minimization problem, but it may be OK to call it "least $L^1$ estimation", in view of $\rho_\tau(t) = t(\tau - I_{(-\infty, 0)}(t))$ is a piecewise linear function.
Is quantile regression a maximum likelihood method?
You seem to confuse two closely-related yet very different concepts: a regression model (which is a specification of a statistical model) and a parameter estimation method (which essentially is a data
Is quantile regression a maximum likelihood method? You seem to confuse two closely-related yet very different concepts: a regression model (which is a specification of a statistical model) and a parameter estimation method (which essentially is a data-based objective function formulation and subsequent numerical procedures). For simplicity, we restrict ourselves to the linear parametric family. A quantile regression (model) models (i.e., approximates) the $\tau$-th conditional quantile of the response $y$ given predictors $x$ as a linear function of parameters: \begin{align} Q_\tau(y|x) = \alpha + \beta'x. \tag{1} \end{align} Likewise, a mean regression (model) models the conditional mean of the response $y$ given predictors $x$ as a linear function of parameters: \begin{align} E(y|x) = \alpha + \beta'x. \tag{2} \end{align} In principle (of course, it is somewhat a quite narrow view), $(1)$ standalone is the heart of "quantile regression" -- we do not need to understand how parameters $\alpha$ and $\beta$ will be estimated to specify a quantile regression model. The parameter estimation problem kicks in when a sample $\{(y_i, x_i): i = 1, \ldots, n\}$ is observed. As you may have already known, typically $\alpha$ and $\beta$ are estimated by minimizing the sum of check function: \begin{align} (\hat{\alpha}, \hat{\beta}) = \operatorname{argmin}_{\alpha, \beta}\sum_{i = 1}^n \rho_\tau(y_i - \alpha - \beta'x_i), \tag{3} \end{align} which is numerically implemented by the linear programming or interior point algorithm. Of course, this is one of many parameter estimation methods (when $\tau = 0.5$, this is usually referred to as Least Absolute Deviation Estimation), which, as you stated, does not require any distributional assumption of $y$. The MLE, as another parameter estimation method, on the other hand, can be carried out only if one specifies the complete conditional distribution of $y$. That means, to do maximum likelihood estimation, you will need to specify a statistical model that is more granular than regression models such as $(1)$ or $(2)$ (it is more granular because the complete distribution function contains much more information than the quantile function or the mean function only. In fact, both $Q_\tau(y|x)$ and $E(y|x)$ can be derived probabilistically from the distribution of $y|x$). For example, a statistical model like \begin{align} y | x \sim f(\alpha + \beta'x; \theta), \tag{4} \end{align} where $f$ is some known density function with additional parameter $\theta$. Model $(4)$ then entails the likelihood function (assuming the observations are i.i.d.) \begin{align} L(\alpha, \beta; \theta) = \prod_{i = 1}^nf(\alpha + \beta x_i; \theta), \end{align} which can be maximized over the parameter space to determine MLE. It is well-known that when $f$ is Gaussian, Model $(4)$ implies the mean regression model $(2)$, and when $f$ is (asymmetrical) Laplacian, Model $(4)$ implies the quantile regression model $(1)$. For other conditional distributions $f$, in general $(1)$ or $(2)$ are not nested in $(4)$ (that is, neither $Q_\tau(y|x)$ nor $E(y|x)$ admits the simple linear form $\alpha + \beta'x$ under $(4)$). In summary, the question "Is quantile regression a maximum likelihood method?" is somewhat ill-posed because the former is a statistical model while the latter is a parameter estimation method that depends on a more granular statistical model than the quantile regression model. In this sense, I do not think these two concepts are comparable. If by "what is the broader term for methods like quantile regression?", you meant "what is the parameter estimation method typically used to estimate $(\alpha, \beta)$ in $(1)$?", then the answer is $(3)$ -- I am not sure if there is a universally accepted term for this minimization problem, but it may be OK to call it "least $L^1$ estimation", in view of $\rho_\tau(t) = t(\tau - I_{(-\infty, 0)}(t))$ is a piecewise linear function.
Is quantile regression a maximum likelihood method? You seem to confuse two closely-related yet very different concepts: a regression model (which is a specification of a statistical model) and a parameter estimation method (which essentially is a data
25,731
Is quantile regression a maximum likelihood method?
It depends on the loss function you're trying to minimize. In MLE you're not always assuming that the distribution is gaussian. For instance, there's a relation between the distribution you assume and the loss function you try to minimize Gaussian distribution $\propto e^{-(x-\mu)^2}$ implies $L^2$ loss Laplace distribution $\propto e^{-|x-\mu|}$ implies $L^1$ loss In the case of Gaussian distribution $$ P(y|x) = N(y| f(x;\theta), \sigma^2) $$ where $\sigma$ is fixed. Therefore the likelihood estimation is is $$ \theta^* = \text{arg max}_\theta \prod_i P(y_i|x_i) = \text{arg max}_\theta \sum_i \log P(x_i | y_i) $$ and therefore $$ \theta^* = \text{arg max} -n \log \sigma - \frac{n}{2} \log (2\pi) -\frac{1}{2} \sum_i \left(\frac{y_i - f(x_i, \theta)}{\sigma}\right)^2 $$ which removing constant terms is $$ \theta^* = \text{argmax}_\theta -\sum_i \left(y_i - f(x_i, \theta)\right)^2 $$ which is the standard $L^2$ loss function for regression problems. So, as you can see by defining a loss function you're also defining which distribution you assume of your data. In the case of quantile regression is the same. Depending on your loss function you'll implicitly be specifying an underlying distribution.
Is quantile regression a maximum likelihood method?
It depends on the loss function you're trying to minimize. In MLE you're not always assuming that the distribution is gaussian. For instance, there's a relation between the distribution you assume and
Is quantile regression a maximum likelihood method? It depends on the loss function you're trying to minimize. In MLE you're not always assuming that the distribution is gaussian. For instance, there's a relation between the distribution you assume and the loss function you try to minimize Gaussian distribution $\propto e^{-(x-\mu)^2}$ implies $L^2$ loss Laplace distribution $\propto e^{-|x-\mu|}$ implies $L^1$ loss In the case of Gaussian distribution $$ P(y|x) = N(y| f(x;\theta), \sigma^2) $$ where $\sigma$ is fixed. Therefore the likelihood estimation is is $$ \theta^* = \text{arg max}_\theta \prod_i P(y_i|x_i) = \text{arg max}_\theta \sum_i \log P(x_i | y_i) $$ and therefore $$ \theta^* = \text{arg max} -n \log \sigma - \frac{n}{2} \log (2\pi) -\frac{1}{2} \sum_i \left(\frac{y_i - f(x_i, \theta)}{\sigma}\right)^2 $$ which removing constant terms is $$ \theta^* = \text{argmax}_\theta -\sum_i \left(y_i - f(x_i, \theta)\right)^2 $$ which is the standard $L^2$ loss function for regression problems. So, as you can see by defining a loss function you're also defining which distribution you assume of your data. In the case of quantile regression is the same. Depending on your loss function you'll implicitly be specifying an underlying distribution.
Is quantile regression a maximum likelihood method? It depends on the loss function you're trying to minimize. In MLE you're not always assuming that the distribution is gaussian. For instance, there's a relation between the distribution you assume and
25,732
Is quantile regression a maximum likelihood method?
Quantile Regression is not necessarily a maximum likelihood method (while it can be when using a working likelihood like the asymmetric Laplace distribution). Performing empirical risk minimization with the quantile loss is not (necessarily) a maximum likelihood estimation method. You can simply minimize this special risk and can show for arbitrary distributions that it result in an estimation of the quantile: https://en.m.wikipedia.org/wiki/Empirical_risk_minimization The proof for this goes by defining the risk as the expected loss function: $R_\tau = \int_R dy p(y) w_\tau(y,\hat{y}) |y-\hat{y}|$ splitting each integral explicitly to resolve the absolute value $|y-\hat{y}|$ taking the derivative with respect to $\hat{y}$ and setting it to zero identify the definition of the $\tau$ quantile All this works without assuming a special probability density p, so it is definitely not a maximum likelihood estimation. This is also how we can show that the expected mean squared minimization estimates the (conditional) mean and the mean absolute error estimates the (conditional) median.
Is quantile regression a maximum likelihood method?
Quantile Regression is not necessarily a maximum likelihood method (while it can be when using a working likelihood like the asymmetric Laplace distribution). Performing empirical risk minimization wi
Is quantile regression a maximum likelihood method? Quantile Regression is not necessarily a maximum likelihood method (while it can be when using a working likelihood like the asymmetric Laplace distribution). Performing empirical risk minimization with the quantile loss is not (necessarily) a maximum likelihood estimation method. You can simply minimize this special risk and can show for arbitrary distributions that it result in an estimation of the quantile: https://en.m.wikipedia.org/wiki/Empirical_risk_minimization The proof for this goes by defining the risk as the expected loss function: $R_\tau = \int_R dy p(y) w_\tau(y,\hat{y}) |y-\hat{y}|$ splitting each integral explicitly to resolve the absolute value $|y-\hat{y}|$ taking the derivative with respect to $\hat{y}$ and setting it to zero identify the definition of the $\tau$ quantile All this works without assuming a special probability density p, so it is definitely not a maximum likelihood estimation. This is also how we can show that the expected mean squared minimization estimates the (conditional) mean and the mean absolute error estimates the (conditional) median.
Is quantile regression a maximum likelihood method? Quantile Regression is not necessarily a maximum likelihood method (while it can be when using a working likelihood like the asymmetric Laplace distribution). Performing empirical risk minimization wi
25,733
If $Y$ is independent of $X_{1}$ and $X_{2}$, does it indicate $Y$ is also independent of $X_{1}+X_{2}$?
Somewhat surprisingly, this is not necessarily true. For example, consider the joint probability distribution described by the following table. $Y$ $X_1$ $X_2$ prob 0 1 0 0.25 1 1 1 0.25 1 0 0 0.25 0 0 1 0.25 Each of the three random variables follows marginally a Bernoulli($0.5$) distribution, and it is very easy to confirm that $Y \perp X_1$ and $Y \perp X_2$. However, consider that the probability $$P(Y=1, \ X_1 + X_2 = 1) = 0$$ while on the other hand $$P(Y=1)P(X_1+X_2 = 1) = \frac{1}{2}\times\frac{1}{2} = 0.25.$$ Thus, $Y$ is not independent of $X_1 + X_2$.
If $Y$ is independent of $X_{1}$ and $X_{2}$, does it indicate $Y$ is also independent of $X_{1}+X_{
Somewhat surprisingly, this is not necessarily true. For example, consider the joint probability distribution described by the following table. $Y$ $X_1$ $X_2$ prob 0 1 0 0.25 1 1 1 0.25 1
If $Y$ is independent of $X_{1}$ and $X_{2}$, does it indicate $Y$ is also independent of $X_{1}+X_{2}$? Somewhat surprisingly, this is not necessarily true. For example, consider the joint probability distribution described by the following table. $Y$ $X_1$ $X_2$ prob 0 1 0 0.25 1 1 1 0.25 1 0 0 0.25 0 0 1 0.25 Each of the three random variables follows marginally a Bernoulli($0.5$) distribution, and it is very easy to confirm that $Y \perp X_1$ and $Y \perp X_2$. However, consider that the probability $$P(Y=1, \ X_1 + X_2 = 1) = 0$$ while on the other hand $$P(Y=1)P(X_1+X_2 = 1) = \frac{1}{2}\times\frac{1}{2} = 0.25.$$ Thus, $Y$ is not independent of $X_1 + X_2$.
If $Y$ is independent of $X_{1}$ and $X_{2}$, does it indicate $Y$ is also independent of $X_{1}+X_{ Somewhat surprisingly, this is not necessarily true. For example, consider the joint probability distribution described by the following table. $Y$ $X_1$ $X_2$ prob 0 1 0 0.25 1 1 1 0.25 1
25,734
Plain English explanation of Ito's integral?
Ito's integral has nothing to do with the area under a curve and no connection with rectangles, random or otherwise. Let me try to share a motivation in the simplest language I can manage. There's really no better justification for Ito's formula than talking about stock prices, so let's suppose we have a stock, United Marshmallow, and an old-fashioned stock ticker. Let's suppose that, at each tick, the price of United Marshmallow goes up by 1 or down by 1. Let's say the stock price starts at 10, and the next six prices are 11, 12, 11, 12, 11, 10. In other words, the fluctuations in prices are: $$+1, +1, -1, +1, -1, -1$$ (I know that under this model, the stock price could go negative, but let's ignore that for now.) Let's say we're a trader and we want to come up with a strategy for trading this stock. At time $t$, all we know is what's happened at that time, so whatever amount of stock we choose to buy (or sell) at time $t$ cannot depend on information after time $t$. Let $W_t$ be the total fluctuation in the stock up to time $t$. We get this by adding up the fluctuations up to that time. So $W_1 = 1$, $W_2 = 2$, $W_3 = 1$, $W_4 = 2$, $W_5 = 1$, $W_6 = 0$. One simple trading strategy is to buy $W_t$ shares at time $t$ and sell them at time $t+1$. The idea here is that, if the stock has gone up a lot, then we should be more inclined to make a bet on it going up again, and if it's gone down a lot, we should be inclined to bet on it going down again. Note that $W_t$ can be negative, which would correspond to selling the stock (short sales are allowed) and then buying it back again. The profit from this strategy is just the sum over the amount we buy at time $t$ multiplied by fluctuation in price from time $t$ to time $t+1$ $$\sum_t W_t (W_{t+1} - W_t)$$ It looks a bit like a Riemann sum, but it's not, because the price can go down, so the "base" of the "rectangle" makes no sense. And also, our $W_t$ has to be strictly on the left-hand side of the interval from $t$ to $t+1$, or else we'd be using future information. Let's look at the cumulative profit we would get if we did this strategy at each possible time point. After time $1$, we bet $W_1 = 1$ dollars, and the next fluctuation is $+1$, so our profit so far is $1 \times 1 = 1$. Next, we bet $W_2 = 2$ dollars, but then the stock goes down, so our "profit" is $2 \times -1 = -2$. The overall profit so far is $1 -2 = -1$. Continuing in this fashion, we get the following table: time $t$ 2 3 4 5 6 cumulative profit by time $t$ 1 -1 0 -2 -3 Now let's compare this with an integral. We are doing some sort of "integral" of the function $f(W) = W$, so maybe there's a relationship with the integral of this function? time $t$ 2 3 4 5 6 cumulative profit by time $t$ 1 -1 0 -2 -3 $W_t$ 2 1 2 1 0 $W_t^2/2$ 2 1/2 2 1/2 0 Perhaps you notice that they match up exactly if you subtract $t/2$. time $t$ 2 3 4 5 6 cumulative profit by time $t$ 1 -1 0 -2 -3 $W_t$ 2 1 2 1 0 $W_t^2/2$ 2 1/2 2 1/2 0 $W_t^2/2 - t/2$ 1 -1 0 -2 -3 We get $\sum^t W_t(W_{t+1} - W_t) = W_t^2/2 - t/2$. You can do the same calculation with any other sequence of $+1$ and $-1$ as the price fluctuations and it will still be true! This is the mathematical fact that underpins Ito calculus. If you take some sort of limit, time becomes continuous, $W_t$ becomes Brownian motion, and you get the famous formula $$\int_0^t W(t) dW = W(t)^2/2 - t/2$$ Here, both sides are random variables. But the reason why the formula is true is not because of some application of the central limit theorem. It's because the mathematical fact that we checked in the example above holds for any set of fluctuations we could have chosen. This formula extends to functions of $W(t)$, and you get the chain rule of Ito calculus. To summarise, Ito's integral is really a way to calculate the (random) profit from a strategy which someone would make if they were trading a stock which moved up and down randomly. It's not an attempt to compute the area under any kind of curve, and it doesn't have much to do with the Riemann integral, except for a superficial similarity in the definition, and absolutely nothing to do with the Lebesgue integral, except that Lebesgue integration is required to make the "passage to the limit" part work formally.
Plain English explanation of Ito's integral?
Ito's integral has nothing to do with the area under a curve and no connection with rectangles, random or otherwise. Let me try to share a motivation in the simplest language I can manage. There's rea
Plain English explanation of Ito's integral? Ito's integral has nothing to do with the area under a curve and no connection with rectangles, random or otherwise. Let me try to share a motivation in the simplest language I can manage. There's really no better justification for Ito's formula than talking about stock prices, so let's suppose we have a stock, United Marshmallow, and an old-fashioned stock ticker. Let's suppose that, at each tick, the price of United Marshmallow goes up by 1 or down by 1. Let's say the stock price starts at 10, and the next six prices are 11, 12, 11, 12, 11, 10. In other words, the fluctuations in prices are: $$+1, +1, -1, +1, -1, -1$$ (I know that under this model, the stock price could go negative, but let's ignore that for now.) Let's say we're a trader and we want to come up with a strategy for trading this stock. At time $t$, all we know is what's happened at that time, so whatever amount of stock we choose to buy (or sell) at time $t$ cannot depend on information after time $t$. Let $W_t$ be the total fluctuation in the stock up to time $t$. We get this by adding up the fluctuations up to that time. So $W_1 = 1$, $W_2 = 2$, $W_3 = 1$, $W_4 = 2$, $W_5 = 1$, $W_6 = 0$. One simple trading strategy is to buy $W_t$ shares at time $t$ and sell them at time $t+1$. The idea here is that, if the stock has gone up a lot, then we should be more inclined to make a bet on it going up again, and if it's gone down a lot, we should be inclined to bet on it going down again. Note that $W_t$ can be negative, which would correspond to selling the stock (short sales are allowed) and then buying it back again. The profit from this strategy is just the sum over the amount we buy at time $t$ multiplied by fluctuation in price from time $t$ to time $t+1$ $$\sum_t W_t (W_{t+1} - W_t)$$ It looks a bit like a Riemann sum, but it's not, because the price can go down, so the "base" of the "rectangle" makes no sense. And also, our $W_t$ has to be strictly on the left-hand side of the interval from $t$ to $t+1$, or else we'd be using future information. Let's look at the cumulative profit we would get if we did this strategy at each possible time point. After time $1$, we bet $W_1 = 1$ dollars, and the next fluctuation is $+1$, so our profit so far is $1 \times 1 = 1$. Next, we bet $W_2 = 2$ dollars, but then the stock goes down, so our "profit" is $2 \times -1 = -2$. The overall profit so far is $1 -2 = -1$. Continuing in this fashion, we get the following table: time $t$ 2 3 4 5 6 cumulative profit by time $t$ 1 -1 0 -2 -3 Now let's compare this with an integral. We are doing some sort of "integral" of the function $f(W) = W$, so maybe there's a relationship with the integral of this function? time $t$ 2 3 4 5 6 cumulative profit by time $t$ 1 -1 0 -2 -3 $W_t$ 2 1 2 1 0 $W_t^2/2$ 2 1/2 2 1/2 0 Perhaps you notice that they match up exactly if you subtract $t/2$. time $t$ 2 3 4 5 6 cumulative profit by time $t$ 1 -1 0 -2 -3 $W_t$ 2 1 2 1 0 $W_t^2/2$ 2 1/2 2 1/2 0 $W_t^2/2 - t/2$ 1 -1 0 -2 -3 We get $\sum^t W_t(W_{t+1} - W_t) = W_t^2/2 - t/2$. You can do the same calculation with any other sequence of $+1$ and $-1$ as the price fluctuations and it will still be true! This is the mathematical fact that underpins Ito calculus. If you take some sort of limit, time becomes continuous, $W_t$ becomes Brownian motion, and you get the famous formula $$\int_0^t W(t) dW = W(t)^2/2 - t/2$$ Here, both sides are random variables. But the reason why the formula is true is not because of some application of the central limit theorem. It's because the mathematical fact that we checked in the example above holds for any set of fluctuations we could have chosen. This formula extends to functions of $W(t)$, and you get the chain rule of Ito calculus. To summarise, Ito's integral is really a way to calculate the (random) profit from a strategy which someone would make if they were trading a stock which moved up and down randomly. It's not an attempt to compute the area under any kind of curve, and it doesn't have much to do with the Riemann integral, except for a superficial similarity in the definition, and absolutely nothing to do with the Lebesgue integral, except that Lebesgue integration is required to make the "passage to the limit" part work formally.
Plain English explanation of Ito's integral? Ito's integral has nothing to do with the area under a curve and no connection with rectangles, random or otherwise. Let me try to share a motivation in the simplest language I can manage. There's rea
25,735
Plain English explanation of Ito's integral?
I think you're confusing the Lebesgue integral with Itô calculus. They are related concepts. I'll explain. Lebesgue vs Riemann The simplest explanation of the difference between Lebesgue and Riemann integration - that I know of - follows. Imagine a bunch of bank notes tossed on a carpet. Riemann would count the money by first drawing a rectangular grid on a carpet, then adding up bank notes row by row. Lebesgue, would rather count number of 1-dollar bills, then 5-dollar bills, then 10-dollar bills etc. Then simply sum up: $1\times n_1+5\times n_5+10\times n_{10} \dots$ Why would you need Lebesgue integral if we already have Riemann? The reason is that the latter doesn't work on functions that are not flat at small scales. Consider any ordinary function you know of, e.g. $\exp$ or $\sin$: if you look at the small enough interval $\delta x$ the function will be flat between $x$ and $x+\delta x$. Some functions don't flatten when you take a magnifying glass and zoom in. They stay rough at any scale, then Riemann integration fails, and you need something else. Here comes the Lebesgue integral to save the day (in some cases). Itô integration Suppose you need to sum a value of fruit basket. Easy: $V=n\times p $, where $n,p$ - quantity and price of a fruit. If both $n$ and $p$ are stochastic, then you must apply Itô calculus because $dV\ne \frac{\partial V}{\partial n}dn+ \frac{\partial V}{\partial p}dp$. Here's an [almost] plain English explanation. If we're control the amount of fruit ourselves, then $n$ is deterministic, i.e. we know in advance how much fruit we hold at any time $t$ in future. However, we're likely do not know the prices, they are stochastic. The good thing is that we may know the parameters of the stochastic process, e.g. $p(t)-p(0)\equiv \Delta p(t)\sim\mathcal N(0,t)$. Now, to forecast $p$ we simply need to integrate it: $p(t)=p(0)+\xi_t$, where $\xi_t\sim\mathcal N(0,t)$ Now the value of the basket is simply: $V(t)=n\times p(t)$ or in Itô integral formulation: $dV(t)=n\times dp(t)$ So far so good, and it doesn't seem like this Itô integral is any different from Riemann. Here's where it gets interesting: what if we're valuing someone else's fruit basket, where we don't know how much fruit is held at any time $t$ $n(t)=?$. It is a stochastic process though, and we may know its parameters, e.g. $dn(t)\sim\mathcal N(0,t)$ Can we get a process for the value of the basket $V(t)$? Because if we did, then we could integrate again: $V(t)=V(0)+\int_0^tdV(t)$ Riemann would say that it's easy: $dV=\left(dn\times p+n\times dp\right)$ - it's a usual full differential, and it's WRONG. That's where the Itô integral comes up: $dV=\left(dn\times p+n\times dp+dn\times dp\right)$. WTH did the last term $dn\times dp$ come from?! Consider the value of a basket at time 0 and time $t$:$$V(0)=n(0)\times p(0)\\V(t)= n(t)\times p(t)$$ Look at the difference: $$\Delta V(t)\equiv V(t)-V(0)= n(0)\times [p(t)-p(0)]+[n(t)-n(0)]\times p(0)+[n(t)-n(0)]\times[p(t)-p(0)] = \Delta n\times p(0)+n(0)\times\Delta p+\Delta n\times\Delta p$$ This corresponds to the Itô calculus $dV$ above. How are these related? If you have a function $V(t)$ where $t$ is a deterministic variable such as time, then usual calculus and Riemann integration works: $dV(t)=\frac{\partial V}{\partial t}dt$ If your function has stochastic variables $V(t,p)$ such as price of financial assets $p$, then Itô calculus and Lebesgue integration is in order: $dV(t)\ne\frac{\partial V}{\partial t}dt+\frac{\partial V}{\partial p}dp(t)$ The example with a fruit basket was a very simple function $V(n,p)=n\times p$, where we can get to the answer without Itô calculus formalism, but if you apply Itô calculus you get the same answer.
Plain English explanation of Ito's integral?
I think you're confusing the Lebesgue integral with Itô calculus. They are related concepts. I'll explain. Lebesgue vs Riemann The simplest explanation of the difference between Lebesgue and Riemann i
Plain English explanation of Ito's integral? I think you're confusing the Lebesgue integral with Itô calculus. They are related concepts. I'll explain. Lebesgue vs Riemann The simplest explanation of the difference between Lebesgue and Riemann integration - that I know of - follows. Imagine a bunch of bank notes tossed on a carpet. Riemann would count the money by first drawing a rectangular grid on a carpet, then adding up bank notes row by row. Lebesgue, would rather count number of 1-dollar bills, then 5-dollar bills, then 10-dollar bills etc. Then simply sum up: $1\times n_1+5\times n_5+10\times n_{10} \dots$ Why would you need Lebesgue integral if we already have Riemann? The reason is that the latter doesn't work on functions that are not flat at small scales. Consider any ordinary function you know of, e.g. $\exp$ or $\sin$: if you look at the small enough interval $\delta x$ the function will be flat between $x$ and $x+\delta x$. Some functions don't flatten when you take a magnifying glass and zoom in. They stay rough at any scale, then Riemann integration fails, and you need something else. Here comes the Lebesgue integral to save the day (in some cases). Itô integration Suppose you need to sum a value of fruit basket. Easy: $V=n\times p $, where $n,p$ - quantity and price of a fruit. If both $n$ and $p$ are stochastic, then you must apply Itô calculus because $dV\ne \frac{\partial V}{\partial n}dn+ \frac{\partial V}{\partial p}dp$. Here's an [almost] plain English explanation. If we're control the amount of fruit ourselves, then $n$ is deterministic, i.e. we know in advance how much fruit we hold at any time $t$ in future. However, we're likely do not know the prices, they are stochastic. The good thing is that we may know the parameters of the stochastic process, e.g. $p(t)-p(0)\equiv \Delta p(t)\sim\mathcal N(0,t)$. Now, to forecast $p$ we simply need to integrate it: $p(t)=p(0)+\xi_t$, where $\xi_t\sim\mathcal N(0,t)$ Now the value of the basket is simply: $V(t)=n\times p(t)$ or in Itô integral formulation: $dV(t)=n\times dp(t)$ So far so good, and it doesn't seem like this Itô integral is any different from Riemann. Here's where it gets interesting: what if we're valuing someone else's fruit basket, where we don't know how much fruit is held at any time $t$ $n(t)=?$. It is a stochastic process though, and we may know its parameters, e.g. $dn(t)\sim\mathcal N(0,t)$ Can we get a process for the value of the basket $V(t)$? Because if we did, then we could integrate again: $V(t)=V(0)+\int_0^tdV(t)$ Riemann would say that it's easy: $dV=\left(dn\times p+n\times dp\right)$ - it's a usual full differential, and it's WRONG. That's where the Itô integral comes up: $dV=\left(dn\times p+n\times dp+dn\times dp\right)$. WTH did the last term $dn\times dp$ come from?! Consider the value of a basket at time 0 and time $t$:$$V(0)=n(0)\times p(0)\\V(t)= n(t)\times p(t)$$ Look at the difference: $$\Delta V(t)\equiv V(t)-V(0)= n(0)\times [p(t)-p(0)]+[n(t)-n(0)]\times p(0)+[n(t)-n(0)]\times[p(t)-p(0)] = \Delta n\times p(0)+n(0)\times\Delta p+\Delta n\times\Delta p$$ This corresponds to the Itô calculus $dV$ above. How are these related? If you have a function $V(t)$ where $t$ is a deterministic variable such as time, then usual calculus and Riemann integration works: $dV(t)=\frac{\partial V}{\partial t}dt$ If your function has stochastic variables $V(t,p)$ such as price of financial assets $p$, then Itô calculus and Lebesgue integration is in order: $dV(t)\ne\frac{\partial V}{\partial t}dt+\frac{\partial V}{\partial p}dp(t)$ The example with a fruit basket was a very simple function $V(n,p)=n\times p$, where we can get to the answer without Itô calculus formalism, but if you apply Itô calculus you get the same answer.
Plain English explanation of Ito's integral? I think you're confusing the Lebesgue integral with Itô calculus. They are related concepts. I'll explain. Lebesgue vs Riemann The simplest explanation of the difference between Lebesgue and Riemann i
25,736
Would the real adjusted R-squared formula please step forward?
Standard implementation in R One potential confusion comes from the role of the intercept in the correction factor used by lm. If present, it shows up in both the numerator and the denominator of the correction factor. Quoting from an answer in the linked question: Extracting the most relevant line you get: ans$adj.r.squared <- 1 - (1 - ans$r.squared) * ((n - df.int)/rdf) which corresponds in mathematical notation to: $$R^2_{adj} = 1 - (1 - R^2) \frac{n-1}{n-p-1}$$ assuming that there is an intercept (i.e., df.int=1), $n$ is your sample size, and $p$ is your number of predictors. Thus, your error degrees of freedom (i.e., rdf) equals n-p-1. Note the "assuming that there is an intercept" phrase in the first quote above. The above description holds for a situation where the number of predictors p does not include the intercept. That can be checked in the code for the lm.fit() function. The residual degrees of freedom (called df.residual in the lm.fit code but rdf in the summary.lm code) are calculated as df.residual = n - z$rank where n is the number of observations and z$rank is the rank of the fitted model z, the number of linearly independent parameter estimates returned. If the model has sufficient n and there is an intercept, that rank is the number of predictors other than the intercept plus 1 for the intercept. Without an intercept, that rank it is just the number of predictors. So if p is interpreted as the number of predictors not including the intercept, the formula in the above quote holds if the model includes an intercept. If there is no intercept, then df.int = 0 in the code quoted above and the rdf in the denominator is simply n-p. Thus without an intercept you get instead: $$R^2_{adj} = 1 - (1 - R^2) \frac{n}{n-p}$$ So one could say that are two "real adjusted $R^2$ formulas" used in lm depending on whether the intercept is included in the model. Recognizing that the denominator in either case is df.residual = n - z$rank, where z$rank is the rank of your model, should help reduce any confusion. Where the correction factors come from The Wikipedia page provides an explanation for where the $n-p-1$ in the denominator and the $n-1$ in the numerator come from, when the model includes an intercept: The principle behind the adjusted ''R''2 statistic can be seen by rewriting the ordinary ''R''2 as $$R^2 = {1-{\textit{VAR}_\text{res} \over \textit{VAR}_\text{tot}}}$$ where $\text{VAR}_\text{res} = SS_\text{res}/n$ and $\text{VAR}_\text{tot} = SS_\text{tot}/n$ are the sample variances of the estimated residuals and the dependent variable respectively, which can be seen as biased estimates of the population variances of the errors and of the dependent variable. These estimates are replaced by statistically unbiased versions: $\text{VAR}_\text{res} = SS_\text{res}/(n-p-1)$ and $\text{VAR}_\text{tot} = SS_\text{tot}/(n-1)$. The extension to the above formula for a no-intercept model seems direct. Other adjustments Although the above standard $R_{adj}^2$ effectively incorporates unbiased estimates of total and residual variance, it is not itself unbiased. In particular, that $R_{adj}^2$ estimate can take on negative values even though the underlying population multiple squared correlation coefficient (between observed and linearly-predicted values) is necessarily non-negative. That point is raised in the OP and in the answer from @Carl. But as Olkin and Pratt (1958) put it in their work on the unique uniformly minimum variance unbiased estimator of $\rho^2$ (page 211): We cannot hope for a non-negative unbiased estimator, since there is no region in the sample space having zero probability for $\rho^2=0$ and positive probability for $\rho^2 > 0$. There is an extensive literature on attempts to obtain improved adjusted estimates. Karch (2020) recently compared 20 different versions of adjusted $R^2$, and provided an exact implementation of the Olkin-Pratt estimator. The comparison included both the original estimators and the corresponding "positive-part shrinkage estimators" proposed by Shieh (2008), which keep non-negative values as is and set negative values to 0. The Olkin-Pratt estimator was the clear choice for an unbiased minimum mean-square error (MSE), but unbiased estimators could improve on MSE. Karch notes (page 7): No estimator had uniformly lowest MSE across all conditions. Even stronger, no estimator was uniformly best according to the maximum or average MSE perspectives. However, across all conditions, the positive-part version of the most widely used Ezekiel (adjusted $R^2$) estimator performed best both according to the maximum MSE as well as average MSE perspective. What Karch calls the Ezekiel estimator is the formula used in the standard R implementation described above, called McNemar's formula in the OP. "The real adjusted $R^2$ formula" There is no single "real" formula that will work the best in all situations, as Karch demonstrates. The choice is based on what tradeoffs one wishes to make with respect to bias and MSE, and how you wish to deal with the possibility of negative sample estimates. Nevertheless, Karch has also shown that the standard adjusted $R^2$ formula works remarkably well in practical situations with reasonable ratios of observations to predictors and non-negative population values of $\rho^2$ as low as 0.01. For more extreme situations, with even lower population $\rho^2$ values or barely more observations than predictors, the proposal in the answer from @Carl (inverse Fisher transformation of an adjusted Fisher z-transformed correlation coefficient) might have some advantages.
Would the real adjusted R-squared formula please step forward?
Standard implementation in R One potential confusion comes from the role of the intercept in the correction factor used by lm. If present, it shows up in both the numerator and the denominator of the
Would the real adjusted R-squared formula please step forward? Standard implementation in R One potential confusion comes from the role of the intercept in the correction factor used by lm. If present, it shows up in both the numerator and the denominator of the correction factor. Quoting from an answer in the linked question: Extracting the most relevant line you get: ans$adj.r.squared <- 1 - (1 - ans$r.squared) * ((n - df.int)/rdf) which corresponds in mathematical notation to: $$R^2_{adj} = 1 - (1 - R^2) \frac{n-1}{n-p-1}$$ assuming that there is an intercept (i.e., df.int=1), $n$ is your sample size, and $p$ is your number of predictors. Thus, your error degrees of freedom (i.e., rdf) equals n-p-1. Note the "assuming that there is an intercept" phrase in the first quote above. The above description holds for a situation where the number of predictors p does not include the intercept. That can be checked in the code for the lm.fit() function. The residual degrees of freedom (called df.residual in the lm.fit code but rdf in the summary.lm code) are calculated as df.residual = n - z$rank where n is the number of observations and z$rank is the rank of the fitted model z, the number of linearly independent parameter estimates returned. If the model has sufficient n and there is an intercept, that rank is the number of predictors other than the intercept plus 1 for the intercept. Without an intercept, that rank it is just the number of predictors. So if p is interpreted as the number of predictors not including the intercept, the formula in the above quote holds if the model includes an intercept. If there is no intercept, then df.int = 0 in the code quoted above and the rdf in the denominator is simply n-p. Thus without an intercept you get instead: $$R^2_{adj} = 1 - (1 - R^2) \frac{n}{n-p}$$ So one could say that are two "real adjusted $R^2$ formulas" used in lm depending on whether the intercept is included in the model. Recognizing that the denominator in either case is df.residual = n - z$rank, where z$rank is the rank of your model, should help reduce any confusion. Where the correction factors come from The Wikipedia page provides an explanation for where the $n-p-1$ in the denominator and the $n-1$ in the numerator come from, when the model includes an intercept: The principle behind the adjusted ''R''2 statistic can be seen by rewriting the ordinary ''R''2 as $$R^2 = {1-{\textit{VAR}_\text{res} \over \textit{VAR}_\text{tot}}}$$ where $\text{VAR}_\text{res} = SS_\text{res}/n$ and $\text{VAR}_\text{tot} = SS_\text{tot}/n$ are the sample variances of the estimated residuals and the dependent variable respectively, which can be seen as biased estimates of the population variances of the errors and of the dependent variable. These estimates are replaced by statistically unbiased versions: $\text{VAR}_\text{res} = SS_\text{res}/(n-p-1)$ and $\text{VAR}_\text{tot} = SS_\text{tot}/(n-1)$. The extension to the above formula for a no-intercept model seems direct. Other adjustments Although the above standard $R_{adj}^2$ effectively incorporates unbiased estimates of total and residual variance, it is not itself unbiased. In particular, that $R_{adj}^2$ estimate can take on negative values even though the underlying population multiple squared correlation coefficient (between observed and linearly-predicted values) is necessarily non-negative. That point is raised in the OP and in the answer from @Carl. But as Olkin and Pratt (1958) put it in their work on the unique uniformly minimum variance unbiased estimator of $\rho^2$ (page 211): We cannot hope for a non-negative unbiased estimator, since there is no region in the sample space having zero probability for $\rho^2=0$ and positive probability for $\rho^2 > 0$. There is an extensive literature on attempts to obtain improved adjusted estimates. Karch (2020) recently compared 20 different versions of adjusted $R^2$, and provided an exact implementation of the Olkin-Pratt estimator. The comparison included both the original estimators and the corresponding "positive-part shrinkage estimators" proposed by Shieh (2008), which keep non-negative values as is and set negative values to 0. The Olkin-Pratt estimator was the clear choice for an unbiased minimum mean-square error (MSE), but unbiased estimators could improve on MSE. Karch notes (page 7): No estimator had uniformly lowest MSE across all conditions. Even stronger, no estimator was uniformly best according to the maximum or average MSE perspectives. However, across all conditions, the positive-part version of the most widely used Ezekiel (adjusted $R^2$) estimator performed best both according to the maximum MSE as well as average MSE perspective. What Karch calls the Ezekiel estimator is the formula used in the standard R implementation described above, called McNemar's formula in the OP. "The real adjusted $R^2$ formula" There is no single "real" formula that will work the best in all situations, as Karch demonstrates. The choice is based on what tradeoffs one wishes to make with respect to bias and MSE, and how you wish to deal with the possibility of negative sample estimates. Nevertheless, Karch has also shown that the standard adjusted $R^2$ formula works remarkably well in practical situations with reasonable ratios of observations to predictors and non-negative population values of $\rho^2$ as low as 0.01. For more extreme situations, with even lower population $\rho^2$ values or barely more observations than predictors, the proposal in the answer from @Carl (inverse Fisher transformation of an adjusted Fisher z-transformed correlation coefficient) might have some advantages.
Would the real adjusted R-squared formula please step forward? Standard implementation in R One potential confusion comes from the role of the intercept in the correction factor used by lm. If present, it shows up in both the numerator and the denominator of the
25,737
Would the real adjusted R-squared formula please step forward?
A partial answer follows, contributions are welcome, and the question remains open. Some of the questions that posed substantial roadblocks toward an understanding of what $R_{adj}^2$ is, are dealt with here in order to address the question "Would the real adjusted R-squared formula please step forward." What it is not is a proof of anything, it is merely an attempt to find what a solution to the adjustment problem is, and is not. @EdM refers to this answer, which refers to Karch J (2019), which refers to the adjusted R-squared methods of Olkin and Pratt (1958), and in which it states that the method of Olkin and Pratt has not been implemented in any software because no one likes hypergeometric $\,_2F_1$ functions. Olkin and Pratt, as their last published function write that $$R_{adj}^{2}=1-\frac{n-2 }{n-v}\left(1-R^2\right) \, _2F_1\left(1,1,\frac{1}{2} (n-v+2);1-R^2\right)\;,$$ but write, as identified by Karch, $\,_2F_1(\alpha,\beta,\gamma;x)$, as $F(\alpha,\beta;\gamma;x)$. Fortunately, Olkin and Pratt list the appropriate infinite sum definition for an $\,_2F_1$ function, $\sum _{k=0}^{\infty } \frac{x^k (\alpha )_k (\beta )_k}{k! (\gamma )_k}$. About this formula they write, "We cannot hope for a non-negative unbiased estimator, since there is no region in the sample space having zero probability for $\rho^2 = 0$ and positive probability for $\rho^2 > 0$. For the same reason there can be no positive unbiased estimator of $\rho$ either." What the Olkin and Pratt (O-P) solution does is find a minimum error estimator of $R_{\text{adj}}^2$. This results in a family of curves that looks quite similar to the real and imaginary plot to follow, below. However, the case in which $v=1$ has a region wherein the O-P correction factor is above the line of identity, which indeed agrees with O-P's caution to only use their formula for $v\geq2$. The current most commonly used formula appears in the answer given by @EdM below as $$R^2_{adj} = 1 - (1 - R^2) \frac{n}{n-v}\;,$$ that is, if we count constant parameters as parameters (and not doing so would be indefensible). However, it has problems. Suppose we examine what that formula means by taking its limits. First pro forma let us take the limit as $R\to 1$, that yields 1, and thus there is no correction, and that makes sense. However, let us now take the limit as $R\to 0$, $$\underset{R\to 0}{\text{lim}}\left[R^2_{adj} =1-\frac{n \left(1-R^2\right)}{n-v}\right]\to R^2_{adj}=-\frac{v}{n-v}$$ That result is a negative number as $n>v$, and there are several problems with that. (1) It means that a relationship to the square of Pearson correlation coefficient does not exist (see below), as the square of that coefficient is bounded on $(0,1)$, and the adjustment formula is bounded on $(-\frac{v}{n-v},1)$, which has no clear meaning. (2) More generally, $R^2$ and the Pearson correlation coefficient squared should ideally have similar properties and indeed in the case of monovariate ordinary least squares linear regression (in x or y) R-squared is identical to r-squared, the square of Pearson correlation coefficient. This is not true if we assign a slope or intercept that is not the same as that implied by the Pearson correlation coefficient, or during bivariate regression. (3) There have been attempts to justify the negative valued answers for both $R_{adj}^2$ and $R^2$ which can arise from its ANOVA definition, for example as in the following image of linear regression with intercept set at zero using Excel, And we might reasonably ask how the $R^2$-value can be $-1.165$, and what that means. It could be argued that we are just subtracting a positive square, however, that is incorrect. Recalling the limit as $R\to 0$ above, $R^2_{adj}=-\frac{v}{n-v}$, it is clearly the square itself that is negative. The rules of mathematics thus allow one to take its square root which yields, $$R_{adj}(R=0)=\pm\sqrt{\frac{v}{n-v}}\,i\;,$$ where $i=\sqrt{-1}$, an imaginary number. Let us plot the $R$-values, i.e., the square root of $R_{adj}^2$ from the formula above, which is then $$R_{adj}=\pm\sqrt{1-\frac{n \left(1-R^2\right)}{n-v}}$$ to see just how bad it is as a family of curves for the positive root for $n=10$, and $v=1\text{ to }9$, as we cannot set $v=10$. The good news is that if $v=0$ the formula at least will return the identity. Plotting $R^2$ rather than $R$-values would change nothing, negative $R^2$-values are not real, that is, one cannot square a real number and obtain a negative value. As we can see from the plot, imaginary number answers (Im) as dashed blue lines for $R_{adj}$ occur at smaller R-values when the degrees of freedom $(v)$ are fewest, and become progressively more problematic as their number increases. The real number answers (Re) are in solid blue lines. Trusting this type of adjustment appears to be questionable unless the $R_{adj}$-values are close to 1. (4) It may be that what is being done during ANOVA is to ignore an "interaction term," a cross product, or "other" term in the ANOVA formula for $R^2$, For example, see this post Nonlinear regression SSE Loss. Thus, we are stuck trying to squeeze blood from a turnip to make any real world sense of this. Can anything be done to breath life into this? Remember the $\pm$ sign when we took the square root? One could redefine adjusted R-values piecewise to be $$\left\{ \begin{array}{@{}ll@{}} \sqrt{1-\frac{n \left(1-R^2\right)}{n-v}}, & 1-\frac{n \left(1-R^2\right)}{n-v}>0 \\ -\sqrt{\frac{n \left(1-R^2\right)}{n-v}-1}, & 1-\frac{n \left(1-R^2\right)}{n-v}\leq 0 \\ \end{array}\right. $$ This is not quite the same as adjusted R-values, because we would also have to redefine what it means to square this formula piecewise, but it would at least convert complex values to reals. In effect, this redefines when adjusted R-values are positive and when they are negative and is the result of sneaking in an absolute value to clear the complex numbers. It looks like this: and now has the properties we might desire, except that the negative values are still inexplicable for R on $(0,1)$. It turns out there is a way to define adjusted R-value, or at least a good start on one, although we do not follow through entirely on all its implications here, as one can only do so much at one sitting. That is, we can redefine $R_{adj}^2$ so as to remove the bias of correlation, which some authorities claim is not possible. That is, we can replace the sample means of $x$ and $y$ with their unbiased, population mean-values as follows; Adjusted r-squared is defined as the square of the population mean corrected Pearson correlation coefficient (r). That is, $$r_{adj}^2=\left[\frac{\sum _{i=1}^n (x_i-w) (y_i-z)}{\sqrt{\sum _{i=1}^n (x_i-w)^2} \sqrt{\sum _{i=1}^n (y_i-z)^2}}\right]^2,$$ where $w$ and $z$ are the population mean values for $x$ and $y$ respectively. If we are not given the population mean values, we cannot produce a unique value for adjusted R-squared in a particular case, but we could produce a unique estimator under certain additional assumptions, for example, from simulation studies (see below), or if the population mean values are known. Using this new definition, in no case will adjusted R-squared be negative, and this is a distinguishing feature of this re-definition. For the example of three co-ordinate pairs (1,10}, {5,2} and {3,-5}, a population mean adjusted R-squared surface has the following appearance. (Note, this shows what the adjustment is for $w$ and $z$ but does not display how likely $(w,z)$ is as a bivariate model, see a bivariate Student's t-model as an example.) The orange surface is population adjusted R-squared. The translucent blue flat surface is the ordinary Pearson correlation coefficient squared. Note that using a current formula the software I used listed the $𝑅^2$ value as $0.28$ and the adjusted $𝑅^2$ as $−0.43$, where the former is correctly the square of the Pearson correlation coefficient, and the latter the square of an imaginary number. Note that in a single individual case with only three realizations, that population mean adjusted r-squared will be larger than r-squared when the population mean values are far enough distant from the sample mean values (limited by 1 above), but that this is increasingly improbable when either the number of realizations, $(n)$, or for the mean of sample mean-values as the number of repetitions of a simulation increases for a fixed $n$ and given population mean-values. This may seem strange at first glance, but it has to be that way. It is well known that an outlier causes correlation magnitude to increase, and when an entire cloud of data are far from the population means in $x$ and $y$, those population means, which are known to be correct by assumption, then becomes an outlier with respect to the data cloud causing the adjusted R-squared value to increase. Such a situation becomes increasingly improbable when more data is collected. The formulas in current usage give no indication of such behaviour due to their one dimensionality. The problem type, however, only reduces to a one-dimensional one in the aggregate. We show this next in simulation studies. Doing simulations has the advantage of allowing us to assign population mean values a priori. Pearson correlation is: $$ r=\frac{\sum _{i=1}^n \left(x_i-\bar{x}\right) (y_i-\bar{y})}{\sqrt{\sum _{i=1}^n \left(x_i-\bar{x}\right)^2} \sqrt{\sum _{i=1}^n (y_i-\bar{y})^2}} $$ Notice that even if this arises from normal distributions that we do not know what the population means are, so we substituted the sample means $\bar{x}$ and $\bar{y}$. Wait one, that means that $r$ is biased and that is the bias we are trying to remove. To understand this (in case you do not) imagine you threw two darts at a dart board, in that case $(\bar{x},\bar{y})$ would be the midpoint of the line joining the two darts, that line is also the shortest distance between those points, and note that deviations are also distances. Thus, that is the absolute minimum root mean square value of all potential differences between the two dart positions and any population mean. To see that, throw a third dart and try to neatly split the positional difference between the first two darts. In fact, you would be lucky indeed to even hit a point within the minimum circle joining those first two darts. In effect, correlation using sample means typically (but not always, as above) overestimates correlation using population means, especially when the sample size is small, which is a good reason to ask how to adjust an R-value to reduce bias, and why the correction is a function of sample size. Now one way to address this problem might be to follow up with small number correction of standard deviation, see Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution?, and work that through for what a correlation is in terms of small number formulas (a collection of gamma functions). Finally the simulations. In this case, we simulate $y=2x$, where are generating data is from $x=0,1,2,\dots,n-1,n$ for $n=\{5,10,20,40,100\}$, and $v=\{1,2,3,4\}$. Then we inject noise into $y=2x$ in multiple ways using the independent standard normal distributions, $\mathcal{N}(0,1)$. Thus, we know that our population expected values are, for example, for $n=10$ with (when noiselessly progressing from 0 to 9) are $9/2$ for $x$, and $9$ for $y$. Such that, in that case, we would write an unbiased correlation as $$ r_{adj}=\frac{\sum _{i=1}^n \left(x_i-\frac{9}{2}\right) (y_i-9)}{\sqrt{\sum _{i=1}^n \left(x_i-\frac{9}{2}\right)^2} \sqrt{\sum _{i=1}^n (y_i-9)^2}} $$ That is, we modelled $r$ for a new $r_{adj}$ for up to 4 rv's in a linear equation and 2 rv's for $r$ itself using modelling for xy-data as follows, $\{x\text{-value}\to\text{ns}\,rv_1+x,y\text{-value}\to \text{ns}\, rv_2 +(\text{ns}\, rv_3+x) (\text{ns}\, rv_3+2)\}$, where all $rv$'s are independent standard normal random variates, ns is the "noise multiplier" and allowed to very from 1/15, to as much as needed to obtain r-values near zero (e.g., up to 13 to 1800), stepwise in a vaguely geometric progression, that defies easy description but was adjusted to make approximately similar spacing of mean r-values for up to about 30 r-values for each curve. To be clear, in case my notation is not self-evident, the random variables are either present in the noise equation above, or they are empty (0 would work as a marker for empty in this case, but actually the rv's were either used or not). So the $x$ value in the simulations sometimes were $x$ plus scaled (SND) noise, and sometimes not. Similarly, random variables were sometimes added to the intercept (of "0") the slope of 2, the x-value used for $y=f(x)$ (which is not the same as adding noise to the $x$-value independent variable, and conceptualizing that may seem paradoxical until one realizes that a injecting noise into $y=f(x)$ as $x$ plus noise, injects noise into $y$, not into $x$ itself, if we do not redefine what the $x$-values are explicitly and independently). Note well that although two points determine a line, we have assumed that noise can be independently present in each parameter or measurement of $y=m\, x+b$, for a total of 4 rv's. Now the perfectionist would point out that because we calculating a correlation that we cannot assume that the noise added in is uncorrelated between, for example $x$ and $y$. Although that is true, if we have correlated random variables for noise, each rv does not add a whole degree of freedom, thus the simulations to follow are a simplification that is not unlike the simplification of just adding up numbers of rv's to use the current formulas. Of these simulations let us examine one to see what this means. This is a plot of r-values on the $x$-axis and $r-r_{adj}$ on the $y$-axis. The simulation dots in this case were made using $n=5$ and $v=2$ from 24 different noise multipliers each having 100000 trials and whose mean r-values ares shown as each blue dot. In the case shown, the blue line, which closely approximates the blue dots is from the formula $r-r_{adj}\approx A0\left(z^{A1}-z^{A2}\right),$ where $z$ is a continuous version of discrete average $r$-values. Now notice how well the blue curve fits the blue dots. That is because we did curve fitting of the blue dots to obtain that fit. Note that the error from the fit equation (blue) is small. This appears to contradict O-P's statement that "We cannot hope for a non-negative unbiased estimator...." Now a giant leap, the orange line is from estimating the parameters $A0,A1,A2$ from functions of $n$ and $v$, and that the error from the estimating equation (orange) is a maximum of about 10% of the magnitude of the $R-R_{adj}$. Explaining this procedure would take a while, because the fit function is actually scaled from an undocumented PDF that fits somewhat better than the beta distribution, and is algebraically of different form from the Kumaraswamy distribution. However, the simple fit parameter estimators were generated from regression of 24 simulation curves. This is heuristic, and more work is needed. Nevertheless, it is instructive that as an area under the curve (AUC) of r-value corrections from $R=0\text{ to }1$, the fit function, AUC*PDF, has a fairly high $r^2$ (0.9875, logarithmic fitting) to $\text{AUC}=\dfrac{0.12631}{n^{0.6351} (n-v)^{0.3582}}$, which strongly suggests that the correction $r-r_{adj}$ decreases for increasing $n$, and increases for increasing $v$. This is all over the simulation data, it is a real effect. The same implication arises from an examination of the current adjusted $R^2$ formulas, with the difference being that those current formulas are unrelated to density functions and do not span all r-values on $(0,1)$. More on this some other time, for now, the point is that one can estimate what $r-r_{adj}$ is from functions of $n$ and $v$ over the whole range of r-values at least on $r=(0,1)$, which is not what is being done now. So let us look at what is being done now to see how that stacks up. Although the curve close to $R=1$, seems to fit, the formula overall seems unrelated to the problem, becomes complex numbered for smaller R-values, and has error so huge when it isn't complex-valued that it defies easy description as an error function. What it shows is that we would be better off redefining $R_{adj}^2$ to be $\left\{\Re\left[\sqrt{1-\frac{n \left(1-R^2\right)}{n-v}}\right]\right\}^2$ than the current formula. There are umpteen other possible methods of creating r-value adjustments that do not have the problems listed above. The points here are that at the moment R-value formulas leave something to be desired. In sum, adjusted R-value needs work, the current formulas are range limited and have limited applicability. A very large thank you to @whuber and @EdM for providing conceptual context for the work above. References Karch J (2019) Improving on adjusted R-squared. PsyArXiv, 16. Sept. 2019. (link) Olkin, Ingram; Pratt, John W (1958) Unbiased Estimation of Certain Correlation Coefficients. Ann. Math. Statist. 29, 1, 201--211. doi:10.1214/aoms/1177706717. (link)
Would the real adjusted R-squared formula please step forward?
A partial answer follows, contributions are welcome, and the question remains open. Some of the questions that posed substantial roadblocks toward an understanding of what $R_{adj}^2$ is, are dealt wi
Would the real adjusted R-squared formula please step forward? A partial answer follows, contributions are welcome, and the question remains open. Some of the questions that posed substantial roadblocks toward an understanding of what $R_{adj}^2$ is, are dealt with here in order to address the question "Would the real adjusted R-squared formula please step forward." What it is not is a proof of anything, it is merely an attempt to find what a solution to the adjustment problem is, and is not. @EdM refers to this answer, which refers to Karch J (2019), which refers to the adjusted R-squared methods of Olkin and Pratt (1958), and in which it states that the method of Olkin and Pratt has not been implemented in any software because no one likes hypergeometric $\,_2F_1$ functions. Olkin and Pratt, as their last published function write that $$R_{adj}^{2}=1-\frac{n-2 }{n-v}\left(1-R^2\right) \, _2F_1\left(1,1,\frac{1}{2} (n-v+2);1-R^2\right)\;,$$ but write, as identified by Karch, $\,_2F_1(\alpha,\beta,\gamma;x)$, as $F(\alpha,\beta;\gamma;x)$. Fortunately, Olkin and Pratt list the appropriate infinite sum definition for an $\,_2F_1$ function, $\sum _{k=0}^{\infty } \frac{x^k (\alpha )_k (\beta )_k}{k! (\gamma )_k}$. About this formula they write, "We cannot hope for a non-negative unbiased estimator, since there is no region in the sample space having zero probability for $\rho^2 = 0$ and positive probability for $\rho^2 > 0$. For the same reason there can be no positive unbiased estimator of $\rho$ either." What the Olkin and Pratt (O-P) solution does is find a minimum error estimator of $R_{\text{adj}}^2$. This results in a family of curves that looks quite similar to the real and imaginary plot to follow, below. However, the case in which $v=1$ has a region wherein the O-P correction factor is above the line of identity, which indeed agrees with O-P's caution to only use their formula for $v\geq2$. The current most commonly used formula appears in the answer given by @EdM below as $$R^2_{adj} = 1 - (1 - R^2) \frac{n}{n-v}\;,$$ that is, if we count constant parameters as parameters (and not doing so would be indefensible). However, it has problems. Suppose we examine what that formula means by taking its limits. First pro forma let us take the limit as $R\to 1$, that yields 1, and thus there is no correction, and that makes sense. However, let us now take the limit as $R\to 0$, $$\underset{R\to 0}{\text{lim}}\left[R^2_{adj} =1-\frac{n \left(1-R^2\right)}{n-v}\right]\to R^2_{adj}=-\frac{v}{n-v}$$ That result is a negative number as $n>v$, and there are several problems with that. (1) It means that a relationship to the square of Pearson correlation coefficient does not exist (see below), as the square of that coefficient is bounded on $(0,1)$, and the adjustment formula is bounded on $(-\frac{v}{n-v},1)$, which has no clear meaning. (2) More generally, $R^2$ and the Pearson correlation coefficient squared should ideally have similar properties and indeed in the case of monovariate ordinary least squares linear regression (in x or y) R-squared is identical to r-squared, the square of Pearson correlation coefficient. This is not true if we assign a slope or intercept that is not the same as that implied by the Pearson correlation coefficient, or during bivariate regression. (3) There have been attempts to justify the negative valued answers for both $R_{adj}^2$ and $R^2$ which can arise from its ANOVA definition, for example as in the following image of linear regression with intercept set at zero using Excel, And we might reasonably ask how the $R^2$-value can be $-1.165$, and what that means. It could be argued that we are just subtracting a positive square, however, that is incorrect. Recalling the limit as $R\to 0$ above, $R^2_{adj}=-\frac{v}{n-v}$, it is clearly the square itself that is negative. The rules of mathematics thus allow one to take its square root which yields, $$R_{adj}(R=0)=\pm\sqrt{\frac{v}{n-v}}\,i\;,$$ where $i=\sqrt{-1}$, an imaginary number. Let us plot the $R$-values, i.e., the square root of $R_{adj}^2$ from the formula above, which is then $$R_{adj}=\pm\sqrt{1-\frac{n \left(1-R^2\right)}{n-v}}$$ to see just how bad it is as a family of curves for the positive root for $n=10$, and $v=1\text{ to }9$, as we cannot set $v=10$. The good news is that if $v=0$ the formula at least will return the identity. Plotting $R^2$ rather than $R$-values would change nothing, negative $R^2$-values are not real, that is, one cannot square a real number and obtain a negative value. As we can see from the plot, imaginary number answers (Im) as dashed blue lines for $R_{adj}$ occur at smaller R-values when the degrees of freedom $(v)$ are fewest, and become progressively more problematic as their number increases. The real number answers (Re) are in solid blue lines. Trusting this type of adjustment appears to be questionable unless the $R_{adj}$-values are close to 1. (4) It may be that what is being done during ANOVA is to ignore an "interaction term," a cross product, or "other" term in the ANOVA formula for $R^2$, For example, see this post Nonlinear regression SSE Loss. Thus, we are stuck trying to squeeze blood from a turnip to make any real world sense of this. Can anything be done to breath life into this? Remember the $\pm$ sign when we took the square root? One could redefine adjusted R-values piecewise to be $$\left\{ \begin{array}{@{}ll@{}} \sqrt{1-\frac{n \left(1-R^2\right)}{n-v}}, & 1-\frac{n \left(1-R^2\right)}{n-v}>0 \\ -\sqrt{\frac{n \left(1-R^2\right)}{n-v}-1}, & 1-\frac{n \left(1-R^2\right)}{n-v}\leq 0 \\ \end{array}\right. $$ This is not quite the same as adjusted R-values, because we would also have to redefine what it means to square this formula piecewise, but it would at least convert complex values to reals. In effect, this redefines when adjusted R-values are positive and when they are negative and is the result of sneaking in an absolute value to clear the complex numbers. It looks like this: and now has the properties we might desire, except that the negative values are still inexplicable for R on $(0,1)$. It turns out there is a way to define adjusted R-value, or at least a good start on one, although we do not follow through entirely on all its implications here, as one can only do so much at one sitting. That is, we can redefine $R_{adj}^2$ so as to remove the bias of correlation, which some authorities claim is not possible. That is, we can replace the sample means of $x$ and $y$ with their unbiased, population mean-values as follows; Adjusted r-squared is defined as the square of the population mean corrected Pearson correlation coefficient (r). That is, $$r_{adj}^2=\left[\frac{\sum _{i=1}^n (x_i-w) (y_i-z)}{\sqrt{\sum _{i=1}^n (x_i-w)^2} \sqrt{\sum _{i=1}^n (y_i-z)^2}}\right]^2,$$ where $w$ and $z$ are the population mean values for $x$ and $y$ respectively. If we are not given the population mean values, we cannot produce a unique value for adjusted R-squared in a particular case, but we could produce a unique estimator under certain additional assumptions, for example, from simulation studies (see below), or if the population mean values are known. Using this new definition, in no case will adjusted R-squared be negative, and this is a distinguishing feature of this re-definition. For the example of three co-ordinate pairs (1,10}, {5,2} and {3,-5}, a population mean adjusted R-squared surface has the following appearance. (Note, this shows what the adjustment is for $w$ and $z$ but does not display how likely $(w,z)$ is as a bivariate model, see a bivariate Student's t-model as an example.) The orange surface is population adjusted R-squared. The translucent blue flat surface is the ordinary Pearson correlation coefficient squared. Note that using a current formula the software I used listed the $𝑅^2$ value as $0.28$ and the adjusted $𝑅^2$ as $−0.43$, where the former is correctly the square of the Pearson correlation coefficient, and the latter the square of an imaginary number. Note that in a single individual case with only three realizations, that population mean adjusted r-squared will be larger than r-squared when the population mean values are far enough distant from the sample mean values (limited by 1 above), but that this is increasingly improbable when either the number of realizations, $(n)$, or for the mean of sample mean-values as the number of repetitions of a simulation increases for a fixed $n$ and given population mean-values. This may seem strange at first glance, but it has to be that way. It is well known that an outlier causes correlation magnitude to increase, and when an entire cloud of data are far from the population means in $x$ and $y$, those population means, which are known to be correct by assumption, then becomes an outlier with respect to the data cloud causing the adjusted R-squared value to increase. Such a situation becomes increasingly improbable when more data is collected. The formulas in current usage give no indication of such behaviour due to their one dimensionality. The problem type, however, only reduces to a one-dimensional one in the aggregate. We show this next in simulation studies. Doing simulations has the advantage of allowing us to assign population mean values a priori. Pearson correlation is: $$ r=\frac{\sum _{i=1}^n \left(x_i-\bar{x}\right) (y_i-\bar{y})}{\sqrt{\sum _{i=1}^n \left(x_i-\bar{x}\right)^2} \sqrt{\sum _{i=1}^n (y_i-\bar{y})^2}} $$ Notice that even if this arises from normal distributions that we do not know what the population means are, so we substituted the sample means $\bar{x}$ and $\bar{y}$. Wait one, that means that $r$ is biased and that is the bias we are trying to remove. To understand this (in case you do not) imagine you threw two darts at a dart board, in that case $(\bar{x},\bar{y})$ would be the midpoint of the line joining the two darts, that line is also the shortest distance between those points, and note that deviations are also distances. Thus, that is the absolute minimum root mean square value of all potential differences between the two dart positions and any population mean. To see that, throw a third dart and try to neatly split the positional difference between the first two darts. In fact, you would be lucky indeed to even hit a point within the minimum circle joining those first two darts. In effect, correlation using sample means typically (but not always, as above) overestimates correlation using population means, especially when the sample size is small, which is a good reason to ask how to adjust an R-value to reduce bias, and why the correction is a function of sample size. Now one way to address this problem might be to follow up with small number correction of standard deviation, see Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution?, and work that through for what a correlation is in terms of small number formulas (a collection of gamma functions). Finally the simulations. In this case, we simulate $y=2x$, where are generating data is from $x=0,1,2,\dots,n-1,n$ for $n=\{5,10,20,40,100\}$, and $v=\{1,2,3,4\}$. Then we inject noise into $y=2x$ in multiple ways using the independent standard normal distributions, $\mathcal{N}(0,1)$. Thus, we know that our population expected values are, for example, for $n=10$ with (when noiselessly progressing from 0 to 9) are $9/2$ for $x$, and $9$ for $y$. Such that, in that case, we would write an unbiased correlation as $$ r_{adj}=\frac{\sum _{i=1}^n \left(x_i-\frac{9}{2}\right) (y_i-9)}{\sqrt{\sum _{i=1}^n \left(x_i-\frac{9}{2}\right)^2} \sqrt{\sum _{i=1}^n (y_i-9)^2}} $$ That is, we modelled $r$ for a new $r_{adj}$ for up to 4 rv's in a linear equation and 2 rv's for $r$ itself using modelling for xy-data as follows, $\{x\text{-value}\to\text{ns}\,rv_1+x,y\text{-value}\to \text{ns}\, rv_2 +(\text{ns}\, rv_3+x) (\text{ns}\, rv_3+2)\}$, where all $rv$'s are independent standard normal random variates, ns is the "noise multiplier" and allowed to very from 1/15, to as much as needed to obtain r-values near zero (e.g., up to 13 to 1800), stepwise in a vaguely geometric progression, that defies easy description but was adjusted to make approximately similar spacing of mean r-values for up to about 30 r-values for each curve. To be clear, in case my notation is not self-evident, the random variables are either present in the noise equation above, or they are empty (0 would work as a marker for empty in this case, but actually the rv's were either used or not). So the $x$ value in the simulations sometimes were $x$ plus scaled (SND) noise, and sometimes not. Similarly, random variables were sometimes added to the intercept (of "0") the slope of 2, the x-value used for $y=f(x)$ (which is not the same as adding noise to the $x$-value independent variable, and conceptualizing that may seem paradoxical until one realizes that a injecting noise into $y=f(x)$ as $x$ plus noise, injects noise into $y$, not into $x$ itself, if we do not redefine what the $x$-values are explicitly and independently). Note well that although two points determine a line, we have assumed that noise can be independently present in each parameter or measurement of $y=m\, x+b$, for a total of 4 rv's. Now the perfectionist would point out that because we calculating a correlation that we cannot assume that the noise added in is uncorrelated between, for example $x$ and $y$. Although that is true, if we have correlated random variables for noise, each rv does not add a whole degree of freedom, thus the simulations to follow are a simplification that is not unlike the simplification of just adding up numbers of rv's to use the current formulas. Of these simulations let us examine one to see what this means. This is a plot of r-values on the $x$-axis and $r-r_{adj}$ on the $y$-axis. The simulation dots in this case were made using $n=5$ and $v=2$ from 24 different noise multipliers each having 100000 trials and whose mean r-values ares shown as each blue dot. In the case shown, the blue line, which closely approximates the blue dots is from the formula $r-r_{adj}\approx A0\left(z^{A1}-z^{A2}\right),$ where $z$ is a continuous version of discrete average $r$-values. Now notice how well the blue curve fits the blue dots. That is because we did curve fitting of the blue dots to obtain that fit. Note that the error from the fit equation (blue) is small. This appears to contradict O-P's statement that "We cannot hope for a non-negative unbiased estimator...." Now a giant leap, the orange line is from estimating the parameters $A0,A1,A2$ from functions of $n$ and $v$, and that the error from the estimating equation (orange) is a maximum of about 10% of the magnitude of the $R-R_{adj}$. Explaining this procedure would take a while, because the fit function is actually scaled from an undocumented PDF that fits somewhat better than the beta distribution, and is algebraically of different form from the Kumaraswamy distribution. However, the simple fit parameter estimators were generated from regression of 24 simulation curves. This is heuristic, and more work is needed. Nevertheless, it is instructive that as an area under the curve (AUC) of r-value corrections from $R=0\text{ to }1$, the fit function, AUC*PDF, has a fairly high $r^2$ (0.9875, logarithmic fitting) to $\text{AUC}=\dfrac{0.12631}{n^{0.6351} (n-v)^{0.3582}}$, which strongly suggests that the correction $r-r_{adj}$ decreases for increasing $n$, and increases for increasing $v$. This is all over the simulation data, it is a real effect. The same implication arises from an examination of the current adjusted $R^2$ formulas, with the difference being that those current formulas are unrelated to density functions and do not span all r-values on $(0,1)$. More on this some other time, for now, the point is that one can estimate what $r-r_{adj}$ is from functions of $n$ and $v$ over the whole range of r-values at least on $r=(0,1)$, which is not what is being done now. So let us look at what is being done now to see how that stacks up. Although the curve close to $R=1$, seems to fit, the formula overall seems unrelated to the problem, becomes complex numbered for smaller R-values, and has error so huge when it isn't complex-valued that it defies easy description as an error function. What it shows is that we would be better off redefining $R_{adj}^2$ to be $\left\{\Re\left[\sqrt{1-\frac{n \left(1-R^2\right)}{n-v}}\right]\right\}^2$ than the current formula. There are umpteen other possible methods of creating r-value adjustments that do not have the problems listed above. The points here are that at the moment R-value formulas leave something to be desired. In sum, adjusted R-value needs work, the current formulas are range limited and have limited applicability. A very large thank you to @whuber and @EdM for providing conceptual context for the work above. References Karch J (2019) Improving on adjusted R-squared. PsyArXiv, 16. Sept. 2019. (link) Olkin, Ingram; Pratt, John W (1958) Unbiased Estimation of Certain Correlation Coefficients. Ann. Math. Statist. 29, 1, 201--211. doi:10.1214/aoms/1177706717. (link)
Would the real adjusted R-squared formula please step forward? A partial answer follows, contributions are welcome, and the question remains open. Some of the questions that posed substantial roadblocks toward an understanding of what $R_{adj}^2$ is, are dealt wi
25,738
Getting all answers correct by taking the same exam for fewest times
This is similar to the game Mastermind. There is a lot of literature on this topic. For that specific case (4 questions with each 6 options) several strategies have been devised that reduce the average number of takes to a bit above 4.3. You could pick out one of those strategies or make a new one and apply it to the case of $n$ questions with $2$ options, which is your situation. The question is too broad to provide a detailed answer here.
Getting all answers correct by taking the same exam for fewest times
This is similar to the game Mastermind. There is a lot of literature on this topic. For that specific case (4 questions with each 6 options) several strategies have been devised that reduce the averag
Getting all answers correct by taking the same exam for fewest times This is similar to the game Mastermind. There is a lot of literature on this topic. For that specific case (4 questions with each 6 options) several strategies have been devised that reduce the average number of takes to a bit above 4.3. You could pick out one of those strategies or make a new one and apply it to the case of $n$ questions with $2$ options, which is your situation. The question is too broad to provide a detailed answer here.
Getting all answers correct by taking the same exam for fewest times This is similar to the game Mastermind. There is a lot of literature on this topic. For that specific case (4 questions with each 6 options) several strategies have been devised that reduce the averag
25,739
Getting all answers correct by taking the same exam for fewest times
This is an optimisation problem where you seek to find an unknown $n$-digit binary number from guesses, where the feedback from those guesses is that you receive the number of correct digits. This is essentially just binary Mastermind, which is also examined in a computational problem called "black-box optimisation" (see e.g., Doerr et al 2001).
Getting all answers correct by taking the same exam for fewest times
This is an optimisation problem where you seek to find an unknown $n$-digit binary number from guesses, where the feedback from those guesses is that you receive the number of correct digits. This is
Getting all answers correct by taking the same exam for fewest times This is an optimisation problem where you seek to find an unknown $n$-digit binary number from guesses, where the feedback from those guesses is that you receive the number of correct digits. This is essentially just binary Mastermind, which is also examined in a computational problem called "black-box optimisation" (see e.g., Doerr et al 2001).
Getting all answers correct by taking the same exam for fewest times This is an optimisation problem where you seek to find an unknown $n$-digit binary number from guesses, where the feedback from those guesses is that you receive the number of correct digits. This is
25,740
Getting all answers correct by taking the same exam for fewest times
As others have said, the problem is very similar to the game Mastermind. Suppose that the correct answers are binary variables $c_i$ for $i = 1, \ldots, n$ and that Rain takes the test $k$ times, at time $j$ answering $x_{i, j}$ to the $i$-th question ($i \le n, j \le k$). The total correct answer to the $j$-th time is $T_j$. What follows are just some observation and notes, based on the OP explicit request to only provide some hints about the problem. Note that an easy "information-theoretic" lower bound on $k$ for a generic configuration of correct answers is $k \ge O(n / \log n)$: each test provides Rain with a number $0 \le T_j \le n$, which amounts to $\le \log n$ bits of knowledge, while the required knowledge to know all the answers is ~$n$ (because of the $n$ binary questions). In the general case you can define variables $z^Y_i$ and $z^N_i$ to be $0$ or $1$ respectively if the $i$-th correct answer is Yes or No. In such a way your problem is to determine the point of correct answers in a "discrete" linear space of dimension $2n$: to see why consider that by the above definition of variables you have the constraints $$ z^Y_i + z^N_i = 1 $$ Moreover, at your $j$-th take of the exam, you are testing a linear combination of such variables and you know that their sum is $T_j$: $$ \sum_{i = 1}^n z^{Y/N}_i = T_j$$ This highlights that it is trivial to solve such problem in $n$ queries because by taking the test $k$ times you have $n + k$ equations defining a point in a $2n$ dimensional space, so that if you are smart enough in not making redundant queries (just change your answers one at a time) you can take only $n$ times the quiz. In particular cases (such as when the yes/no ratio is particularly unbalanced) it should be easy to come up with particularly suited heuristics: suppose by example you know that there is only one Yes answer in the entire quiz. You can then find it in just $\log n$ queries by standard bisection on the answer sets. Moreover you can check if you are in such a case by issuing an "all-yes" first query (in which case $T_1 = 1$). By generalizing the idea in the previous bullet point, If the number of Yes answers is $C$ (suppose $C \le n/2$) (and this can become known by a single query), you are basically searching a set of size $C$ inside a set of size $n$ (thus there are $\binom{n}{C} \simeq n^C$ of them) and your query consists in knowing the cardinality of the intersection of one set $S$ of your choosing with said set of Yes questions, which I think is a much more studied problem and you can probably find many references on it. Call the set you are tring to find (Yes answers) $Y$. With a single query you can know its cardinality $|Y| = m$. Now a randomly selected set $S$ used as query allows you to know the cardinality of the two subsets $|Y \cap S| = t$ and $|Y \cap S^c| = m - t$, and your original problem has been reduced to two subproblems of roughly half the size (also the number of sought Yes answer will usually halve at each iteration). I won't write explicit details, but it is just a matter of simple probability calculations. Exploiting the above observation, you should came up with a probabilitic algorithm that solves the subproblem $P(m, n) \simeq\le 1 + 2 * P(m/2, n/2)$, which should get you a bound of $O(m \log n)$. Coming up with a deterministic algorithm for such problem may be done using the technique of maximized expectations, but I can't foresee if it would work or not.
Getting all answers correct by taking the same exam for fewest times
As others have said, the problem is very similar to the game Mastermind. Suppose that the correct answers are binary variables $c_i$ for $i = 1, \ldots, n$ and that Rain takes the test $k$ times, at t
Getting all answers correct by taking the same exam for fewest times As others have said, the problem is very similar to the game Mastermind. Suppose that the correct answers are binary variables $c_i$ for $i = 1, \ldots, n$ and that Rain takes the test $k$ times, at time $j$ answering $x_{i, j}$ to the $i$-th question ($i \le n, j \le k$). The total correct answer to the $j$-th time is $T_j$. What follows are just some observation and notes, based on the OP explicit request to only provide some hints about the problem. Note that an easy "information-theoretic" lower bound on $k$ for a generic configuration of correct answers is $k \ge O(n / \log n)$: each test provides Rain with a number $0 \le T_j \le n$, which amounts to $\le \log n$ bits of knowledge, while the required knowledge to know all the answers is ~$n$ (because of the $n$ binary questions). In the general case you can define variables $z^Y_i$ and $z^N_i$ to be $0$ or $1$ respectively if the $i$-th correct answer is Yes or No. In such a way your problem is to determine the point of correct answers in a "discrete" linear space of dimension $2n$: to see why consider that by the above definition of variables you have the constraints $$ z^Y_i + z^N_i = 1 $$ Moreover, at your $j$-th take of the exam, you are testing a linear combination of such variables and you know that their sum is $T_j$: $$ \sum_{i = 1}^n z^{Y/N}_i = T_j$$ This highlights that it is trivial to solve such problem in $n$ queries because by taking the test $k$ times you have $n + k$ equations defining a point in a $2n$ dimensional space, so that if you are smart enough in not making redundant queries (just change your answers one at a time) you can take only $n$ times the quiz. In particular cases (such as when the yes/no ratio is particularly unbalanced) it should be easy to come up with particularly suited heuristics: suppose by example you know that there is only one Yes answer in the entire quiz. You can then find it in just $\log n$ queries by standard bisection on the answer sets. Moreover you can check if you are in such a case by issuing an "all-yes" first query (in which case $T_1 = 1$). By generalizing the idea in the previous bullet point, If the number of Yes answers is $C$ (suppose $C \le n/2$) (and this can become known by a single query), you are basically searching a set of size $C$ inside a set of size $n$ (thus there are $\binom{n}{C} \simeq n^C$ of them) and your query consists in knowing the cardinality of the intersection of one set $S$ of your choosing with said set of Yes questions, which I think is a much more studied problem and you can probably find many references on it. Call the set you are tring to find (Yes answers) $Y$. With a single query you can know its cardinality $|Y| = m$. Now a randomly selected set $S$ used as query allows you to know the cardinality of the two subsets $|Y \cap S| = t$ and $|Y \cap S^c| = m - t$, and your original problem has been reduced to two subproblems of roughly half the size (also the number of sought Yes answer will usually halve at each iteration). I won't write explicit details, but it is just a matter of simple probability calculations. Exploiting the above observation, you should came up with a probabilitic algorithm that solves the subproblem $P(m, n) \simeq\le 1 + 2 * P(m/2, n/2)$, which should get you a bound of $O(m \log n)$. Coming up with a deterministic algorithm for such problem may be done using the technique of maximized expectations, but I can't foresee if it would work or not.
Getting all answers correct by taking the same exam for fewest times As others have said, the problem is very similar to the game Mastermind. Suppose that the correct answers are binary variables $c_i$ for $i = 1, \ldots, n$ and that Rain takes the test $k$ times, at t
25,741
Getting all answers correct by taking the same exam for fewest times
Do you want to minimize the maximum number of retakes? or minimize the expected number of retakes? You could come up with very different strategies depending on which you want to look at. A first step naive approach would take up to $n+1$ times and would consist of taking the test the first time, then on the second time taking the test change only the first answer, If the score goes up then keep the new answer, if it goes down go back to the first answer for all future steps. On the 3rd time (2nd retake) change only the 2nd answer, etc. Now you can start comparing other strategies to that one. If on the 2nd time taking the test 2 answers are changed, then if the score changes we know the correct answers for 2 questions and have saved a step, but if we changed one to be correct and the other to be wrong then the score does not change and we do not know which change was correct until we take the exam a 3rd time changing only one of them (but that will tell us about the other as well), so either 1 or 2 retakes to get 2 answers (50% chance of each) which will reduce the expected number of retakes, but probably keep the maximum the same. Now you can look at other strategies and see how they compare (change the 1st 3 answers, change the first $\frac{n}{2}$, etc.).
Getting all answers correct by taking the same exam for fewest times
Do you want to minimize the maximum number of retakes? or minimize the expected number of retakes? You could come up with very different strategies depending on which you want to look at. A first step
Getting all answers correct by taking the same exam for fewest times Do you want to minimize the maximum number of retakes? or minimize the expected number of retakes? You could come up with very different strategies depending on which you want to look at. A first step naive approach would take up to $n+1$ times and would consist of taking the test the first time, then on the second time taking the test change only the first answer, If the score goes up then keep the new answer, if it goes down go back to the first answer for all future steps. On the 3rd time (2nd retake) change only the 2nd answer, etc. Now you can start comparing other strategies to that one. If on the 2nd time taking the test 2 answers are changed, then if the score changes we know the correct answers for 2 questions and have saved a step, but if we changed one to be correct and the other to be wrong then the score does not change and we do not know which change was correct until we take the exam a 3rd time changing only one of them (but that will tell us about the other as well), so either 1 or 2 retakes to get 2 answers (50% chance of each) which will reduce the expected number of retakes, but probably keep the maximum the same. Now you can look at other strategies and see how they compare (change the 1st 3 answers, change the first $\frac{n}{2}$, etc.).
Getting all answers correct by taking the same exam for fewest times Do you want to minimize the maximum number of retakes? or minimize the expected number of retakes? You could come up with very different strategies depending on which you want to look at. A first step
25,742
Calculating the p-values in a constrained (non-negative) least squares
Solving a non-negative least squares (NNLS) is based on an algorithm which makes it different from regular least squares. Algebraic expression for standard error (does not work) With regular least squares you can express p-values by using a t-test in combination with estimates for the variance of the coefficients. This expression for the sample variance of the estimate of the coefficients $\hat\theta$ is $$Var(\hat\theta) = \sigma^2(X^TX)^{-1}$$ The variance of the errors $\sigma$ will generally be unknown but it can be estimated using the residuals. This expression can be derived algebraically starting from the expression for the coefficients in terms of the measurements $y$ $$\hat\theta = (X^TX)^{-1} X^T y$$ This implies/assumes that the $\theta$ can be negative, and so it breaks down when the coefficients are restricted. Inverse of Fisher information matrix (not applicable) The variance/distribution of the estimate of the coefficients also asymptotically approaches the observed Fisher information matrix: $$(\hat\theta-\theta) \xrightarrow{d} N(0,\mathcal{I}(\hat\theta))$$ But I am not sure whether this applies well here. The NNLS estimate is not an unbiased estimate. Monte Carlo Method Whenever the expressions become too complicated you can use a computational method to estimate the error. With the Monte Carlo Method you simulate the distribution of the randomness of the experiment by simulating repetitions of the experiment (recalculating/modelling new data) and based on this you estimate the variance of the coefficients. What you could do is take the observed estimates of the model coefficients $\hat\theta$ and residual variance $\hat\sigma$ and based on this compute new data (a couple of thousand repetitions, but it depends on how much precision you wish) from which you can observe the distribution (and variation and derived from this the estimate for the error) for the coefficients. (and there are more complicated schemes to perform this modelling)
Calculating the p-values in a constrained (non-negative) least squares
Solving a non-negative least squares (NNLS) is based on an algorithm which makes it different from regular least squares. Algebraic expression for standard error (does not work) With regular least squ
Calculating the p-values in a constrained (non-negative) least squares Solving a non-negative least squares (NNLS) is based on an algorithm which makes it different from regular least squares. Algebraic expression for standard error (does not work) With regular least squares you can express p-values by using a t-test in combination with estimates for the variance of the coefficients. This expression for the sample variance of the estimate of the coefficients $\hat\theta$ is $$Var(\hat\theta) = \sigma^2(X^TX)^{-1}$$ The variance of the errors $\sigma$ will generally be unknown but it can be estimated using the residuals. This expression can be derived algebraically starting from the expression for the coefficients in terms of the measurements $y$ $$\hat\theta = (X^TX)^{-1} X^T y$$ This implies/assumes that the $\theta$ can be negative, and so it breaks down when the coefficients are restricted. Inverse of Fisher information matrix (not applicable) The variance/distribution of the estimate of the coefficients also asymptotically approaches the observed Fisher information matrix: $$(\hat\theta-\theta) \xrightarrow{d} N(0,\mathcal{I}(\hat\theta))$$ But I am not sure whether this applies well here. The NNLS estimate is not an unbiased estimate. Monte Carlo Method Whenever the expressions become too complicated you can use a computational method to estimate the error. With the Monte Carlo Method you simulate the distribution of the randomness of the experiment by simulating repetitions of the experiment (recalculating/modelling new data) and based on this you estimate the variance of the coefficients. What you could do is take the observed estimates of the model coefficients $\hat\theta$ and residual variance $\hat\sigma$ and based on this compute new data (a couple of thousand repetitions, but it depends on how much precision you wish) from which you can observe the distribution (and variation and derived from this the estimate for the error) for the coefficients. (and there are more complicated schemes to perform this modelling)
Calculating the p-values in a constrained (non-negative) least squares Solving a non-negative least squares (NNLS) is based on an algorithm which makes it different from regular least squares. Algebraic expression for standard error (does not work) With regular least squ
25,743
Calculating the p-values in a constrained (non-negative) least squares
If you would be OK using R I think you could also use bbmle's mle2 function to optimize the least squares likelihood function and calculate 95% confidence intervals on the nonnegative nnls coefficients. Furthermore, you can take into account that your coefficients cannot go negative by optimizing the log of your coefficients, so that on a backtransformed scale they could never become negative. Here is a numerical example illustrating this approach, here in the context of deconvoluting a superposition of gaussian-shaped chromatographic peaks with Gaussian noise on them : (any comments welcome) First let's simulate some data : require(Matrix) n = 200 x = 1:n npeaks = 20 set.seed(123) u = sample(x, npeaks, replace=FALSE) # peak locations which later need to be estimated peakhrange = c(10,1E3) # peak height range h = 10^runif(npeaks, min=log10(min(peakhrange)), max=log10(max(peakhrange))) # simulated peak heights, to be estimated a = rep(0, n) # locations of spikes of simulated spike train, need to be estimated a[u] = h gauspeak = function(x, u, w, h=1) h*exp(((x-u)^2)/(-2*(w^2))) # shape of single peak, assumed to be known bM = do.call(cbind, lapply(1:n, function (u) gauspeak(x, u=u, w=5, h=1) )) # banded matrix with theoretical peak shape function used y_nonoise = as.vector(bM %*% a) # noiseless simulated signal = linear convolution of spike train with peak shape function y = y_nonoise + rnorm(n, mean=0, sd=100) # simulated signal with gaussian noise on it y = pmax(y,0) par(mfrow=c(1,1)) plot(y, type="l", ylab="Signal", xlab="x", main="Simulated spike train (red) to be estimated given known blur kernel & with Gaussian noise") lines(a, type="h", col="red") Let's now deconvolute the measured noisy signal y with a banded matrix containing shifted copied of the known gaussian shaped blur kernel bM (this is our covariate/design matrix). First, let's deconvolute the signal with nonnegative least squares : library(nnls) library(microbenchmark) microbenchmark(a_nnls <- nnls(A=bM,b=y)$x) # 5.5 ms plot(x, y, type="l", main="Ground truth (red), nnls estimate (blue)", ylab="Signal (black) & peaks (red & blue)", xlab="Time", ylim=c(-max(y),max(y))) lines(x,-y) lines(a, type="h", col="red", lwd=2) lines(-a_nnls, type="h", col="blue", lwd=2) yhat = as.vector(bM %*% a_nnls) # predicted values residuals = (y-yhat) nonzero = (a_nnls!=0) # nonzero coefficients n = nrow(bM) p = sum(nonzero)+1 # nr of estimated parameters = nr of nonzero coefficients+estimated variance variance = sum(residuals^2)/(n-p) # estimated variance = 8114.505 Now let's optimize the negative log-likelihood of our gaussian loss objective, and optimize the log of your coefficients so that on a backtransformed scale they can never be negative : library(bbmle) XM=as.matrix(bM)[,nonzero,drop=FALSE] # design matrix, keeping only covariates with nonnegative nnls coefs colnames(XM)=paste0("v",as.character(1:n))[nonzero] yv=as.vector(y) # response # negative log likelihood function for gaussian loss NEGLL_gaus_logbetas <- function(logbetas, X=XM, y=yv, sd=sqrt(variance)) { -sum(stats::dnorm(x = y, mean = X %*% exp(logbetas), sd = sd, log = TRUE)) } parnames(NEGLL_gaus_logbetas) <- colnames(XM) system.time(fit <- mle2( minuslogl = NEGLL_gaus_logbetas, start = setNames(log(a_nnls[nonzero]+1E-10), colnames(XM)), # we initialise with nnls estimates vecpar = TRUE, optimizer = "nlminb" )) # takes 0.86s AIC(fit) # 2394.857 summary(fit) # now gives log(coefficients) (note that p values are 2 sided) # Coefficients: # Estimate Std. Error z value Pr(z) # v10 4.57339 2.28665 2.0000 0.0454962 * # v11 5.30521 1.10127 4.8173 1.455e-06 *** # v27 3.36162 1.37185 2.4504 0.0142689 * # v38 3.08328 23.98324 0.1286 0.8977059 # v39 3.88101 12.01675 0.3230 0.7467206 # v48 5.63771 3.33932 1.6883 0.0913571 . # v49 4.07475 16.21209 0.2513 0.8015511 # v58 3.77749 19.78448 0.1909 0.8485789 # v59 6.28745 1.53541 4.0950 4.222e-05 *** # v70 1.23613 222.34992 0.0056 0.9955643 # v71 2.67320 54.28789 0.0492 0.9607271 # v80 5.54908 1.12656 4.9257 8.407e-07 *** # v86 5.96813 9.31872 0.6404 0.5218830 # v87 4.27829 84.86010 0.0504 0.9597911 # v88 4.83853 21.42043 0.2259 0.8212918 # v107 6.11318 0.64794 9.4348 < 2.2e-16 *** # v108 4.13673 4.85345 0.8523 0.3940316 # v117 3.27223 1.86578 1.7538 0.0794627 . # v129 4.48811 2.82435 1.5891 0.1120434 # v130 4.79551 2.04481 2.3452 0.0190165 * # v145 3.97314 0.60547 6.5620 5.308e-11 *** # v157 5.49003 0.13670 40.1608 < 2.2e-16 *** # v172 5.88622 1.65908 3.5479 0.0003884 *** # v173 6.49017 1.08156 6.0008 1.964e-09 *** # v181 6.79913 1.81802 3.7399 0.0001841 *** # v182 5.43450 7.66955 0.7086 0.4785848 # v188 1.51878 233.81977 0.0065 0.9948174 # v189 5.06634 5.20058 0.9742 0.3299632 # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # # -2 log L: 2338.857 exp(confint(fit, method="quad")) # backtransformed confidence intervals calculated via quadratic approximation (=Wald confidence intervals) # 2.5 % 97.5 % # v10 1.095964e+00 8.562480e+03 # v11 2.326040e+01 1.743531e+03 # v27 1.959787e+00 4.242829e+02 # v38 8.403942e-20 5.670507e+21 # v39 2.863032e-09 8.206810e+11 # v48 4.036402e-01 1.953696e+05 # v49 9.330044e-13 3.710221e+15 # v58 6.309090e-16 3.027742e+18 # v59 2.652533e+01 1.090313e+04 # v70 1.871739e-189 6.330566e+189 # v71 8.933534e-46 2.349031e+47 # v80 2.824905e+01 2.338118e+03 # v86 4.568985e-06 3.342200e+10 # v87 4.216892e-71 1.233336e+74 # v88 7.383119e-17 2.159994e+20 # v107 1.268806e+02 1.608602e+03 # v108 4.626990e-03 8.468795e+05 # v117 6.806996e-01 1.021572e+03 # v129 3.508065e-01 2.255556e+04 # v130 2.198449e+00 6.655952e+03 # v145 1.622306e+01 1.741383e+02 # v157 1.853224e+02 3.167003e+02 # v172 1.393601e+01 9.301732e+03 # v173 7.907170e+01 5.486191e+03 # v181 2.542890e+01 3.164652e+04 # v182 6.789470e-05 7.735850e+08 # v188 4.284006e-199 4.867958e+199 # v189 5.936664e-03 4.236704e+06 library(broom) signlevels = tidy(fit)$p.value/2 # 1-sided p values for peak to be sign higher than 1 adjsignlevels = p.adjust(signlevels, method="fdr") # FDR corrected p values a_nnlsbbmle = exp(coef(fit)) # exp to backtransform max(a_nnls[nonzero]-a_nnlsbbmle) # -9.981704e-11, coefficients as expected almost the same plot(x, y, type="l", main="Ground truth (red), nnls bbmle logcoeff estimate (blue & green, green=FDR p value<0.05)", ylab="Signal (black) & peaks (red & blue)", xlab="Time", ylim=c(-max(y),max(y))) lines(x,-y) lines(a, type="h", col="red", lwd=2) lines(x[nonzero], -a_nnlsbbmle, type="h", col="blue", lwd=2) lines(x[nonzero][(adjsignlevels<0.05)&(a_nnlsbbmle>1)], -a_nnlsbbmle[(adjsignlevels<0.05)&(a_nnlsbbmle>1)], type="h", col="green", lwd=2) sum((signlevels<0.05)&(a_nnlsbbmle>1)) # 14 peaks significantly higher than 1 before FDR correction sum((adjsignlevels<0.05)&(a_nnlsbbmle>1)) # 11 peaks significant after FDR correction I haven't tried to compare the performance of this method relative to either nonparametric or parametric bootstrapping, but it's surely much faster. I was also inclined to think that I should be able to calculate Wald confidence intervals for the nonnegative nnls coefficients based on the observed Fisher information matrix, calculated at a log transformed coefficient scale to enforce the nonnegativity constraints and evaluated at the nnls estimates. I think this goes like this, and in fact should be formally identical to what I did using mle2 above : XM=as.matrix(bM)[,nonzero,drop=FALSE] # design matrix posbetas = a_nnls[nonzero] # nonzero nnls coefficients dispersion=sum(residuals^2)/(n-p) # estimated dispersion (variance in case of gaussian noise) (1 if noise were poisson or binomial) information_matrix = t(XM) %*% XM # observed Fisher information matrix for nonzero coefs, ie negative of the 2nd derivative (Hessian) of the log likelihood at param estimates scaled_information_matrix = (t(XM) %*% XM)*(1/dispersion) # information matrix scaled by 1/dispersion # let's now calculate this scaled information matrix on a log transformed Y scale (cf. stat.psu.edu/~sesa/stat504/Lecture/lec2part2.pdf, slide 20 eqn 8 & Table 1) to take into account the nonnegativity constraints on the parameters scaled_information_matrix_logscale = scaled_information_matrix/((1/posbetas)^2) # scaled information_matrix on transformed log scale=scaled information matrix/(PHI'(betas)^2) if PHI(beta)=log(beta) vcov_logscale = solve(scaled_information_matrix_logscale) # scaled variance-covariance matrix of coefs on log scale ie of log(posbetas) # PS maybe figure out how to do this in better way using chol2inv & QR decomposition - in R unscaled covariance matrix is calculated as chol2inv(qr(XW_glm)$qr) SEs_logscale = sqrt(diag(vcov_logscale)) # SEs of coefs on log scale ie of log(posbetas) posbetas_LOWER95CL = exp(log(posbetas) - 1.96*SEs_logscale) posbetas_UPPER95CL = exp(log(posbetas) + 1.96*SEs_logscale) data.frame("2.5 %"=posbetas_LOWER95CL,"97.5 %"=posbetas_UPPER95CL,check.names=F) # 2.5 % 97.5 % # 1 1.095874e+00 8.563185e+03 # 2 2.325947e+01 1.743600e+03 # 3 1.959691e+00 4.243037e+02 # 4 8.397159e-20 5.675087e+21 # 5 2.861885e-09 8.210098e+11 # 6 4.036017e-01 1.953882e+05 # 7 9.325838e-13 3.711894e+15 # 8 6.306894e-16 3.028796e+18 # 9 2.652467e+01 1.090340e+04 # 10 1.870702e-189 6.334074e+189 # 11 8.932335e-46 2.349347e+47 # 12 2.824872e+01 2.338145e+03 # 13 4.568282e-06 3.342714e+10 # 14 4.210592e-71 1.235182e+74 # 15 7.380152e-17 2.160863e+20 # 16 1.268778e+02 1.608639e+03 # 17 4.626207e-03 8.470228e+05 # 18 6.806543e-01 1.021640e+03 # 19 3.507709e-01 2.255786e+04 # 20 2.198287e+00 6.656441e+03 # 21 1.622270e+01 1.741421e+02 # 22 1.853214e+02 3.167018e+02 # 23 1.393520e+01 9.302273e+03 # 24 7.906871e+01 5.486398e+03 # 25 2.542730e+01 3.164851e+04 # 26 6.787667e-05 7.737904e+08 # 27 4.249153e-199 4.907886e+199 # 28 5.935583e-03 4.237476e+06 z_logscale = log(posbetas)/SEs_logscale # z values for log(coefs) being greater than 0, ie coefs being > 1 (since log(1) = 0) pvals = pnorm(z_logscale, lower.tail=FALSE) # one-sided p values for log(coefs) being greater than 0, ie coefs being > 1 (since log(1) = 0) pvals.adj = p.adjust(pvals, method="fdr") # FDR corrected p values plot(x, y, type="l", main="Ground truth (red), nnls estimates (blue & green, green=FDR Wald p value<0.05)", ylab="Signal (black) & peaks (red & blue)", xlab="Time", ylim=c(-max(y),max(y))) lines(x,-y) lines(a, type="h", col="red", lwd=2) lines(-a_nnls, type="h", col="blue", lwd=2) lines(x[nonzero][pvals.adj<0.05], -a_nnls[nonzero][pvals.adj<0.05], type="h", col="green", lwd=2) sum((pvals<0.05)&(posbetas>1)) # 14 peaks significantly higher than 1 before FDR correction sum((pvals.adj<0.05)&(posbetas>1)) # 11 peaks significantly higher than 1 after FDR correction The results of these calculations and the ones returned by mle2 are nearly identical (but much faster), so I think this is right, and would correspond that what we were implicitly doing with mle2... Just refitting the covariates with positive coefficients in an nnls fit using a regular linear model fit btw does not work, since such a linear model fit would not take into account the nonnegativity constraints and so would result in nonsensical confidence intervals that could go negative. This paper "Exact post model selection inference for marginal screening" by Jason Lee & Jonathan Taylor also presents a method to do post-model selection inference on nonnegative nnls (or LASSO) coefficients and uses truncated Gaussian distributions for that. I haven't seen any openly available implementation of this method for nnls fits though - for LASSO fits there is the selectiveInference package that does something like that. If anyone would happen to have an implementation, please let me know! In the method above one could also split the data in a training & validation set (e.g. odd & even observations) and infer the covariates with positive coefficients from the training set & then calculate confidence intervals & p values from the validation set. That would be a bit more resistant against overfitting though it would also cause a loss in power since one would only use half of the data. I didn't do it here because the nonnegativity constraint in itself is already quite effective in guarding against overfitting.
Calculating the p-values in a constrained (non-negative) least squares
If you would be OK using R I think you could also use bbmle's mle2 function to optimize the least squares likelihood function and calculate 95% confidence intervals on the nonnegative nnls coefficient
Calculating the p-values in a constrained (non-negative) least squares If you would be OK using R I think you could also use bbmle's mle2 function to optimize the least squares likelihood function and calculate 95% confidence intervals on the nonnegative nnls coefficients. Furthermore, you can take into account that your coefficients cannot go negative by optimizing the log of your coefficients, so that on a backtransformed scale they could never become negative. Here is a numerical example illustrating this approach, here in the context of deconvoluting a superposition of gaussian-shaped chromatographic peaks with Gaussian noise on them : (any comments welcome) First let's simulate some data : require(Matrix) n = 200 x = 1:n npeaks = 20 set.seed(123) u = sample(x, npeaks, replace=FALSE) # peak locations which later need to be estimated peakhrange = c(10,1E3) # peak height range h = 10^runif(npeaks, min=log10(min(peakhrange)), max=log10(max(peakhrange))) # simulated peak heights, to be estimated a = rep(0, n) # locations of spikes of simulated spike train, need to be estimated a[u] = h gauspeak = function(x, u, w, h=1) h*exp(((x-u)^2)/(-2*(w^2))) # shape of single peak, assumed to be known bM = do.call(cbind, lapply(1:n, function (u) gauspeak(x, u=u, w=5, h=1) )) # banded matrix with theoretical peak shape function used y_nonoise = as.vector(bM %*% a) # noiseless simulated signal = linear convolution of spike train with peak shape function y = y_nonoise + rnorm(n, mean=0, sd=100) # simulated signal with gaussian noise on it y = pmax(y,0) par(mfrow=c(1,1)) plot(y, type="l", ylab="Signal", xlab="x", main="Simulated spike train (red) to be estimated given known blur kernel & with Gaussian noise") lines(a, type="h", col="red") Let's now deconvolute the measured noisy signal y with a banded matrix containing shifted copied of the known gaussian shaped blur kernel bM (this is our covariate/design matrix). First, let's deconvolute the signal with nonnegative least squares : library(nnls) library(microbenchmark) microbenchmark(a_nnls <- nnls(A=bM,b=y)$x) # 5.5 ms plot(x, y, type="l", main="Ground truth (red), nnls estimate (blue)", ylab="Signal (black) & peaks (red & blue)", xlab="Time", ylim=c(-max(y),max(y))) lines(x,-y) lines(a, type="h", col="red", lwd=2) lines(-a_nnls, type="h", col="blue", lwd=2) yhat = as.vector(bM %*% a_nnls) # predicted values residuals = (y-yhat) nonzero = (a_nnls!=0) # nonzero coefficients n = nrow(bM) p = sum(nonzero)+1 # nr of estimated parameters = nr of nonzero coefficients+estimated variance variance = sum(residuals^2)/(n-p) # estimated variance = 8114.505 Now let's optimize the negative log-likelihood of our gaussian loss objective, and optimize the log of your coefficients so that on a backtransformed scale they can never be negative : library(bbmle) XM=as.matrix(bM)[,nonzero,drop=FALSE] # design matrix, keeping only covariates with nonnegative nnls coefs colnames(XM)=paste0("v",as.character(1:n))[nonzero] yv=as.vector(y) # response # negative log likelihood function for gaussian loss NEGLL_gaus_logbetas <- function(logbetas, X=XM, y=yv, sd=sqrt(variance)) { -sum(stats::dnorm(x = y, mean = X %*% exp(logbetas), sd = sd, log = TRUE)) } parnames(NEGLL_gaus_logbetas) <- colnames(XM) system.time(fit <- mle2( minuslogl = NEGLL_gaus_logbetas, start = setNames(log(a_nnls[nonzero]+1E-10), colnames(XM)), # we initialise with nnls estimates vecpar = TRUE, optimizer = "nlminb" )) # takes 0.86s AIC(fit) # 2394.857 summary(fit) # now gives log(coefficients) (note that p values are 2 sided) # Coefficients: # Estimate Std. Error z value Pr(z) # v10 4.57339 2.28665 2.0000 0.0454962 * # v11 5.30521 1.10127 4.8173 1.455e-06 *** # v27 3.36162 1.37185 2.4504 0.0142689 * # v38 3.08328 23.98324 0.1286 0.8977059 # v39 3.88101 12.01675 0.3230 0.7467206 # v48 5.63771 3.33932 1.6883 0.0913571 . # v49 4.07475 16.21209 0.2513 0.8015511 # v58 3.77749 19.78448 0.1909 0.8485789 # v59 6.28745 1.53541 4.0950 4.222e-05 *** # v70 1.23613 222.34992 0.0056 0.9955643 # v71 2.67320 54.28789 0.0492 0.9607271 # v80 5.54908 1.12656 4.9257 8.407e-07 *** # v86 5.96813 9.31872 0.6404 0.5218830 # v87 4.27829 84.86010 0.0504 0.9597911 # v88 4.83853 21.42043 0.2259 0.8212918 # v107 6.11318 0.64794 9.4348 < 2.2e-16 *** # v108 4.13673 4.85345 0.8523 0.3940316 # v117 3.27223 1.86578 1.7538 0.0794627 . # v129 4.48811 2.82435 1.5891 0.1120434 # v130 4.79551 2.04481 2.3452 0.0190165 * # v145 3.97314 0.60547 6.5620 5.308e-11 *** # v157 5.49003 0.13670 40.1608 < 2.2e-16 *** # v172 5.88622 1.65908 3.5479 0.0003884 *** # v173 6.49017 1.08156 6.0008 1.964e-09 *** # v181 6.79913 1.81802 3.7399 0.0001841 *** # v182 5.43450 7.66955 0.7086 0.4785848 # v188 1.51878 233.81977 0.0065 0.9948174 # v189 5.06634 5.20058 0.9742 0.3299632 # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # # -2 log L: 2338.857 exp(confint(fit, method="quad")) # backtransformed confidence intervals calculated via quadratic approximation (=Wald confidence intervals) # 2.5 % 97.5 % # v10 1.095964e+00 8.562480e+03 # v11 2.326040e+01 1.743531e+03 # v27 1.959787e+00 4.242829e+02 # v38 8.403942e-20 5.670507e+21 # v39 2.863032e-09 8.206810e+11 # v48 4.036402e-01 1.953696e+05 # v49 9.330044e-13 3.710221e+15 # v58 6.309090e-16 3.027742e+18 # v59 2.652533e+01 1.090313e+04 # v70 1.871739e-189 6.330566e+189 # v71 8.933534e-46 2.349031e+47 # v80 2.824905e+01 2.338118e+03 # v86 4.568985e-06 3.342200e+10 # v87 4.216892e-71 1.233336e+74 # v88 7.383119e-17 2.159994e+20 # v107 1.268806e+02 1.608602e+03 # v108 4.626990e-03 8.468795e+05 # v117 6.806996e-01 1.021572e+03 # v129 3.508065e-01 2.255556e+04 # v130 2.198449e+00 6.655952e+03 # v145 1.622306e+01 1.741383e+02 # v157 1.853224e+02 3.167003e+02 # v172 1.393601e+01 9.301732e+03 # v173 7.907170e+01 5.486191e+03 # v181 2.542890e+01 3.164652e+04 # v182 6.789470e-05 7.735850e+08 # v188 4.284006e-199 4.867958e+199 # v189 5.936664e-03 4.236704e+06 library(broom) signlevels = tidy(fit)$p.value/2 # 1-sided p values for peak to be sign higher than 1 adjsignlevels = p.adjust(signlevels, method="fdr") # FDR corrected p values a_nnlsbbmle = exp(coef(fit)) # exp to backtransform max(a_nnls[nonzero]-a_nnlsbbmle) # -9.981704e-11, coefficients as expected almost the same plot(x, y, type="l", main="Ground truth (red), nnls bbmle logcoeff estimate (blue & green, green=FDR p value<0.05)", ylab="Signal (black) & peaks (red & blue)", xlab="Time", ylim=c(-max(y),max(y))) lines(x,-y) lines(a, type="h", col="red", lwd=2) lines(x[nonzero], -a_nnlsbbmle, type="h", col="blue", lwd=2) lines(x[nonzero][(adjsignlevels<0.05)&(a_nnlsbbmle>1)], -a_nnlsbbmle[(adjsignlevels<0.05)&(a_nnlsbbmle>1)], type="h", col="green", lwd=2) sum((signlevels<0.05)&(a_nnlsbbmle>1)) # 14 peaks significantly higher than 1 before FDR correction sum((adjsignlevels<0.05)&(a_nnlsbbmle>1)) # 11 peaks significant after FDR correction I haven't tried to compare the performance of this method relative to either nonparametric or parametric bootstrapping, but it's surely much faster. I was also inclined to think that I should be able to calculate Wald confidence intervals for the nonnegative nnls coefficients based on the observed Fisher information matrix, calculated at a log transformed coefficient scale to enforce the nonnegativity constraints and evaluated at the nnls estimates. I think this goes like this, and in fact should be formally identical to what I did using mle2 above : XM=as.matrix(bM)[,nonzero,drop=FALSE] # design matrix posbetas = a_nnls[nonzero] # nonzero nnls coefficients dispersion=sum(residuals^2)/(n-p) # estimated dispersion (variance in case of gaussian noise) (1 if noise were poisson or binomial) information_matrix = t(XM) %*% XM # observed Fisher information matrix for nonzero coefs, ie negative of the 2nd derivative (Hessian) of the log likelihood at param estimates scaled_information_matrix = (t(XM) %*% XM)*(1/dispersion) # information matrix scaled by 1/dispersion # let's now calculate this scaled information matrix on a log transformed Y scale (cf. stat.psu.edu/~sesa/stat504/Lecture/lec2part2.pdf, slide 20 eqn 8 & Table 1) to take into account the nonnegativity constraints on the parameters scaled_information_matrix_logscale = scaled_information_matrix/((1/posbetas)^2) # scaled information_matrix on transformed log scale=scaled information matrix/(PHI'(betas)^2) if PHI(beta)=log(beta) vcov_logscale = solve(scaled_information_matrix_logscale) # scaled variance-covariance matrix of coefs on log scale ie of log(posbetas) # PS maybe figure out how to do this in better way using chol2inv & QR decomposition - in R unscaled covariance matrix is calculated as chol2inv(qr(XW_glm)$qr) SEs_logscale = sqrt(diag(vcov_logscale)) # SEs of coefs on log scale ie of log(posbetas) posbetas_LOWER95CL = exp(log(posbetas) - 1.96*SEs_logscale) posbetas_UPPER95CL = exp(log(posbetas) + 1.96*SEs_logscale) data.frame("2.5 %"=posbetas_LOWER95CL,"97.5 %"=posbetas_UPPER95CL,check.names=F) # 2.5 % 97.5 % # 1 1.095874e+00 8.563185e+03 # 2 2.325947e+01 1.743600e+03 # 3 1.959691e+00 4.243037e+02 # 4 8.397159e-20 5.675087e+21 # 5 2.861885e-09 8.210098e+11 # 6 4.036017e-01 1.953882e+05 # 7 9.325838e-13 3.711894e+15 # 8 6.306894e-16 3.028796e+18 # 9 2.652467e+01 1.090340e+04 # 10 1.870702e-189 6.334074e+189 # 11 8.932335e-46 2.349347e+47 # 12 2.824872e+01 2.338145e+03 # 13 4.568282e-06 3.342714e+10 # 14 4.210592e-71 1.235182e+74 # 15 7.380152e-17 2.160863e+20 # 16 1.268778e+02 1.608639e+03 # 17 4.626207e-03 8.470228e+05 # 18 6.806543e-01 1.021640e+03 # 19 3.507709e-01 2.255786e+04 # 20 2.198287e+00 6.656441e+03 # 21 1.622270e+01 1.741421e+02 # 22 1.853214e+02 3.167018e+02 # 23 1.393520e+01 9.302273e+03 # 24 7.906871e+01 5.486398e+03 # 25 2.542730e+01 3.164851e+04 # 26 6.787667e-05 7.737904e+08 # 27 4.249153e-199 4.907886e+199 # 28 5.935583e-03 4.237476e+06 z_logscale = log(posbetas)/SEs_logscale # z values for log(coefs) being greater than 0, ie coefs being > 1 (since log(1) = 0) pvals = pnorm(z_logscale, lower.tail=FALSE) # one-sided p values for log(coefs) being greater than 0, ie coefs being > 1 (since log(1) = 0) pvals.adj = p.adjust(pvals, method="fdr") # FDR corrected p values plot(x, y, type="l", main="Ground truth (red), nnls estimates (blue & green, green=FDR Wald p value<0.05)", ylab="Signal (black) & peaks (red & blue)", xlab="Time", ylim=c(-max(y),max(y))) lines(x,-y) lines(a, type="h", col="red", lwd=2) lines(-a_nnls, type="h", col="blue", lwd=2) lines(x[nonzero][pvals.adj<0.05], -a_nnls[nonzero][pvals.adj<0.05], type="h", col="green", lwd=2) sum((pvals<0.05)&(posbetas>1)) # 14 peaks significantly higher than 1 before FDR correction sum((pvals.adj<0.05)&(posbetas>1)) # 11 peaks significantly higher than 1 after FDR correction The results of these calculations and the ones returned by mle2 are nearly identical (but much faster), so I think this is right, and would correspond that what we were implicitly doing with mle2... Just refitting the covariates with positive coefficients in an nnls fit using a regular linear model fit btw does not work, since such a linear model fit would not take into account the nonnegativity constraints and so would result in nonsensical confidence intervals that could go negative. This paper "Exact post model selection inference for marginal screening" by Jason Lee & Jonathan Taylor also presents a method to do post-model selection inference on nonnegative nnls (or LASSO) coefficients and uses truncated Gaussian distributions for that. I haven't seen any openly available implementation of this method for nnls fits though - for LASSO fits there is the selectiveInference package that does something like that. If anyone would happen to have an implementation, please let me know! In the method above one could also split the data in a training & validation set (e.g. odd & even observations) and infer the covariates with positive coefficients from the training set & then calculate confidence intervals & p values from the validation set. That would be a bit more resistant against overfitting though it would also cause a loss in power since one would only use half of the data. I didn't do it here because the nonnegativity constraint in itself is already quite effective in guarding against overfitting.
Calculating the p-values in a constrained (non-negative) least squares If you would be OK using R I think you could also use bbmle's mle2 function to optimize the least squares likelihood function and calculate 95% confidence intervals on the nonnegative nnls coefficient
25,744
Calculating the p-values in a constrained (non-negative) least squares
To be more specific regarding the Monte Carlo method @Martijn referred do, you can use Bootstrap, a resampling method that involves sampling from the original data (with replacement) multiple data sets for estimating the distribution of the estimated coefficients and therefore any related statistic, including confidence intervals and p-values. The widely used method is detailed here: Efron, Bradley. "Bootstrap methods: another look at the jackknife." Breakthroughs in statistics. Springer, New York, NY, 1992. 569-593. Matlab has it implemented, see https://www.mathworks.com/help/stats/bootstrp.html particularly the section titled Bootstrapping a Regression Model.
Calculating the p-values in a constrained (non-negative) least squares
To be more specific regarding the Monte Carlo method @Martijn referred do, you can use Bootstrap, a resampling method that involves sampling from the original data (with replacement) multiple data set
Calculating the p-values in a constrained (non-negative) least squares To be more specific regarding the Monte Carlo method @Martijn referred do, you can use Bootstrap, a resampling method that involves sampling from the original data (with replacement) multiple data sets for estimating the distribution of the estimated coefficients and therefore any related statistic, including confidence intervals and p-values. The widely used method is detailed here: Efron, Bradley. "Bootstrap methods: another look at the jackknife." Breakthroughs in statistics. Springer, New York, NY, 1992. 569-593. Matlab has it implemented, see https://www.mathworks.com/help/stats/bootstrp.html particularly the section titled Bootstrapping a Regression Model.
Calculating the p-values in a constrained (non-negative) least squares To be more specific regarding the Monte Carlo method @Martijn referred do, you can use Bootstrap, a resampling method that involves sampling from the original data (with replacement) multiple data set
25,745
Any disadvantages of elastic net over lasso?
One disadvantage is the computational cost. You need to cross-validate the relative weight of L1 vs. L2 penalty, $\alpha$, and that increases the computational cost by the number of values in the $\alpha$ grid. Another disadvantage (but at the same time an advantage) is the flexibility of the estimator. With greater flexibility comes increased probability of overfitting. It may be that the optimal $\alpha$ for the population and for the given sample size is $0$, turning elastic net into lasso, but you happen to choose a different value due to chance (because that value delivers better performance when cross-validating in the particular sample).
Any disadvantages of elastic net over lasso?
One disadvantage is the computational cost. You need to cross-validate the relative weight of L1 vs. L2 penalty, $\alpha$, and that increases the computational cost by the number of values in the $\al
Any disadvantages of elastic net over lasso? One disadvantage is the computational cost. You need to cross-validate the relative weight of L1 vs. L2 penalty, $\alpha$, and that increases the computational cost by the number of values in the $\alpha$ grid. Another disadvantage (but at the same time an advantage) is the flexibility of the estimator. With greater flexibility comes increased probability of overfitting. It may be that the optimal $\alpha$ for the population and for the given sample size is $0$, turning elastic net into lasso, but you happen to choose a different value due to chance (because that value delivers better performance when cross-validating in the particular sample).
Any disadvantages of elastic net over lasso? One disadvantage is the computational cost. You need to cross-validate the relative weight of L1 vs. L2 penalty, $\alpha$, and that increases the computational cost by the number of values in the $\al
25,746
Any disadvantages of elastic net over lasso?
A very late reply, but if you're interested in tuning the elastic net: my blog post explains why it is actually very hard to tune alpha and lambda together, which is a disadvantage. Here's the argumentation in a nutshell. First empirical. When one plots cross-validated likelihood (CVL) against alpha and lambda one will notice a ridge in the landscape along which the CVL is very flat and close to the maximum. CVL is strongly linked to marginal likelihood, which is another criterion to tune hyperparameters (= empirical Bayes). For marginal likelihood one can prove that for elastic net this is approximately a Gaussian likelihood with only one variance parameter v. An infinite number of alpha-lambda combinations can render v, implying non-identifiability.
Any disadvantages of elastic net over lasso?
A very late reply, but if you're interested in tuning the elastic net: my blog post explains why it is actually very hard to tune alpha and lambda together, which is a disadvantage. Here's the argumen
Any disadvantages of elastic net over lasso? A very late reply, but if you're interested in tuning the elastic net: my blog post explains why it is actually very hard to tune alpha and lambda together, which is a disadvantage. Here's the argumentation in a nutshell. First empirical. When one plots cross-validated likelihood (CVL) against alpha and lambda one will notice a ridge in the landscape along which the CVL is very flat and close to the maximum. CVL is strongly linked to marginal likelihood, which is another criterion to tune hyperparameters (= empirical Bayes). For marginal likelihood one can prove that for elastic net this is approximately a Gaussian likelihood with only one variance parameter v. An infinite number of alpha-lambda combinations can render v, implying non-identifiability.
Any disadvantages of elastic net over lasso? A very late reply, but if you're interested in tuning the elastic net: my blog post explains why it is actually very hard to tune alpha and lambda together, which is a disadvantage. Here's the argumen
25,747
When not to use cross validation?
Take-home-messages: the excercise should teach you that it is sometimes (depending on your field: often or even almost always) better not to do data-driven model optimization/tuning/selection. There are also situations where cross validation is not the best choice among the different validation options, but these considerations are not relevant in the context of your excercise here. And not validating (verifying, testing) your model is never a good choice. Unfortunately, the text you cite changes two things between approach 1 and 2: Approach 2 performs cross validation and data-driven model selection/tuning/optimization Approach 1 neither uses cross validation, nor data-driven model selection/tuning/optimization. Approach 3 cross validation without data-driven model selection/tuning/optimization is perfectly feasible (amd IMHO would lead to more insight) in the context discussed here Approach 4, no cross validation but data-driven model selection/tuning/optimization is possible as well, but more complex to construct. IMHO, cross validation and data-driven optimization are two totally different (and largely independent) decisions in setting up your modeling strategy. The only connection is that you can use cross validation estimates as target functional for your optimization. But there exist other target functionals ready to be used, and there are other uses of cross validation estimates (importantly, you can use them for verification of your model, aka validation or testing) Unfortunately, machine learning terminology is IMHO currently a mess which suggests false connections/causes/dependencies here. When you look up approach 3 (cross validation not for optimization but for measuring model performance), you'll find the "decision" cross validation vs. training on the whole data set to be a false dichotomy in this context: When using cross validation to measure classifier performance, the cross validation figure of merit is used as estimate for a model trained on the whole data set. I.e. approach 3 includes approach 1. Now, let's look at the 2nd decision: data-driven model optimization or not. This is IMHO the crucial point here. And yes, there are real world situations where not doing data-driven model optimization is better. Data-driven model optimization comes at a cost. You can think of it this way: the information in your data set is used to estimate not only the $p$ parameters/coefficients of the model, but what the optimization does is estimating further parameters, the so-called hyperparameters. If you describe the model fitting and optimiztion/tuning process as a search for the model parameters, then this hyperparameter optimization means that a vastly larger search space is considered. In other words, in approach 1 (and 3) you restrict the search space by specifiying those hyperparameters. Your real world data set may be large enough (contain enough information) to allow fitting within that restricted search space, but not large enough to fix all parameters sufficiently well in the larger search space of approaches 2 (and 4). In fact, in my field I very often have to deal with data sets that far too small to allow any thought of data-driven optimization. So what do I do instead: I use my domain knowledge about the data and data generating processes to decide which model matches well with the physical nature of data and application. And within these, I still have to restrict my model complexity.
When not to use cross validation?
Take-home-messages: the excercise should teach you that it is sometimes (depending on your field: often or even almost always) better not to do data-driven model optimization/tuning/selection. There
When not to use cross validation? Take-home-messages: the excercise should teach you that it is sometimes (depending on your field: often or even almost always) better not to do data-driven model optimization/tuning/selection. There are also situations where cross validation is not the best choice among the different validation options, but these considerations are not relevant in the context of your excercise here. And not validating (verifying, testing) your model is never a good choice. Unfortunately, the text you cite changes two things between approach 1 and 2: Approach 2 performs cross validation and data-driven model selection/tuning/optimization Approach 1 neither uses cross validation, nor data-driven model selection/tuning/optimization. Approach 3 cross validation without data-driven model selection/tuning/optimization is perfectly feasible (amd IMHO would lead to more insight) in the context discussed here Approach 4, no cross validation but data-driven model selection/tuning/optimization is possible as well, but more complex to construct. IMHO, cross validation and data-driven optimization are two totally different (and largely independent) decisions in setting up your modeling strategy. The only connection is that you can use cross validation estimates as target functional for your optimization. But there exist other target functionals ready to be used, and there are other uses of cross validation estimates (importantly, you can use them for verification of your model, aka validation or testing) Unfortunately, machine learning terminology is IMHO currently a mess which suggests false connections/causes/dependencies here. When you look up approach 3 (cross validation not for optimization but for measuring model performance), you'll find the "decision" cross validation vs. training on the whole data set to be a false dichotomy in this context: When using cross validation to measure classifier performance, the cross validation figure of merit is used as estimate for a model trained on the whole data set. I.e. approach 3 includes approach 1. Now, let's look at the 2nd decision: data-driven model optimization or not. This is IMHO the crucial point here. And yes, there are real world situations where not doing data-driven model optimization is better. Data-driven model optimization comes at a cost. You can think of it this way: the information in your data set is used to estimate not only the $p$ parameters/coefficients of the model, but what the optimization does is estimating further parameters, the so-called hyperparameters. If you describe the model fitting and optimiztion/tuning process as a search for the model parameters, then this hyperparameter optimization means that a vastly larger search space is considered. In other words, in approach 1 (and 3) you restrict the search space by specifiying those hyperparameters. Your real world data set may be large enough (contain enough information) to allow fitting within that restricted search space, but not large enough to fix all parameters sufficiently well in the larger search space of approaches 2 (and 4). In fact, in my field I very often have to deal with data sets that far too small to allow any thought of data-driven optimization. So what do I do instead: I use my domain knowledge about the data and data generating processes to decide which model matches well with the physical nature of data and application. And within these, I still have to restrict my model complexity.
When not to use cross validation? Take-home-messages: the excercise should teach you that it is sometimes (depending on your field: often or even almost always) better not to do data-driven model optimization/tuning/selection. There
25,748
Hyperplanes optimally classify data when inputs are conditionally independent - Why?
Sorry about the missing details in our short paper, but these relations and connections between Likelihood Ratio test and sigmoidal neurons are certainly not new, and can be found in textbooks (e.g. Bishop 2006). In our paper, 'N' is the input dimension and 'n' is the test sample size (which actually translated to the input SNR under the assumption that the SNR grows like sqrt(n)). The connection to the sigmoidal function is done through Bayes rule, as the posterior of the class. Nothing in the rest of the paper and our newer and more important paper from 2017 actually depends on this. Naftali Tishby
Hyperplanes optimally classify data when inputs are conditionally independent - Why?
Sorry about the missing details in our short paper, but these relations and connections between Likelihood Ratio test and sigmoidal neurons are certainly not new, and can be found in textbooks (e.g. B
Hyperplanes optimally classify data when inputs are conditionally independent - Why? Sorry about the missing details in our short paper, but these relations and connections between Likelihood Ratio test and sigmoidal neurons are certainly not new, and can be found in textbooks (e.g. Bishop 2006). In our paper, 'N' is the input dimension and 'n' is the test sample size (which actually translated to the input SNR under the assumption that the SNR grows like sqrt(n)). The connection to the sigmoidal function is done through Bayes rule, as the posterior of the class. Nothing in the rest of the paper and our newer and more important paper from 2017 actually depends on this. Naftali Tishby
Hyperplanes optimally classify data when inputs are conditionally independent - Why? Sorry about the missing details in our short paper, but these relations and connections between Likelihood Ratio test and sigmoidal neurons are certainly not new, and can be found in textbooks (e.g. B
25,749
Hyperplanes optimally classify data when inputs are conditionally independent - Why?
This is a model setup where the authors are using a special form of Bayes theorem that applies when you have a binary variable of interest. They first derive this special form of Bayes theorem as Equation (1), and then they show that the condition in Equation (2) leads them to the linear form specified for their network. It is important to note that the latter equation is not derived from previous conditions --- rather, it is a condition for the linear form they are using for their network. Deriving the first equation: Equation (1) in the paper is just a form of Bayes theorem that frames the conditional probability of interest in terms of the standard logistic (sigmoid) function operating on functions of the likelihood and prior. Taking $y$ and $y'$ to be the two binary outcomes of the random variable $Y$, and applying Bayes theorem, gives: $$\begin{equation} \begin{aligned} p(y|\mathbf{x}) = \frac{p(y,\mathbf{x})}{p(\mathbf{x})} &= \frac{p(\mathbf{x}|y) p(y)}{p(\mathbf{x}|y) p(y)+p(\mathbf{x}|y') p(y')} \\[6pt] &= \frac{1}{1+ p(\mathbf{x}|y') p(y')/p(\mathbf{x}|y) p(y)} \\[6pt] &= \frac{1}{1+ \exp \Big( \log \Big( \tfrac{p(\mathbf{x}|y') p(y')}{p(\mathbf{x}|y) p(y)} \Big) \Big)} \\[6pt] &= \frac{1}{1+ \exp \Big( - \log \tfrac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')} - \log \tfrac{p(y)}{p(y')} \Big)} \\[6pt] &= \text{logistic} \Bigg( \log \frac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')} + \log \frac{p(y)}{p(y')} \Bigg). \\[6pt] \end{aligned} \end{equation}$$ Using Equation (2) as a condition for the lienar form of the network: As stated above, this equation is not something that is derived from previous results. Rather, it is a sufficient condition that leads to the linear form that the authors use in their model ---i.e., the authors are saying that if this equation holds, then certain subsequent results follow. Letting the input vector $\mathbf{x} = (x_1,...,x_N)$ have length $N$, if Equation (2) holds, then taking logarithms of both sides gives: $$\begin{equation} \begin{aligned} \log \frac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')} &= \log \prod_{i=1}^N \Big[ \frac{p(x_i|y)}{p(x_i|y')} \Big]^{n p (x_i)} \\[6pt] &= \sum_{i=1}^N n p (x_i) \log \Big[ \frac{p(x_i|y)}{p(x_i|y')} \Big] \\[6pt] &= \sum_{i=1}^N h_i w_i. \\[6pt] \end{aligned} \end{equation}$$ Under this condition, we therefore obtain the posterior form: $$\begin{equation} \begin{aligned} p(y|\mathbf{x}) &= \text{logistic} \Bigg( \log \frac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')} + \log \frac{p(y)}{p(y')} \Bigg) \\[6pt] &= \text{logistic} \Bigg( \sum_{i=1}^N h_i w_i + b \Bigg), \\[6pt] \end{aligned} \end{equation}$$ which is the form that the authors are using in their network. This is the model form postulated by the authors in the background section, prior to specifying Equations (1)-(2). The paper does not define $n$ is in this model setup, but as you point out, the answer by Prof Tishby says that this is the test sample size. In regard to your third question, it appears that the requirement of Equation (2) means that the values in $\mathbf{x}$ are not conditionally independent given $y$.
Hyperplanes optimally classify data when inputs are conditionally independent - Why?
This is a model setup where the authors are using a special form of Bayes theorem that applies when you have a binary variable of interest. They first derive this special form of Bayes theorem as Equ
Hyperplanes optimally classify data when inputs are conditionally independent - Why? This is a model setup where the authors are using a special form of Bayes theorem that applies when you have a binary variable of interest. They first derive this special form of Bayes theorem as Equation (1), and then they show that the condition in Equation (2) leads them to the linear form specified for their network. It is important to note that the latter equation is not derived from previous conditions --- rather, it is a condition for the linear form they are using for their network. Deriving the first equation: Equation (1) in the paper is just a form of Bayes theorem that frames the conditional probability of interest in terms of the standard logistic (sigmoid) function operating on functions of the likelihood and prior. Taking $y$ and $y'$ to be the two binary outcomes of the random variable $Y$, and applying Bayes theorem, gives: $$\begin{equation} \begin{aligned} p(y|\mathbf{x}) = \frac{p(y,\mathbf{x})}{p(\mathbf{x})} &= \frac{p(\mathbf{x}|y) p(y)}{p(\mathbf{x}|y) p(y)+p(\mathbf{x}|y') p(y')} \\[6pt] &= \frac{1}{1+ p(\mathbf{x}|y') p(y')/p(\mathbf{x}|y) p(y)} \\[6pt] &= \frac{1}{1+ \exp \Big( \log \Big( \tfrac{p(\mathbf{x}|y') p(y')}{p(\mathbf{x}|y) p(y)} \Big) \Big)} \\[6pt] &= \frac{1}{1+ \exp \Big( - \log \tfrac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')} - \log \tfrac{p(y)}{p(y')} \Big)} \\[6pt] &= \text{logistic} \Bigg( \log \frac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')} + \log \frac{p(y)}{p(y')} \Bigg). \\[6pt] \end{aligned} \end{equation}$$ Using Equation (2) as a condition for the lienar form of the network: As stated above, this equation is not something that is derived from previous results. Rather, it is a sufficient condition that leads to the linear form that the authors use in their model ---i.e., the authors are saying that if this equation holds, then certain subsequent results follow. Letting the input vector $\mathbf{x} = (x_1,...,x_N)$ have length $N$, if Equation (2) holds, then taking logarithms of both sides gives: $$\begin{equation} \begin{aligned} \log \frac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')} &= \log \prod_{i=1}^N \Big[ \frac{p(x_i|y)}{p(x_i|y')} \Big]^{n p (x_i)} \\[6pt] &= \sum_{i=1}^N n p (x_i) \log \Big[ \frac{p(x_i|y)}{p(x_i|y')} \Big] \\[6pt] &= \sum_{i=1}^N h_i w_i. \\[6pt] \end{aligned} \end{equation}$$ Under this condition, we therefore obtain the posterior form: $$\begin{equation} \begin{aligned} p(y|\mathbf{x}) &= \text{logistic} \Bigg( \log \frac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')} + \log \frac{p(y)}{p(y')} \Bigg) \\[6pt] &= \text{logistic} \Bigg( \sum_{i=1}^N h_i w_i + b \Bigg), \\[6pt] \end{aligned} \end{equation}$$ which is the form that the authors are using in their network. This is the model form postulated by the authors in the background section, prior to specifying Equations (1)-(2). The paper does not define $n$ is in this model setup, but as you point out, the answer by Prof Tishby says that this is the test sample size. In regard to your third question, it appears that the requirement of Equation (2) means that the values in $\mathbf{x}$ are not conditionally independent given $y$.
Hyperplanes optimally classify data when inputs are conditionally independent - Why? This is a model setup where the authors are using a special form of Bayes theorem that applies when you have a binary variable of interest. They first derive this special form of Bayes theorem as Equ
25,750
Hyperplanes optimally classify data when inputs are conditionally independent - Why?
For 1 $P(y \mid x) = \frac{P(y, x)}{P(x)}$ $= \frac{P(y,x)}{\sum_{i}P(y_{i},x)}$ Now as $y_{i}$ is binary, this becomes: $= \frac{P(y,x)}{P(y,x)+P(y',x)}$ $= \frac{1}{1+\frac{P(y',x)}{P(y,x)}}$ $= \frac{1}{1+exp[-log \ \frac{P(y,x)}{P(y',x)}]}$ and from there its just the property of the logarithm to get to the final form (should be sufficiently clear by this point, let me know if not).
Hyperplanes optimally classify data when inputs are conditionally independent - Why?
For 1 $P(y \mid x) = \frac{P(y, x)}{P(x)}$ $= \frac{P(y,x)}{\sum_{i}P(y_{i},x)}$ Now as $y_{i}$ is binary, this becomes: $= \frac{P(y,x)}{P(y,x)+P(y',x)}$ $= \frac{1}{1+\frac{P(y',x)}{P(y,x)}}$ $= \fr
Hyperplanes optimally classify data when inputs are conditionally independent - Why? For 1 $P(y \mid x) = \frac{P(y, x)}{P(x)}$ $= \frac{P(y,x)}{\sum_{i}P(y_{i},x)}$ Now as $y_{i}$ is binary, this becomes: $= \frac{P(y,x)}{P(y,x)+P(y',x)}$ $= \frac{1}{1+\frac{P(y',x)}{P(y,x)}}$ $= \frac{1}{1+exp[-log \ \frac{P(y,x)}{P(y',x)}]}$ and from there its just the property of the logarithm to get to the final form (should be sufficiently clear by this point, let me know if not).
Hyperplanes optimally classify data when inputs are conditionally independent - Why? For 1 $P(y \mid x) = \frac{P(y, x)}{P(x)}$ $= \frac{P(y,x)}{\sum_{i}P(y_{i},x)}$ Now as $y_{i}$ is binary, this becomes: $= \frac{P(y,x)}{P(y,x)+P(y',x)}$ $= \frac{1}{1+\frac{P(y',x)}{P(y,x)}}$ $= \fr
25,751
Hot deck imputation, ''it preserves the distribution of the item values'', how can that be?
Hot-deck imputation of missing values is one of the simplest single-imputation methods. The method - which is intuitively obvious - is that a case with missing value receives valid value from a case randomly chosen from those cases which are maximally similar to the missing one, based on some background variables specified by the user (these variables are also called "deck variables"). The pool of donor cases is called "deck". In the most basic scenario - no background characteristics - you might declare the belonging to the same n-cases dataset to be that and only "background variable"; then the imputation will be just random selection from n-m valid cases to be donors for the m cases with missing values. Random substitution is at the core of hot-deck. To allow for the idea of correlatedness influencing values, matching on more specific background variables is used. For example, you may want to impute the missing response of a white male of 30-35 yrs range from donors belonging to that specific combination of characteristics. Background characterics should be - at least theoretically - associated with the analyzed characteristic (to be imputed); the association, though, should not be the one which is the subject of the study - otherwise it comes we are doing a contamination via imputation. Hot-deck imputation is old still popular because it is both simple in idea and, at the same time, suitable for situations where such methods of processing missing values as listwise deletion or mean/median substitution will not do because missings are allocated in the data not chaotically – not according to MCAR pattern (Missing Completely At Random). Hot-deck is reasonably suited for MAR pattern (for MNAR, multiple-imputation is the only decent solution). Hot-deck, being random borrowing, does not bias marginal distribution, at least potentially. It, however, potentially affects correlations and biases regressional parameters; this effect, however, could be minimized with more complex/sophisticated versions of hot-deck procedure. A shortcoming of hot-deck imputation is that it demands the above mentioned background variables be certainly categorical (because of categorical, no special "matching algorithm" is required); quantitative deck variables - discretize them into categories. As for the variables with missing values - they can be any type, and this is the asset of the method (many alternative forms of single imputation can impute only to quantitative or continuous features). Another weakness of hot-deck imputation is this: when you impute missings in several variables, for example X and Y, i.e. run an imputation function once with X, then with Y, and if case i was missing in both variables, the imputation of i in Y will not be related with what value had been imputed in i in X; in other words, possible correlation between X and Y is not taken into account when imputing Y. In other words, imputation is "univariate", it doesn't recognize potential multivariate nature of the "dependent" (i.e. recipient, having missing values) variables.$^1$ Do not maluse hot-deck imputation. Any imputation of misssings is recommended to do only if there is no more than 20% of cases are missing in a variable. The deck of potential donors must be large enough. If there is one donor it is risky that if it an atypical case you expand the atypicality over other data. Selection of donors with or without replacement. It is posssible to do it either way. In no-replacement regime a donor case, randomly selected, can impute value only to one recipient case. In allow-replacement regime a donor case can become donor again if is randomly selected again, thus imputing to several recipient cases. The 2nd regime may cause severe distributional bias if the recipient cases are many while donor cases suitable to impute there are few, for then one donor will impute its value to many recipients; whereas when there is a lot of donors to choose from, the bias will be tolerable. The no-replacement way leads to no bias but may leave many cases unimputed if there are few donors. Adding noise. Classic hot-deck imputation just borrows (copies) a value as is. It is, however, possible to conceive of adding random noise to a borrowed/imputed value if the value is quantitative. Partial match on deck characteristics. If there are several background variables, a donor case is eligible for random choice if it matches some recipient cases by all the background variables. With more than 2 or 3 such deck characteristics or when they contain many categories that makes it likely not to find eligible donors at all. To overcome, it is possible to require only partial match as necessary to make a donor eligible. For example, require matching on k any of the total g of deck variables. Or, require matching on k first of the list g of deck variables. The greater has occured that k for a potential donor the higher will be its potentiality to be randomly selected. [Partial match as well as replacement/noreplacement are implemented in my hot-dock macro for SPSS.] $^1$ If you insist on taking account of that, you might be recommended two alternatives: (1) at imputing Y, add the already imputed X to the list of background variables (you should make X categorical variable) and use a hot-deck imputation function which allows for partial match on the background variables; (2) extend over Y the imputational solution which had emerged in imputation of X, i.e. use the same donor case. This 2nd alternative is quick and easy, but it is the strict reproduction on Y of the imputation having been done on X, – nothing of independence between the two imputational processes remains here - therefore this alternative is not good. It is possible to do a "constrained" version of hot-deck imputation which takes into account correlations or associations between the imputation variables (variables with missing values) themselves, trying to maintain those correlations. One of possible ways to do it is to arrange these variables as a second and special set of background variables (after binning, if necessary). [I've programmed such imputation for SPSS, you might want to read the algorithm in "Impute missing data" Word document downloadible on my web-site.] Fig. Hot-deck imputation along with some other methods of single imputation. Hot-deck imputation does not model or estimate values for the missings, it selects them randomly from the abundance of present valid cases, and if needed – under restriction conditions.
Hot deck imputation, ''it preserves the distribution of the item values'', how can that be?
Hot-deck imputation of missing values is one of the simplest single-imputation methods. The method - which is intuitively obvious - is that a case with missing value receives valid value from a case r
Hot deck imputation, ''it preserves the distribution of the item values'', how can that be? Hot-deck imputation of missing values is one of the simplest single-imputation methods. The method - which is intuitively obvious - is that a case with missing value receives valid value from a case randomly chosen from those cases which are maximally similar to the missing one, based on some background variables specified by the user (these variables are also called "deck variables"). The pool of donor cases is called "deck". In the most basic scenario - no background characteristics - you might declare the belonging to the same n-cases dataset to be that and only "background variable"; then the imputation will be just random selection from n-m valid cases to be donors for the m cases with missing values. Random substitution is at the core of hot-deck. To allow for the idea of correlatedness influencing values, matching on more specific background variables is used. For example, you may want to impute the missing response of a white male of 30-35 yrs range from donors belonging to that specific combination of characteristics. Background characterics should be - at least theoretically - associated with the analyzed characteristic (to be imputed); the association, though, should not be the one which is the subject of the study - otherwise it comes we are doing a contamination via imputation. Hot-deck imputation is old still popular because it is both simple in idea and, at the same time, suitable for situations where such methods of processing missing values as listwise deletion or mean/median substitution will not do because missings are allocated in the data not chaotically – not according to MCAR pattern (Missing Completely At Random). Hot-deck is reasonably suited for MAR pattern (for MNAR, multiple-imputation is the only decent solution). Hot-deck, being random borrowing, does not bias marginal distribution, at least potentially. It, however, potentially affects correlations and biases regressional parameters; this effect, however, could be minimized with more complex/sophisticated versions of hot-deck procedure. A shortcoming of hot-deck imputation is that it demands the above mentioned background variables be certainly categorical (because of categorical, no special "matching algorithm" is required); quantitative deck variables - discretize them into categories. As for the variables with missing values - they can be any type, and this is the asset of the method (many alternative forms of single imputation can impute only to quantitative or continuous features). Another weakness of hot-deck imputation is this: when you impute missings in several variables, for example X and Y, i.e. run an imputation function once with X, then with Y, and if case i was missing in both variables, the imputation of i in Y will not be related with what value had been imputed in i in X; in other words, possible correlation between X and Y is not taken into account when imputing Y. In other words, imputation is "univariate", it doesn't recognize potential multivariate nature of the "dependent" (i.e. recipient, having missing values) variables.$^1$ Do not maluse hot-deck imputation. Any imputation of misssings is recommended to do only if there is no more than 20% of cases are missing in a variable. The deck of potential donors must be large enough. If there is one donor it is risky that if it an atypical case you expand the atypicality over other data. Selection of donors with or without replacement. It is posssible to do it either way. In no-replacement regime a donor case, randomly selected, can impute value only to one recipient case. In allow-replacement regime a donor case can become donor again if is randomly selected again, thus imputing to several recipient cases. The 2nd regime may cause severe distributional bias if the recipient cases are many while donor cases suitable to impute there are few, for then one donor will impute its value to many recipients; whereas when there is a lot of donors to choose from, the bias will be tolerable. The no-replacement way leads to no bias but may leave many cases unimputed if there are few donors. Adding noise. Classic hot-deck imputation just borrows (copies) a value as is. It is, however, possible to conceive of adding random noise to a borrowed/imputed value if the value is quantitative. Partial match on deck characteristics. If there are several background variables, a donor case is eligible for random choice if it matches some recipient cases by all the background variables. With more than 2 or 3 such deck characteristics or when they contain many categories that makes it likely not to find eligible donors at all. To overcome, it is possible to require only partial match as necessary to make a donor eligible. For example, require matching on k any of the total g of deck variables. Or, require matching on k first of the list g of deck variables. The greater has occured that k for a potential donor the higher will be its potentiality to be randomly selected. [Partial match as well as replacement/noreplacement are implemented in my hot-dock macro for SPSS.] $^1$ If you insist on taking account of that, you might be recommended two alternatives: (1) at imputing Y, add the already imputed X to the list of background variables (you should make X categorical variable) and use a hot-deck imputation function which allows for partial match on the background variables; (2) extend over Y the imputational solution which had emerged in imputation of X, i.e. use the same donor case. This 2nd alternative is quick and easy, but it is the strict reproduction on Y of the imputation having been done on X, – nothing of independence between the two imputational processes remains here - therefore this alternative is not good. It is possible to do a "constrained" version of hot-deck imputation which takes into account correlations or associations between the imputation variables (variables with missing values) themselves, trying to maintain those correlations. One of possible ways to do it is to arrange these variables as a second and special set of background variables (after binning, if necessary). [I've programmed such imputation for SPSS, you might want to read the algorithm in "Impute missing data" Word document downloadible on my web-site.] Fig. Hot-deck imputation along with some other methods of single imputation. Hot-deck imputation does not model or estimate values for the missings, it selects them randomly from the abundance of present valid cases, and if needed – under restriction conditions.
Hot deck imputation, ''it preserves the distribution of the item values'', how can that be? Hot-deck imputation of missing values is one of the simplest single-imputation methods. The method - which is intuitively obvious - is that a case with missing value receives valid value from a case r
25,752
Is stl a good technique for forecasting, instead of Arima?
The Forecasting: principles and practice book by Rob J. Hyndman and George Anthanasopoulos answers your question: STL has several advantages over the classical decomposition method and X-12-ARIMA: Unlike X-12-ARIMA, STL will handle any type of seasonality, not only monthly and quarterly data. The seasonal component is allowed to change over time, and the rate of change can be controlled by the user. The smoothness of the trend-cycle can also be controlled by the user. It can be robust to outliers (i.e., the user can specify a robust decomposition). So occasional unusual observations will not affect the estimates of the trend-cycle and seasonal components. They will, however, affect the remainder component. On the other hand, STL has some disadvantages. In particular, it does not automatically handle trading day or calendar variation, and it only provides facilities for additive decompositions. So STL can deal with phenomena such as multiple seasonalities, high-frequency seasonalities (e.g. 365 for daily data) and cycles. However if you have daily data you can go for a model which tackles the thematic of multiple seasonalities, e.g. TBATS instead of STL. If you have many multiple seasonalities and millions or billions of observations you can go for data-savvy complex models such as recurrent neural nets. STL might be a useful approach for modeling business cycles. In a business cycle not every cycle has exact the same length, but they are rather an irregularly recurring phenomenon. Sometimes recession might last 2 years and sometimes it might last 5 or 6. STL is more able to capture this kind of uncertainty than ARIMA. Also if you cannot make your data stationary STL will be more useful than ARIMA. ARIMA requires the data to be stationary or at least to be stationary in differences. You can also take a part of your data as test set and test whether on your particular dataset STL works better than ARIMA. STL is usually used for understanding and describing the data, but you can combine it with simple forecasting methods as described in chapter 6.6 of the book I mentioned above. These simply forecasting methods are not always "worse" than complex methods such as Auto-regressive models, neural nets or Bayesian models such as Kalman filter. You can compare them for instance by using scaled errors (e.g. MAE and RMSE) on the training and the test set of your data.
Is stl a good technique for forecasting, instead of Arima?
The Forecasting: principles and practice book by Rob J. Hyndman and George Anthanasopoulos answers your question: STL has several advantages over the classical decomposition method and X-12-ARIMA: Un
Is stl a good technique for forecasting, instead of Arima? The Forecasting: principles and practice book by Rob J. Hyndman and George Anthanasopoulos answers your question: STL has several advantages over the classical decomposition method and X-12-ARIMA: Unlike X-12-ARIMA, STL will handle any type of seasonality, not only monthly and quarterly data. The seasonal component is allowed to change over time, and the rate of change can be controlled by the user. The smoothness of the trend-cycle can also be controlled by the user. It can be robust to outliers (i.e., the user can specify a robust decomposition). So occasional unusual observations will not affect the estimates of the trend-cycle and seasonal components. They will, however, affect the remainder component. On the other hand, STL has some disadvantages. In particular, it does not automatically handle trading day or calendar variation, and it only provides facilities for additive decompositions. So STL can deal with phenomena such as multiple seasonalities, high-frequency seasonalities (e.g. 365 for daily data) and cycles. However if you have daily data you can go for a model which tackles the thematic of multiple seasonalities, e.g. TBATS instead of STL. If you have many multiple seasonalities and millions or billions of observations you can go for data-savvy complex models such as recurrent neural nets. STL might be a useful approach for modeling business cycles. In a business cycle not every cycle has exact the same length, but they are rather an irregularly recurring phenomenon. Sometimes recession might last 2 years and sometimes it might last 5 or 6. STL is more able to capture this kind of uncertainty than ARIMA. Also if you cannot make your data stationary STL will be more useful than ARIMA. ARIMA requires the data to be stationary or at least to be stationary in differences. You can also take a part of your data as test set and test whether on your particular dataset STL works better than ARIMA. STL is usually used for understanding and describing the data, but you can combine it with simple forecasting methods as described in chapter 6.6 of the book I mentioned above. These simply forecasting methods are not always "worse" than complex methods such as Auto-regressive models, neural nets or Bayesian models such as Kalman filter. You can compare them for instance by using scaled errors (e.g. MAE and RMSE) on the training and the test set of your data.
Is stl a good technique for forecasting, instead of Arima? The Forecasting: principles and practice book by Rob J. Hyndman and George Anthanasopoulos answers your question: STL has several advantages over the classical decomposition method and X-12-ARIMA: Un
25,753
For feature selection in linear regression model, can I use coefficient estimates?
To begin with, just to put the issue aside: clearly, if the features are not normalized to 0 mean and unit variance, it's easy to build cases where the coefficient means very little. In general, if you take a feature and multiply it by $\alpha$, a regressor will divide the coefficient by $\alpha$, for example. Even when the variables are all normalized, large coefficients can mean very little. Say that $x$ is some hidden feature somewhat correlated with $y$, and $z$ and $w$ are observed featured which are slightly noisy versions of $x$, the regression matrix will be not very well defined, and you could get large-magnitude coefficients for $z$ and $w$ (perhaps with opposite signs). Regularization is usually used precisely to avoid this. Perhaps sklearn.feature_selection.f_regression is similar to what you're looking for. It summarizes, for each individual feature, both the f-score and the p-value. Alternatively, for any regression scheme, a "black box" approach could be to build the model for all features except $x$, and assess its performance (using cross validation). You could then rank the features based on the performance. Feature importance is a bit trick to define. In the above two schemes, if $x_i$ is the $i$the resulting "most important" feature, it does not necessarily mean that using $x_1, \ldots x_{i - 1}$, it is indeed the next most important one (perhaps its information is already contained in the preceding ones).
For feature selection in linear regression model, can I use coefficient estimates?
To begin with, just to put the issue aside: clearly, if the features are not normalized to 0 mean and unit variance, it's easy to build cases where the coefficient means very little. In general, if yo
For feature selection in linear regression model, can I use coefficient estimates? To begin with, just to put the issue aside: clearly, if the features are not normalized to 0 mean and unit variance, it's easy to build cases where the coefficient means very little. In general, if you take a feature and multiply it by $\alpha$, a regressor will divide the coefficient by $\alpha$, for example. Even when the variables are all normalized, large coefficients can mean very little. Say that $x$ is some hidden feature somewhat correlated with $y$, and $z$ and $w$ are observed featured which are slightly noisy versions of $x$, the regression matrix will be not very well defined, and you could get large-magnitude coefficients for $z$ and $w$ (perhaps with opposite signs). Regularization is usually used precisely to avoid this. Perhaps sklearn.feature_selection.f_regression is similar to what you're looking for. It summarizes, for each individual feature, both the f-score and the p-value. Alternatively, for any regression scheme, a "black box" approach could be to build the model for all features except $x$, and assess its performance (using cross validation). You could then rank the features based on the performance. Feature importance is a bit trick to define. In the above two schemes, if $x_i$ is the $i$the resulting "most important" feature, it does not necessarily mean that using $x_1, \ldots x_{i - 1}$, it is indeed the next most important one (perhaps its information is already contained in the preceding ones).
For feature selection in linear regression model, can I use coefficient estimates? To begin with, just to put the issue aside: clearly, if the features are not normalized to 0 mean and unit variance, it's easy to build cases where the coefficient means very little. In general, if yo
25,754
For feature selection in linear regression model, can I use coefficient estimates?
From my point of view, you can select features based on coefficients in the case of using Ridge regression rather than simple linear regression. I agree that a naive linear regression method will generate extremely large coefficients if any two features are highly correlated. However, when you adopt the ridge regression model, this problem will disappear. In fact, it is rather intuitive to select features based on coefficients. If we slightly change the value of one feature, the more response value changes, the more important features are. In fact, this idea is nearly identical to the permutation feature importance, which is widely used as a black-box feature importance analysis approach. For example, in the following code fragment, I give an example to show coefficient values of features in the regression model and their corresponding permutation feature importance. From the results, it is clear that feature coefficients are basically identical to the permutation feature importance of those features. Thus, in conclusion, it is reasonable to use the coefficients of the ridge regression model as a rough approximation of feature importance. import numpy as np from sklearn.datasets import load_diabetes from sklearn.inspection import permutation_importance from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split diabetes = load_diabetes() X_train, X_val, y_train, y_val = train_test_split( diabetes.data, diabetes.target, random_state=0) model = Ridge(alpha=1e-2).fit(X_train, y_train) model.score(X_val, y_val) for i in np.abs(model.coef_).argsort()[::-1][:5]: print(diabetes.feature_names[i], np.abs(model.coef_[i])) r = permutation_importance(model, X_val, y_val, n_repeats=30, random_state=0) for i in r.importances_mean.argsort()[::-1]: if r.importances_mean[i] - 2 * r.importances_std[i] > 0: print(f"{diabetes.feature_names[i]:<8}" f"{r.importances_mean[i]:.3f}" f" +/- {r.importances_std[i]:.3f}") bmi 592.2534291944405 s5 580.078063710006 bp 297.2581037274451 s1 252.42469967919644 sex 203.43588499880846 s5 0.204 +/- 0.050 bmi 0.176 +/- 0.048 bp 0.088 +/- 0.033 sex 0.056 +/- 0.023 Finally, it should be noted that both the mentioned methods are fragile to the multicollinearity problem. Thus, in that case, we need to eliminate highly correlated features first, and then we can directly use the model coefficients as feature importance.
For feature selection in linear regression model, can I use coefficient estimates?
From my point of view, you can select features based on coefficients in the case of using Ridge regression rather than simple linear regression. I agree that a naive linear regression method will gene
For feature selection in linear regression model, can I use coefficient estimates? From my point of view, you can select features based on coefficients in the case of using Ridge regression rather than simple linear regression. I agree that a naive linear regression method will generate extremely large coefficients if any two features are highly correlated. However, when you adopt the ridge regression model, this problem will disappear. In fact, it is rather intuitive to select features based on coefficients. If we slightly change the value of one feature, the more response value changes, the more important features are. In fact, this idea is nearly identical to the permutation feature importance, which is widely used as a black-box feature importance analysis approach. For example, in the following code fragment, I give an example to show coefficient values of features in the regression model and their corresponding permutation feature importance. From the results, it is clear that feature coefficients are basically identical to the permutation feature importance of those features. Thus, in conclusion, it is reasonable to use the coefficients of the ridge regression model as a rough approximation of feature importance. import numpy as np from sklearn.datasets import load_diabetes from sklearn.inspection import permutation_importance from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split diabetes = load_diabetes() X_train, X_val, y_train, y_val = train_test_split( diabetes.data, diabetes.target, random_state=0) model = Ridge(alpha=1e-2).fit(X_train, y_train) model.score(X_val, y_val) for i in np.abs(model.coef_).argsort()[::-1][:5]: print(diabetes.feature_names[i], np.abs(model.coef_[i])) r = permutation_importance(model, X_val, y_val, n_repeats=30, random_state=0) for i in r.importances_mean.argsort()[::-1]: if r.importances_mean[i] - 2 * r.importances_std[i] > 0: print(f"{diabetes.feature_names[i]:<8}" f"{r.importances_mean[i]:.3f}" f" +/- {r.importances_std[i]:.3f}") bmi 592.2534291944405 s5 580.078063710006 bp 297.2581037274451 s1 252.42469967919644 sex 203.43588499880846 s5 0.204 +/- 0.050 bmi 0.176 +/- 0.048 bp 0.088 +/- 0.033 sex 0.056 +/- 0.023 Finally, it should be noted that both the mentioned methods are fragile to the multicollinearity problem. Thus, in that case, we need to eliminate highly correlated features first, and then we can directly use the model coefficients as feature importance.
For feature selection in linear regression model, can I use coefficient estimates? From my point of view, you can select features based on coefficients in the case of using Ridge regression rather than simple linear regression. I agree that a naive linear regression method will gene
25,755
Perplexity and cross-entropy for n-gram models
Yes, the perplexity is always equal to two to the power of the entropy. It doesn't matter what type of model you have, n-gram, unigram, or neural network. There are a few reasons why language modeling people like perplexity instead of just using entropy. One is that, because of the exponent, improvements in perplexity "feel" like they are more substantial than the equivalent improvement in entropy. Another is that before they started using perplexity, the complexity of a language model was reported using a simplistic branching factor measurement that is more similar to perplexity than it is to entropy.
Perplexity and cross-entropy for n-gram models
Yes, the perplexity is always equal to two to the power of the entropy. It doesn't matter what type of model you have, n-gram, unigram, or neural network. There are a few reasons why language modelin
Perplexity and cross-entropy for n-gram models Yes, the perplexity is always equal to two to the power of the entropy. It doesn't matter what type of model you have, n-gram, unigram, or neural network. There are a few reasons why language modeling people like perplexity instead of just using entropy. One is that, because of the exponent, improvements in perplexity "feel" like they are more substantial than the equivalent improvement in entropy. Another is that before they started using perplexity, the complexity of a language model was reported using a simplistic branching factor measurement that is more similar to perplexity than it is to entropy.
Perplexity and cross-entropy for n-gram models Yes, the perplexity is always equal to two to the power of the entropy. It doesn't matter what type of model you have, n-gram, unigram, or neural network. There are a few reasons why language modelin
25,756
Perplexity and cross-entropy for n-gram models
Agreed with the @Aaron answer with a slight modification: It's not always equal to two to the power of the entropy. Actually, It will be (base for log) to the power of entropy. If you have used e as your base then it would be e^entropy.
Perplexity and cross-entropy for n-gram models
Agreed with the @Aaron answer with a slight modification: It's not always equal to two to the power of the entropy. Actually, It will be (base for log) to the power of entropy. If you have used e as
Perplexity and cross-entropy for n-gram models Agreed with the @Aaron answer with a slight modification: It's not always equal to two to the power of the entropy. Actually, It will be (base for log) to the power of entropy. If you have used e as your base then it would be e^entropy.
Perplexity and cross-entropy for n-gram models Agreed with the @Aaron answer with a slight modification: It's not always equal to two to the power of the entropy. Actually, It will be (base for log) to the power of entropy. If you have used e as
25,757
How to calculate confidence interval for a geometric mean?
You can compute the arithmetic mean of the log growth rate: Let $V_t$ be the value of your portfolio at time $t$ Let $R_t = \frac{V_t}{V_{t-1}}$ be the growth rate of your portfolio from $t-1$ to $t$ The basic idea is to take logs and do your standard stuff. Taking logs transforms multiplication into a sum. Let $r_t = \log R_t$ be the log growth rate. $$\bar{r} = \frac{1}{T} \sum_{t=1}^T r_t \quad \quad s_r = \sqrt{\frac{1}{T-1} \sum_{t=1}^T \left( r_t - \bar{r}\right)^2}$$ Then your standard error $\mathit{SE}_{\bar{r}}$ for your sample mean $\bar{r}$ is given by: $$ \mathit{SE}_{\bar{r}} = \frac{s_r}{\sqrt{T}}$$ The 95 percent confidence interval for $\mu_r = {\operatorname{E}[r_t]}$ would be approximately: $$\left( \bar{r} - 2 \mathit{SE}_{\bar{r}} , \bar{r} + 2 \mathit{SE}_{\bar{r}} \right)$$. Exponentiate to get confidence interval for $e^{\mu_r}$ Since $e^x$ is a strictly increasing function, a 95 percent confidence interval for $e^{\mu_r}$ would be: $$\left( e^{\bar{r} - 2 \mathit{SE}_{\bar{r}}} , e^{\bar{r} + 2 \mathit{SE}_{\bar{r}}} \right)$$ And we're done. Why are we done? Observe $\bar{r} = \frac{1}{T} \sum_t r_t$ is the log of the geometric mean Hence $e^{\bar{r}}$ is geometric mean of your sample. To show this, observe the geometric mean is given by: $$ \mathit{GM} = \left(R_1R_2\ldots R_T\right)^\frac{1}{T}$$ Hence if we take the log of both sides: \begin{align*} \log \mathit{GM} &= \frac{1}{T} \sum_{t=1}^T \log R_t \\ &= \bar{r} \end{align*} Some example to build intuition: Let's say you compute the mean log growth rate is $.02$. Then the geometric mean is $\exp(.02) \approx 1.0202$. Let's say you compute the mean log growth rate is $-.05$, then the geometric mean is $\exp(-.05) = .9512$ For $x \approx 1$, we have $\log(x) \approx x - 1$ and for $y \approx 0$, we have $\exp(y) \approx y + 1$. Further away though, those tricks breka down: Let's say you compute the mean log growth rate is $.69$, then the geometric mean mean is $\exp(.69) \approx 2$ (i.e. the value doubles every period). If all your log growth rates $r_t$ are near zero (or equivalently $\frac{V_t}{V_{t-1}}$ is near 1, then you'll find that the geometric mean and the arithmetic mean will be quite close Another answer that might be useful: As this answer discusses, log differences are basically percent changes. Comment: it's useful in finance to get comfortable thinking in logs. It's similar to thinking in terms of percent changes but mathematically cleaner.
How to calculate confidence interval for a geometric mean?
You can compute the arithmetic mean of the log growth rate: Let $V_t$ be the value of your portfolio at time $t$ Let $R_t = \frac{V_t}{V_{t-1}}$ be the growth rate of your portfolio from $t-1$ to $t$
How to calculate confidence interval for a geometric mean? You can compute the arithmetic mean of the log growth rate: Let $V_t$ be the value of your portfolio at time $t$ Let $R_t = \frac{V_t}{V_{t-1}}$ be the growth rate of your portfolio from $t-1$ to $t$ The basic idea is to take logs and do your standard stuff. Taking logs transforms multiplication into a sum. Let $r_t = \log R_t$ be the log growth rate. $$\bar{r} = \frac{1}{T} \sum_{t=1}^T r_t \quad \quad s_r = \sqrt{\frac{1}{T-1} \sum_{t=1}^T \left( r_t - \bar{r}\right)^2}$$ Then your standard error $\mathit{SE}_{\bar{r}}$ for your sample mean $\bar{r}$ is given by: $$ \mathit{SE}_{\bar{r}} = \frac{s_r}{\sqrt{T}}$$ The 95 percent confidence interval for $\mu_r = {\operatorname{E}[r_t]}$ would be approximately: $$\left( \bar{r} - 2 \mathit{SE}_{\bar{r}} , \bar{r} + 2 \mathit{SE}_{\bar{r}} \right)$$. Exponentiate to get confidence interval for $e^{\mu_r}$ Since $e^x$ is a strictly increasing function, a 95 percent confidence interval for $e^{\mu_r}$ would be: $$\left( e^{\bar{r} - 2 \mathit{SE}_{\bar{r}}} , e^{\bar{r} + 2 \mathit{SE}_{\bar{r}}} \right)$$ And we're done. Why are we done? Observe $\bar{r} = \frac{1}{T} \sum_t r_t$ is the log of the geometric mean Hence $e^{\bar{r}}$ is geometric mean of your sample. To show this, observe the geometric mean is given by: $$ \mathit{GM} = \left(R_1R_2\ldots R_T\right)^\frac{1}{T}$$ Hence if we take the log of both sides: \begin{align*} \log \mathit{GM} &= \frac{1}{T} \sum_{t=1}^T \log R_t \\ &= \bar{r} \end{align*} Some example to build intuition: Let's say you compute the mean log growth rate is $.02$. Then the geometric mean is $\exp(.02) \approx 1.0202$. Let's say you compute the mean log growth rate is $-.05$, then the geometric mean is $\exp(-.05) = .9512$ For $x \approx 1$, we have $\log(x) \approx x - 1$ and for $y \approx 0$, we have $\exp(y) \approx y + 1$. Further away though, those tricks breka down: Let's say you compute the mean log growth rate is $.69$, then the geometric mean mean is $\exp(.69) \approx 2$ (i.e. the value doubles every period). If all your log growth rates $r_t$ are near zero (or equivalently $\frac{V_t}{V_{t-1}}$ is near 1, then you'll find that the geometric mean and the arithmetic mean will be quite close Another answer that might be useful: As this answer discusses, log differences are basically percent changes. Comment: it's useful in finance to get comfortable thinking in logs. It's similar to thinking in terms of percent changes but mathematically cleaner.
How to calculate confidence interval for a geometric mean? You can compute the arithmetic mean of the log growth rate: Let $V_t$ be the value of your portfolio at time $t$ Let $R_t = \frac{V_t}{V_{t-1}}$ be the growth rate of your portfolio from $t-1$ to $t$
25,758
How to calculate confidence interval for a geometric mean?
Let's just extract the statistical problem at hand. You have $X_1, \dots X_n$ from some distribution with mean $\mu$ and variance $\sigma^2$. Consider $Y_i = \log X_i$, where the mean of $Y$ is $\mu_y$ and variance is $\sigma^2_y$. Consider the average of $Y$s: $\bar{Y}_n = \sum_{i=1}^{n} Y_i/n$. Then due to the CLT, $$ \sqrt{n} (\bar{Y}_n - \mu_y) \overset{d}{\to} N(0, \sigma^2_y)\,.$$ Now consider $e^{\bar{Y}_n}$. \begin{align*} e^{\bar{Y}_n} & = \exp\left\{\sum_{i=1}^{n}\dfrac{1}{n} \log Y_i \right\}\\ & = \exp\left\{\sum_{i=1}^{n} \log Y_i^{1/n} \right\}\\ & = \prod_{i=1}^{n}\exp\left\{ \log Y_i^{1/n}\right\}\\ & = \prod_{i=1}^{n} Y_i^{1/n}\,. \end{align*} Thus, $ e^{\bar{Y}}$ is the geometric mean! So next, we can apply the Delta method to the CLT method. Define $g(x) = e^{x}$, then $g'(x) = e^x$. By the Delta method $$\sqrt{n}(e^{\bar{Y}_n} - e^{\mu_y}) \overset{d}{\to} N(0, e^{2\mu_y}\sigma^2_y).$$ So now you have a tool to make your confidence intervals from. $e^{\mu_y}$ is your true geometric mean, and you want to make a confidence interval for this (this is not a confidence interval for the expected value $\mu$). The first step is estimate $\sigma^2_y$. Since $\sigma^2_y$ is the variance of the $Y$s, $$ s^2_y:= \dfrac{1}{n} \sum_{i=1}^{n}(Y_i - \bar{Y}_n)^2 = \dfrac{1}{n}\sum_{i=1}^{n} (\log X_i - \log e^{\bar{Y}_n})^2 = \dfrac{1}{n} \sum_{i=1}^{n} \log \left( \dfrac{X_i}{e^{\bar{Y}_n}} \right)\,.$$ To make your $100(1 - \alpha)$% confidence interval for the true geometric mean: $$e^{\bar{Y}_n} \pm z_{1-\alpha/2}\dfrac{e^{\bar{Y}_n} s_y}{\sqrt{n}}\,.$$
How to calculate confidence interval for a geometric mean?
Let's just extract the statistical problem at hand. You have $X_1, \dots X_n$ from some distribution with mean $\mu$ and variance $\sigma^2$. Consider $Y_i = \log X_i$, where the mean of $Y$ is $\mu_y
How to calculate confidence interval for a geometric mean? Let's just extract the statistical problem at hand. You have $X_1, \dots X_n$ from some distribution with mean $\mu$ and variance $\sigma^2$. Consider $Y_i = \log X_i$, where the mean of $Y$ is $\mu_y$ and variance is $\sigma^2_y$. Consider the average of $Y$s: $\bar{Y}_n = \sum_{i=1}^{n} Y_i/n$. Then due to the CLT, $$ \sqrt{n} (\bar{Y}_n - \mu_y) \overset{d}{\to} N(0, \sigma^2_y)\,.$$ Now consider $e^{\bar{Y}_n}$. \begin{align*} e^{\bar{Y}_n} & = \exp\left\{\sum_{i=1}^{n}\dfrac{1}{n} \log Y_i \right\}\\ & = \exp\left\{\sum_{i=1}^{n} \log Y_i^{1/n} \right\}\\ & = \prod_{i=1}^{n}\exp\left\{ \log Y_i^{1/n}\right\}\\ & = \prod_{i=1}^{n} Y_i^{1/n}\,. \end{align*} Thus, $ e^{\bar{Y}}$ is the geometric mean! So next, we can apply the Delta method to the CLT method. Define $g(x) = e^{x}$, then $g'(x) = e^x$. By the Delta method $$\sqrt{n}(e^{\bar{Y}_n} - e^{\mu_y}) \overset{d}{\to} N(0, e^{2\mu_y}\sigma^2_y).$$ So now you have a tool to make your confidence intervals from. $e^{\mu_y}$ is your true geometric mean, and you want to make a confidence interval for this (this is not a confidence interval for the expected value $\mu$). The first step is estimate $\sigma^2_y$. Since $\sigma^2_y$ is the variance of the $Y$s, $$ s^2_y:= \dfrac{1}{n} \sum_{i=1}^{n}(Y_i - \bar{Y}_n)^2 = \dfrac{1}{n}\sum_{i=1}^{n} (\log X_i - \log e^{\bar{Y}_n})^2 = \dfrac{1}{n} \sum_{i=1}^{n} \log \left( \dfrac{X_i}{e^{\bar{Y}_n}} \right)\,.$$ To make your $100(1 - \alpha)$% confidence interval for the true geometric mean: $$e^{\bar{Y}_n} \pm z_{1-\alpha/2}\dfrac{e^{\bar{Y}_n} s_y}{\sqrt{n}}\,.$$
How to calculate confidence interval for a geometric mean? Let's just extract the statistical problem at hand. You have $X_1, \dots X_n$ from some distribution with mean $\mu$ and variance $\sigma^2$. Consider $Y_i = \log X_i$, where the mean of $Y$ is $\mu_y
25,759
Famous data visualizations [duplicate]
Charles Joseph Minrad's https://en.wikipedia.org/wiki/Charles_Joseph_Minard famous map presenting Napoleon's rather catastrophic russian campaign in 1812: The map shows multiple variables at once, most clear the (diminishing!) number of troops, and where and when they retreated or simply vanished, but also temperature (the below part of the map) and time. Edward Tufte https://en.wikipedia.org/wiki/Edward_Tufte said about this map that it may well be the best statistical graphic ever drawn see E Tufte: "The Visual Display of Quantitative Information" p. 40. so it certainly belongs in this thread!
Famous data visualizations [duplicate]
Charles Joseph Minrad's https://en.wikipedia.org/wiki/Charles_Joseph_Minard famous map presenting Napoleon's rather catastrophic russian campaign in 1812: The map shows multiple variables at once, mo
Famous data visualizations [duplicate] Charles Joseph Minrad's https://en.wikipedia.org/wiki/Charles_Joseph_Minard famous map presenting Napoleon's rather catastrophic russian campaign in 1812: The map shows multiple variables at once, most clear the (diminishing!) number of troops, and where and when they retreated or simply vanished, but also temperature (the below part of the map) and time. Edward Tufte https://en.wikipedia.org/wiki/Edward_Tufte said about this map that it may well be the best statistical graphic ever drawn see E Tufte: "The Visual Display of Quantitative Information" p. 40. so it certainly belongs in this thread!
Famous data visualizations [duplicate] Charles Joseph Minrad's https://en.wikipedia.org/wiki/Charles_Joseph_Minard famous map presenting Napoleon's rather catastrophic russian campaign in 1812: The map shows multiple variables at once, mo
25,760
Famous data visualizations [duplicate]
I'll put up a non-traditional answer: Feynman Diagrams (i.e. not statistical, but definately data related). Feynman Diagrams are a tool for organizing computations in field theories in physics. Feynman first invented them to organize terms in computations in quantum electrodynamics (QED) (so the "data" being organized here are the terms in a very difficult computation). They are a combinatorial device used to encode all the ways in which certain events can occur in QED, or more formally, all the terms appearing in a mathematical expansion for the probability amplitude of an event. They way they organized the data occurring in these computations allowed Feynman to show that QED did not produce infinite probabilities, an achievement called renormalization, for which he won a Nobel prize. Two other men, Julian Schwinger and Sin-Itiro Tomonaga, also won a Nobel for the same achievement, but it is Feynman's techniques, aided by his diagrams, that have stood the test of time. A famous example is the Penguin Diagram which were invented when physicists were discovering that some very natural symmetries did not hold in nature (parity and charge conjugation).
Famous data visualizations [duplicate]
I'll put up a non-traditional answer: Feynman Diagrams (i.e. not statistical, but definately data related). Feynman Diagrams are a tool for organizing computations in field theories in physics. Fey
Famous data visualizations [duplicate] I'll put up a non-traditional answer: Feynman Diagrams (i.e. not statistical, but definately data related). Feynman Diagrams are a tool for organizing computations in field theories in physics. Feynman first invented them to organize terms in computations in quantum electrodynamics (QED) (so the "data" being organized here are the terms in a very difficult computation). They are a combinatorial device used to encode all the ways in which certain events can occur in QED, or more formally, all the terms appearing in a mathematical expansion for the probability amplitude of an event. They way they organized the data occurring in these computations allowed Feynman to show that QED did not produce infinite probabilities, an achievement called renormalization, for which he won a Nobel prize. Two other men, Julian Schwinger and Sin-Itiro Tomonaga, also won a Nobel for the same achievement, but it is Feynman's techniques, aided by his diagrams, that have stood the test of time. A famous example is the Penguin Diagram which were invented when physicists were discovering that some very natural symmetries did not hold in nature (parity and charge conjugation).
Famous data visualizations [duplicate] I'll put up a non-traditional answer: Feynman Diagrams (i.e. not statistical, but definately data related). Feynman Diagrams are a tool for organizing computations in field theories in physics. Fey
25,761
Bayesian model selection and credible interval
It is well known that building a model based on what is significant (or some other criterion such as AIC, whether a credible interval contains 0 etc.) is pretty problematic, particularly if you then do inference as if you had not done model building. Doing a Bayesian analysis does not change that (see also https://stats.stackexchange.com/a/201931/86652). I.e. you should not do variable selection, but rather model averaging (or something that could get you some zero coefficients, but reflects the whole modelling process, such as LASSO or elastic net). Bayesian model choice is more typically framed as Bayesian model averaging. You have different models, each with a different prior probability. If the posterior model probability for a model becomes low enough, you are essentially entirely discarding the model. For equal prior weights for each model and flat priors, model averaging with weights proportional to $\exp(-\text{BIC}/2)$ for each model approximates this. You can alternatively express the model averaging as a prior that is a mixture between a point mass (the weight of the point mass is the prior probability of the effect being exactly zero = the effect is not in the model) and a continuous distribution (e.g. spike-and-slab priors). MCMC sampling can be quite difficult for such a prior. Carvalho et al. motivate the horseshoe shrinkage prior by suggesting that it works like a continuous approximation to a spike-and-slab prior. It is also a case of embedding the problem in a hierarchical model, where to some extent the size and presence of effects on some variables relax the required evidence for others a bit (through the global shrinkage parameter, this is a bit like false-discovery rate control) and on the other hand allow individual effects to stand on their own if the evidence is clear enough. There is a convenient implementation of it available from the brms R package that builds on Stan/rstan. There are a number of further similar priors such as the horseshoe+ prior and the whole topic is an area of ongoing research.
Bayesian model selection and credible interval
It is well known that building a model based on what is significant (or some other criterion such as AIC, whether a credible interval contains 0 etc.) is pretty problematic, particularly if you then d
Bayesian model selection and credible interval It is well known that building a model based on what is significant (or some other criterion such as AIC, whether a credible interval contains 0 etc.) is pretty problematic, particularly if you then do inference as if you had not done model building. Doing a Bayesian analysis does not change that (see also https://stats.stackexchange.com/a/201931/86652). I.e. you should not do variable selection, but rather model averaging (or something that could get you some zero coefficients, but reflects the whole modelling process, such as LASSO or elastic net). Bayesian model choice is more typically framed as Bayesian model averaging. You have different models, each with a different prior probability. If the posterior model probability for a model becomes low enough, you are essentially entirely discarding the model. For equal prior weights for each model and flat priors, model averaging with weights proportional to $\exp(-\text{BIC}/2)$ for each model approximates this. You can alternatively express the model averaging as a prior that is a mixture between a point mass (the weight of the point mass is the prior probability of the effect being exactly zero = the effect is not in the model) and a continuous distribution (e.g. spike-and-slab priors). MCMC sampling can be quite difficult for such a prior. Carvalho et al. motivate the horseshoe shrinkage prior by suggesting that it works like a continuous approximation to a spike-and-slab prior. It is also a case of embedding the problem in a hierarchical model, where to some extent the size and presence of effects on some variables relax the required evidence for others a bit (through the global shrinkage parameter, this is a bit like false-discovery rate control) and on the other hand allow individual effects to stand on their own if the evidence is clear enough. There is a convenient implementation of it available from the brms R package that builds on Stan/rstan. There are a number of further similar priors such as the horseshoe+ prior and the whole topic is an area of ongoing research.
Bayesian model selection and credible interval It is well known that building a model based on what is significant (or some other criterion such as AIC, whether a credible interval contains 0 etc.) is pretty problematic, particularly if you then d
25,762
Bayesian model selection and credible interval
There are a number of formal methods for Bayesian variable selection. A slightly outdated review of Bayesian variable selection methods is presented in: A review of Bayesian variable selection methods: what, how and which A more recent review, which also includes a comparison of different methods and the performance of R packages where they are implemented is: Methods and Tools for Bayesian Variable Selection and Model Averaging in Univariate Linear Regression This reference is particularly useful in that it points you to specific R packages where you just need to plug in the response and the covariate values (and in some cases the hyperparameter values) in order to run the variable selection. Another, quick and dirty and non-recommended, way of conducting "Bayesian" variable selection is to use stepwise selection (forward, backward, both) using BIC and the R command stepAIC(), which can be tweaked to perform selection in terms of BIC. https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/stepAIC.html Another quick and dirty way of testing $\beta_4=0$ is by using the Savage-Dickey density ratio and the posterior simulation you already got: https://arxiv.org/pdf/0910.1452.pdf
Bayesian model selection and credible interval
There are a number of formal methods for Bayesian variable selection. A slightly outdated review of Bayesian variable selection methods is presented in: A review of Bayesian variable selection methods
Bayesian model selection and credible interval There are a number of formal methods for Bayesian variable selection. A slightly outdated review of Bayesian variable selection methods is presented in: A review of Bayesian variable selection methods: what, how and which A more recent review, which also includes a comparison of different methods and the performance of R packages where they are implemented is: Methods and Tools for Bayesian Variable Selection and Model Averaging in Univariate Linear Regression This reference is particularly useful in that it points you to specific R packages where you just need to plug in the response and the covariate values (and in some cases the hyperparameter values) in order to run the variable selection. Another, quick and dirty and non-recommended, way of conducting "Bayesian" variable selection is to use stepwise selection (forward, backward, both) using BIC and the R command stepAIC(), which can be tweaked to perform selection in terms of BIC. https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/stepAIC.html Another quick and dirty way of testing $\beta_4=0$ is by using the Savage-Dickey density ratio and the posterior simulation you already got: https://arxiv.org/pdf/0910.1452.pdf
Bayesian model selection and credible interval There are a number of formal methods for Bayesian variable selection. A slightly outdated review of Bayesian variable selection methods is presented in: A review of Bayesian variable selection methods
25,763
Bayesian model selection and credible interval
The whole idea of Bayesian statistics is different from a frequentist approach. In this way I think to use the terms of significance is not accurate. I guess it is up to the reader to decide if the results (distribution) you get from your model for your $β$ 's are for him reliable or trustful. It always depends on the distribution itself. How skewed and wide is it and how much of the area is below zero? You can also find a nice lecture about the topic here at 41:55 : https://vimeo.com/14553953
Bayesian model selection and credible interval
The whole idea of Bayesian statistics is different from a frequentist approach. In this way I think to use the terms of significance is not accurate. I guess it is up to the reader to decide if the re
Bayesian model selection and credible interval The whole idea of Bayesian statistics is different from a frequentist approach. In this way I think to use the terms of significance is not accurate. I guess it is up to the reader to decide if the results (distribution) you get from your model for your $β$ 's are for him reliable or trustful. It always depends on the distribution itself. How skewed and wide is it and how much of the area is below zero? You can also find a nice lecture about the topic here at 41:55 : https://vimeo.com/14553953
Bayesian model selection and credible interval The whole idea of Bayesian statistics is different from a frequentist approach. In this way I think to use the terms of significance is not accurate. I guess it is up to the reader to decide if the re
25,764
Gaussian process and Correlation
Choosing a kernel is equivalent to choosing a class of functions from which you will choose your model. If choosing a kernel feels like a big thing that encodes a lot of assumptions, that's because it is! People new to the field often don't think much about the choice of kernel and just go with the Gaussian kernel even if it's not appropriate. How do we decide whether or not a kernel seems appropriate? We need to think about what the functions in the corresponding function space look like. The Gaussian kernel corresponds to very smooth functions, and when that kernel is chosen the assumption is being made that smooth functions will provide a decent model. That's not always the case, and there are tons of other kernels that encode different assumptions about what you want your function class to look like. There are kernels for modeling periodic functions, non-stationary kernels, and a whole host of other things. For example, the smoothness assumption encoded by the Gaussian kernel is not appropriate for text classification, as shown by Charles Martin in his blog here. Let's look at examples of functions from spaces corresponding to two different kernels. The first will be the Gaussian kernel $k_1(x, x') = \exp(-\gamma |x - x'|^2)$ and the other will be the Brownian motion kernel $k_2(x, x') = \min \{x, x'\}$. A single random draw from each space looks like the following: Clearly these represent very different assumptions about what a good model is. Also, note that we aren't necessarily forcing correlation. Take your mean function to be $\mu(x) = x^T \beta$ and your covariance function to be $k(x_i, x_j) = \sigma^2 \mathbf 1(i = j)$. Now our model is $$ Y | X \sim \mathcal N(X\beta, \sigma^2 I) $$ i.e. we've just recovered linear regression. But in general this correlation between nearby points is an extremely useful and powerful model. Imagine that you own a oil drilling company and you want to find new oil reserves. It's extremely expensive to drill so you want to drill as few times as possible. Let's say we've drilled $n=5$ holes and we want to know where our next hole should be. We can imagine that the amount of oil in the earth's crust is smoothly varying, so we will model the amount of oil in the entire area that we're considering drilling in with a Gaussian process using the Gaussian kernel, which is how we're saying that really close places will have really similar amounts of oil, and really far apart places are effectively independent. The Gaussian kernel is also stationary, which is reasonable in this case: stationarity says that the correlation between two points only depends on the distance between them. We can then use our model to predict where we should next drill. We've just done a single step in a Bayesian optimization, and I find this to be a very good way to intuitively appreciate why we like the correlation aspect of GPs. Another good resource is Jones et al. (1998). They don't call their model a Gaussian process, but it is. This paper gives a very good feel for why we want to use the correlation between nearby points even in a deterministic setting. One final point: I don't think anyone ever assumes that we can get good prediction results. That's something we'd want to verify, such as by cross validation. Update I want to clarify the nature of the correlation that we're modeling. First let's consider linear regression so $Y | X \sim \mathcal N(X\beta, \sigma^2 I)$. Under this model we have $Y_i \perp Y_j | X$ for $i \neq j$. But we also know that if $||x_1 - x_2||^2 < \varepsilon$ then $$(E(Y_1 | X) - E(Y_2 | X))^2 = (x_1^T \beta - x_2^T \beta)^2 = \langle x_1 - x_2, \beta \rangle^2 \leq || x_1 - x_2||^2 ||\beta ||^2 < \varepsilon ||\beta ||^2. $$ So this tells us that if inputs $x_1$ and $x_2$ are very close then the means of $Y_1$ and $Y_2$ are very close. This is different from being correlated because they're still independent, as evidenced by how $$P(Y_1 > E(Y_1 | X) \ \vert \ Y_2 > E(Y_2 | X)) = P(Y_1 > E(Y_1 | X)).$$ If they were correlated then knowing that $Y_2$ is above its mean would tell us something about $Y_1$. So now let's keep $\mu(x) = x^T \beta$ but we'll add correlation by $Cov(Y_i, Y_j) = k(x_i, x_j)$. We still have the same result that $||x_1 - x_2||^2 < \varepsilon \implies (E(Y_1 | X) - E(Y_2 | X))^2$ is small, but now we've gained the fact that if $Y_1$ is larger than its mean, say, then likely $Y_2$ will be too. This is the correlation that we've added.
Gaussian process and Correlation
Choosing a kernel is equivalent to choosing a class of functions from which you will choose your model. If choosing a kernel feels like a big thing that encodes a lot of assumptions, that's because it
Gaussian process and Correlation Choosing a kernel is equivalent to choosing a class of functions from which you will choose your model. If choosing a kernel feels like a big thing that encodes a lot of assumptions, that's because it is! People new to the field often don't think much about the choice of kernel and just go with the Gaussian kernel even if it's not appropriate. How do we decide whether or not a kernel seems appropriate? We need to think about what the functions in the corresponding function space look like. The Gaussian kernel corresponds to very smooth functions, and when that kernel is chosen the assumption is being made that smooth functions will provide a decent model. That's not always the case, and there are tons of other kernels that encode different assumptions about what you want your function class to look like. There are kernels for modeling periodic functions, non-stationary kernels, and a whole host of other things. For example, the smoothness assumption encoded by the Gaussian kernel is not appropriate for text classification, as shown by Charles Martin in his blog here. Let's look at examples of functions from spaces corresponding to two different kernels. The first will be the Gaussian kernel $k_1(x, x') = \exp(-\gamma |x - x'|^2)$ and the other will be the Brownian motion kernel $k_2(x, x') = \min \{x, x'\}$. A single random draw from each space looks like the following: Clearly these represent very different assumptions about what a good model is. Also, note that we aren't necessarily forcing correlation. Take your mean function to be $\mu(x) = x^T \beta$ and your covariance function to be $k(x_i, x_j) = \sigma^2 \mathbf 1(i = j)$. Now our model is $$ Y | X \sim \mathcal N(X\beta, \sigma^2 I) $$ i.e. we've just recovered linear regression. But in general this correlation between nearby points is an extremely useful and powerful model. Imagine that you own a oil drilling company and you want to find new oil reserves. It's extremely expensive to drill so you want to drill as few times as possible. Let's say we've drilled $n=5$ holes and we want to know where our next hole should be. We can imagine that the amount of oil in the earth's crust is smoothly varying, so we will model the amount of oil in the entire area that we're considering drilling in with a Gaussian process using the Gaussian kernel, which is how we're saying that really close places will have really similar amounts of oil, and really far apart places are effectively independent. The Gaussian kernel is also stationary, which is reasonable in this case: stationarity says that the correlation between two points only depends on the distance between them. We can then use our model to predict where we should next drill. We've just done a single step in a Bayesian optimization, and I find this to be a very good way to intuitively appreciate why we like the correlation aspect of GPs. Another good resource is Jones et al. (1998). They don't call their model a Gaussian process, but it is. This paper gives a very good feel for why we want to use the correlation between nearby points even in a deterministic setting. One final point: I don't think anyone ever assumes that we can get good prediction results. That's something we'd want to verify, such as by cross validation. Update I want to clarify the nature of the correlation that we're modeling. First let's consider linear regression so $Y | X \sim \mathcal N(X\beta, \sigma^2 I)$. Under this model we have $Y_i \perp Y_j | X$ for $i \neq j$. But we also know that if $||x_1 - x_2||^2 < \varepsilon$ then $$(E(Y_1 | X) - E(Y_2 | X))^2 = (x_1^T \beta - x_2^T \beta)^2 = \langle x_1 - x_2, \beta \rangle^2 \leq || x_1 - x_2||^2 ||\beta ||^2 < \varepsilon ||\beta ||^2. $$ So this tells us that if inputs $x_1$ and $x_2$ are very close then the means of $Y_1$ and $Y_2$ are very close. This is different from being correlated because they're still independent, as evidenced by how $$P(Y_1 > E(Y_1 | X) \ \vert \ Y_2 > E(Y_2 | X)) = P(Y_1 > E(Y_1 | X)).$$ If they were correlated then knowing that $Y_2$ is above its mean would tell us something about $Y_1$. So now let's keep $\mu(x) = x^T \beta$ but we'll add correlation by $Cov(Y_i, Y_j) = k(x_i, x_j)$. We still have the same result that $||x_1 - x_2||^2 < \varepsilon \implies (E(Y_1 | X) - E(Y_2 | X))^2$ is small, but now we've gained the fact that if $Y_1$ is larger than its mean, say, then likely $Y_2$ will be too. This is the correlation that we've added.
Gaussian process and Correlation Choosing a kernel is equivalent to choosing a class of functions from which you will choose your model. If choosing a kernel feels like a big thing that encodes a lot of assumptions, that's because it
25,765
Gaussian process and Correlation
If $x_i$ and $x_l$ are similar to each other, i.e. $k(x_i, x_l)$ is large, then $y_i$ and $y_l$ should likely be similar to each other as well. Therefore, closeness in the input space (of the function to be approximated) results in the closeness in the output space. This is reasonable assumptions for many applications. For example, if two students have similar high school GPA, they are expected to perform similarly in the SAT exam as well.
Gaussian process and Correlation
If $x_i$ and $x_l$ are similar to each other, i.e. $k(x_i, x_l)$ is large, then $y_i$ and $y_l$ should likely be similar to each other as well. Therefore, closeness in the input space (of the functio
Gaussian process and Correlation If $x_i$ and $x_l$ are similar to each other, i.e. $k(x_i, x_l)$ is large, then $y_i$ and $y_l$ should likely be similar to each other as well. Therefore, closeness in the input space (of the function to be approximated) results in the closeness in the output space. This is reasonable assumptions for many applications. For example, if two students have similar high school GPA, they are expected to perform similarly in the SAT exam as well.
Gaussian process and Correlation If $x_i$ and $x_l$ are similar to each other, i.e. $k(x_i, x_l)$ is large, then $y_i$ and $y_l$ should likely be similar to each other as well. Therefore, closeness in the input space (of the functio
25,766
Policy Improvement Theorem
They never quite spell it out, but an expression like: \begin{align} E_{\pi'}[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t=s] \end{align} means "the expected discounted value when starting in state $s$, choosing actions according to $\pi'$ for the next time step, and according to $\pi$ thereafter", while: \begin{align} E_{\pi'}[R_{t+1} + \gamma R_{t+2} + \gamma^2 v_\pi(S_{t+2}) | S_t=s] \end{align} means "the expected discounted value when starting in state $s$, choosing actions according to $\pi'$ for the next TWO timesteps, and according to $\pi$ thereafter", etc. So we really have: \begin{align} E_{\pi'}[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t=s] = E[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t=s, A_t=\pi'(s)] \end{align} and if we look up to the beginning of section 4.2 on Policy Improvement, we can see that this is equal to $q(s, \pi'(s))$. The reason that they have these two different expressions for $q(s, \pi(s))$ is that the first is needed because to complete the proof they need to be able to talk about following $\pi'$ for increasingly longer spans of time, and the second is simply the definition of a Q-function for a deterministic policy.
Policy Improvement Theorem
They never quite spell it out, but an expression like: \begin{align} E_{\pi'}[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t=s] \end{align} means "the expected discounted value when starting in state $s$, choo
Policy Improvement Theorem They never quite spell it out, but an expression like: \begin{align} E_{\pi'}[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t=s] \end{align} means "the expected discounted value when starting in state $s$, choosing actions according to $\pi'$ for the next time step, and according to $\pi$ thereafter", while: \begin{align} E_{\pi'}[R_{t+1} + \gamma R_{t+2} + \gamma^2 v_\pi(S_{t+2}) | S_t=s] \end{align} means "the expected discounted value when starting in state $s$, choosing actions according to $\pi'$ for the next TWO timesteps, and according to $\pi$ thereafter", etc. So we really have: \begin{align} E_{\pi'}[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t=s] = E[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t=s, A_t=\pi'(s)] \end{align} and if we look up to the beginning of section 4.2 on Policy Improvement, we can see that this is equal to $q(s, \pi'(s))$. The reason that they have these two different expressions for $q(s, \pi(s))$ is that the first is needed because to complete the proof they need to be able to talk about following $\pi'$ for increasingly longer spans of time, and the second is simply the definition of a Q-function for a deterministic policy.
Policy Improvement Theorem They never quite spell it out, but an expression like: \begin{align} E_{\pi'}[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t=s] \end{align} means "the expected discounted value when starting in state $s$, choo
25,767
Interpreting output from cross correlation function in R
To answer your question, here is an example: set.seed(123) x = arima.sim(model=list(0.2, 0, 0.5), n = 100) y = arima.sim(model=list(0.4, 0, 0.4), n = 100) ccf(x, y, type="correlation") There are two time series, x and y. The correlation between the two occurs at $y_t$ and $x_{t \pm k}$ where $\pm k$ is a lag. In this example, at $k$ = -2, -7, -10, $x_{t + k}$ is significantly $negatively$ correlated with $y_t$. The interpretation can be that x leads y at lags 2, 7 and 10. This is random data so the leads are meaningless. Here are a few useful references for interpretation (my TS knowledge is a bit rusty): http://homepage.univie.ac.at/robert.kunst/prognos4.pdf https://onlinecourses.science.psu.edu/stat510/node/74 To add more detail regarding your situation, it appears that your y_t lags x_{t+k}. The sinusoidal pattern you see in the CCF/ACF is typical for certain time series structures. How familiar are you with AR and MA models? Regarding your hypothesis, it's unclear what data you have, and what the nature of that data may be, but if your time series have a nonstationary pattern, that will result odd ACF/PACF/CCF plots.
Interpreting output from cross correlation function in R
To answer your question, here is an example: set.seed(123) x = arima.sim(model=list(0.2, 0, 0.5), n = 100) y = arima.sim(model=list(0.4, 0, 0.4), n = 100) ccf(x, y, type="correlation") There are two
Interpreting output from cross correlation function in R To answer your question, here is an example: set.seed(123) x = arima.sim(model=list(0.2, 0, 0.5), n = 100) y = arima.sim(model=list(0.4, 0, 0.4), n = 100) ccf(x, y, type="correlation") There are two time series, x and y. The correlation between the two occurs at $y_t$ and $x_{t \pm k}$ where $\pm k$ is a lag. In this example, at $k$ = -2, -7, -10, $x_{t + k}$ is significantly $negatively$ correlated with $y_t$. The interpretation can be that x leads y at lags 2, 7 and 10. This is random data so the leads are meaningless. Here are a few useful references for interpretation (my TS knowledge is a bit rusty): http://homepage.univie.ac.at/robert.kunst/prognos4.pdf https://onlinecourses.science.psu.edu/stat510/node/74 To add more detail regarding your situation, it appears that your y_t lags x_{t+k}. The sinusoidal pattern you see in the CCF/ACF is typical for certain time series structures. How familiar are you with AR and MA models? Regarding your hypothesis, it's unclear what data you have, and what the nature of that data may be, but if your time series have a nonstationary pattern, that will result odd ACF/PACF/CCF plots.
Interpreting output from cross correlation function in R To answer your question, here is an example: set.seed(123) x = arima.sim(model=list(0.2, 0, 0.5), n = 100) y = arima.sim(model=list(0.4, 0, 0.4), n = 100) ccf(x, y, type="correlation") There are two
25,768
Interpreting output from cross correlation function in R
I checked the ccf function with a small example from Box and Jenkins (1976, p 374-375). x <- as.ts(c(11,7,8,12,14)) y <-as.ts(c(7,10,6,7,10)) zz <- ccf(x,y, lag.max=3) zz which gives: Autocorrelations of series ‘X’, by lag -3 -2 -1 0 1 2 3 -0.343 -0.121 0.631 0.139 -0.380 -0.074 0.260 So, we can see that ccf gives as positive lags the calculations of the Box-Jenkins book for negative lags and vice-versa. From the book, we have -0.38 at lag -1 and 0.63 at lag 1. However, the ccf function is correct from what it is said: The lag k value returned by ccf(x, y) estimates the correlation between x[t+k] and y[t]. It is only a matter of definition, but it can be... misleading.
Interpreting output from cross correlation function in R
I checked the ccf function with a small example from Box and Jenkins (1976, p 374-375). x <- as.ts(c(11,7,8,12,14)) y <-as.ts(c(7,10,6,7,10)) zz <- ccf(x,y, lag.max=3) zz which gives: Autocorrelation
Interpreting output from cross correlation function in R I checked the ccf function with a small example from Box and Jenkins (1976, p 374-375). x <- as.ts(c(11,7,8,12,14)) y <-as.ts(c(7,10,6,7,10)) zz <- ccf(x,y, lag.max=3) zz which gives: Autocorrelations of series ‘X’, by lag -3 -2 -1 0 1 2 3 -0.343 -0.121 0.631 0.139 -0.380 -0.074 0.260 So, we can see that ccf gives as positive lags the calculations of the Box-Jenkins book for negative lags and vice-versa. From the book, we have -0.38 at lag -1 and 0.63 at lag 1. However, the ccf function is correct from what it is said: The lag k value returned by ccf(x, y) estimates the correlation between x[t+k] and y[t]. It is only a matter of definition, but it can be... misleading.
Interpreting output from cross correlation function in R I checked the ccf function with a small example from Box and Jenkins (1976, p 374-375). x <- as.ts(c(11,7,8,12,14)) y <-as.ts(c(7,10,6,7,10)) zz <- ccf(x,y, lag.max=3) zz which gives: Autocorrelation
25,769
Conditional Distribution of uniform random variable given Order statistic
A picture might help. Independent uniform distributions on the interval $[0,1]$ may be considered a uniform distribution on the unit square $I^2 = [0,1]\times [0,1]$. Events are regions in the square and their probabilities are their areas. Let $z$ be any possible value of $\max(U,V)$. The set of coordinates $(U,V)$ where $\max(U,V)=z$ forms the top and right edges of a square of side $z$. Let $dz$ be a small positive number. The set of coordinates $(U,V)$ whose maximum lies between $z$ and $z+dz$ forms a narrow thickening of that square, as shaded in the figure. Its area is the difference of the areas of two squares, one of side $z+dz$ and the other of side $z$, whence $$\Pr(z \le Z \le z+dz) = (z+dz)^2 - z^2 = 2z\,dz + (dz)^2.\tag{1}$$ Let $u$ be any possible value of $U$: it is marked with a vertical dashed line in the figures. The left panel shows a case where $u \le z$: The chance that $U\le u$ would be the area to the left of that line (equal to $u$); but the event that $U\le u$ and $Z$ lies between $z$ and $z+dz$ is just the brown shaded area. It's a rectangle, so its area is its width $u$ times its height $dz$. Thus, $$\Pr(U \le u, z \le Z \le z+dz) = u\,dz.\tag{2}$$ The right panel shows a case where $z \lt u \le z+dz$. Now the chance that $U \le u$ and $z \lt Z \le z+dz$ consists of two rectangles. The top one has base $u$ and height $dz$; the right one has base $(u-z)$ and height $z$. Therefore $$\Pr(U \le u, z \le Z \le z+dz) = u\, dz + (u-z)z.\tag{3}$$ By definition, the conditional probabilities are these chances divided by the total chance that $z \le Z \le z+dz$, given in $(1)$ above. Divide $(2)$ and $(3)$ by this value. Letting $dz$ be infinitesimal, and retaining the standard part of the result, gives the chances conditional on $Z=z$. Thus, when $0 \le u \le z$, $$\Pr(U \le u\,|\, Z=z) = \frac{u\,dz}{2z\,dz + (dz)^2} = \frac{u}{2z + dz} \approx \frac{u}{2z}.$$ When $z \lt u \le z+dz$, write $u = z + \lambda dz$ for $0 \lt \lambda \le 1$ and compute $$\Pr(U \le u|Z=z) = \frac{u\, dz + (u-z)z}{2z\,dz + (dz)^2} = \frac{(z + \lambda dz)dz + (\lambda dz)z}{2z\,dz+(dz)^2}\approx\frac{1+\lambda}{2}.$$ Finally, for $u \gt z+dz$, the brown area in the right panel has grown to equal the gray area, whence their ratio is $1$. These results show that the conditional probability grows linearly from $0$ to $z/(2z)=1/2$ as $u$ grows from $0$ to $z$, then shoots up linearly from $1/2$ to $1$ in the infinitesimal interval between $z$ and $z+dz$, then stays at $1$ for all larger $u$. Here's a graph: Because $dz$ is infinitesimal, it is no longer possible to distinguish $z$ from $z+dz$ visually: the plot jumps from a height of $1/2$ to $1$. Putting the foregoing together into a single formula to be applied to any $z$ for which $0 \lt z \le 1$, we could write the conditional distribution function as $$F_{U|Z=z}(u) = \left\{\begin{array}{ll} 0 & u \le 0 \\ \frac{u}{2z} & 0 \lt u\le z \\ 1 & u \gt z. \end{array} \right.$$ This is a complete and rigorous answer. The jump shows that a probability density function will not adequately describe the conditional distribution at the value $U=z$. At all other points, though, there is a density $f_{U|Z=z}(u)$. It is equal to $0$ for $u\le 0$, $1/(2z)$ for $0 \le u \lt z$ (the derivative of $u/(2z)$ with respect to $u$), and $0$ for $u \gt z$. You could use a "generalized function" to write this in a density-like form. Let $\delta_z$ be the "generalized density" giving a jump of magnitude $1$ at $z$: that is, it's the "density" of an atom of unit probability located at $z$. Then the generalized density at $z$ can be written $\frac{1}{2}\delta_z$ to express the fact that a probability of $1/2$ is concentrated at $z$. In full, we could write $$f_{U|Z=z}(u) = \left\{\begin{array}{ll} 0 & u \le 0 \\ \frac{1}{2z} & 0 \lt u\lt z \\ \frac{1}{2}\delta_z(u) & u=z \\ 0 & u \gt z. \end{array} \right.$$
Conditional Distribution of uniform random variable given Order statistic
A picture might help. Independent uniform distributions on the interval $[0,1]$ may be considered a uniform distribution on the unit square $I^2 = [0,1]\times [0,1]$. Events are regions in the square
Conditional Distribution of uniform random variable given Order statistic A picture might help. Independent uniform distributions on the interval $[0,1]$ may be considered a uniform distribution on the unit square $I^2 = [0,1]\times [0,1]$. Events are regions in the square and their probabilities are their areas. Let $z$ be any possible value of $\max(U,V)$. The set of coordinates $(U,V)$ where $\max(U,V)=z$ forms the top and right edges of a square of side $z$. Let $dz$ be a small positive number. The set of coordinates $(U,V)$ whose maximum lies between $z$ and $z+dz$ forms a narrow thickening of that square, as shaded in the figure. Its area is the difference of the areas of two squares, one of side $z+dz$ and the other of side $z$, whence $$\Pr(z \le Z \le z+dz) = (z+dz)^2 - z^2 = 2z\,dz + (dz)^2.\tag{1}$$ Let $u$ be any possible value of $U$: it is marked with a vertical dashed line in the figures. The left panel shows a case where $u \le z$: The chance that $U\le u$ would be the area to the left of that line (equal to $u$); but the event that $U\le u$ and $Z$ lies between $z$ and $z+dz$ is just the brown shaded area. It's a rectangle, so its area is its width $u$ times its height $dz$. Thus, $$\Pr(U \le u, z \le Z \le z+dz) = u\,dz.\tag{2}$$ The right panel shows a case where $z \lt u \le z+dz$. Now the chance that $U \le u$ and $z \lt Z \le z+dz$ consists of two rectangles. The top one has base $u$ and height $dz$; the right one has base $(u-z)$ and height $z$. Therefore $$\Pr(U \le u, z \le Z \le z+dz) = u\, dz + (u-z)z.\tag{3}$$ By definition, the conditional probabilities are these chances divided by the total chance that $z \le Z \le z+dz$, given in $(1)$ above. Divide $(2)$ and $(3)$ by this value. Letting $dz$ be infinitesimal, and retaining the standard part of the result, gives the chances conditional on $Z=z$. Thus, when $0 \le u \le z$, $$\Pr(U \le u\,|\, Z=z) = \frac{u\,dz}{2z\,dz + (dz)^2} = \frac{u}{2z + dz} \approx \frac{u}{2z}.$$ When $z \lt u \le z+dz$, write $u = z + \lambda dz$ for $0 \lt \lambda \le 1$ and compute $$\Pr(U \le u|Z=z) = \frac{u\, dz + (u-z)z}{2z\,dz + (dz)^2} = \frac{(z + \lambda dz)dz + (\lambda dz)z}{2z\,dz+(dz)^2}\approx\frac{1+\lambda}{2}.$$ Finally, for $u \gt z+dz$, the brown area in the right panel has grown to equal the gray area, whence their ratio is $1$. These results show that the conditional probability grows linearly from $0$ to $z/(2z)=1/2$ as $u$ grows from $0$ to $z$, then shoots up linearly from $1/2$ to $1$ in the infinitesimal interval between $z$ and $z+dz$, then stays at $1$ for all larger $u$. Here's a graph: Because $dz$ is infinitesimal, it is no longer possible to distinguish $z$ from $z+dz$ visually: the plot jumps from a height of $1/2$ to $1$. Putting the foregoing together into a single formula to be applied to any $z$ for which $0 \lt z \le 1$, we could write the conditional distribution function as $$F_{U|Z=z}(u) = \left\{\begin{array}{ll} 0 & u \le 0 \\ \frac{u}{2z} & 0 \lt u\le z \\ 1 & u \gt z. \end{array} \right.$$ This is a complete and rigorous answer. The jump shows that a probability density function will not adequately describe the conditional distribution at the value $U=z$. At all other points, though, there is a density $f_{U|Z=z}(u)$. It is equal to $0$ for $u\le 0$, $1/(2z)$ for $0 \le u \lt z$ (the derivative of $u/(2z)$ with respect to $u$), and $0$ for $u \gt z$. You could use a "generalized function" to write this in a density-like form. Let $\delta_z$ be the "generalized density" giving a jump of magnitude $1$ at $z$: that is, it's the "density" of an atom of unit probability located at $z$. Then the generalized density at $z$ can be written $\frac{1}{2}\delta_z$ to express the fact that a probability of $1/2$ is concentrated at $z$. In full, we could write $$f_{U|Z=z}(u) = \left\{\begin{array}{ll} 0 & u \le 0 \\ \frac{1}{2z} & 0 \lt u\lt z \\ \frac{1}{2}\delta_z(u) & u=z \\ 0 & u \gt z. \end{array} \right.$$
Conditional Distribution of uniform random variable given Order statistic A picture might help. Independent uniform distributions on the interval $[0,1]$ may be considered a uniform distribution on the unit square $I^2 = [0,1]\times [0,1]$. Events are regions in the square
25,770
Conditional Distribution of uniform random variable given Order statistic
First consider the distribution of the maximum $Z$ conditional on $U=u$. The maximum $Z$ becomes equal to $u$ in the event that $V<u$ with conditional probability $u$. Otherwise, $Z$ takes some value greater than $u$ equal to $V$. The overall conditional distribution will thus be a mixture between a point mass at $u$ (of size u) and a uniform density on $(u,1)$ (integrating to $1-u$). Representing the point mass by the Dirac delta function, the generalised probability density function (gpdf) of this conditional distribution is $$ f_{Z|U=u}(z) = u\delta(z-u) + \begin{cases} 1 & \text{for }u<z<1 \\ 0 &\text{otherwise}. \end{cases} $$ The joint gpdf of $Z$ and $U$ is then \begin{align} f_{Z,U}(z,u) &= f_{Z|U=u}(z)f_U(u) \\ &= u\delta(z-u) + \begin{cases} 1 & \text{for }0<u<z<1 \\ 0 &\text{otherwise}. \end{cases} \end{align} The pdf of the maximum is $f_Z(z)=2z$. Hence, the conditional gpdf of $U$ given the maximum $Z$ becomes \begin{align} f_{U|Z=z}(u) &= \frac{f_{Z,U}(z,u)}{f_Z(z)} \\ &= \frac12\delta(z-u) + \begin{cases} \frac1{2z} & \text{for }0<u<z \\ 0 &\text{otherwise}, \end{cases} \end{align} a mixture between a point mass at $z$ with probability 1/2 and a uniform density on $(0,z)$ integrating to 1/2.
Conditional Distribution of uniform random variable given Order statistic
First consider the distribution of the maximum $Z$ conditional on $U=u$. The maximum $Z$ becomes equal to $u$ in the event that $V<u$ with conditional probability $u$. Otherwise, $Z$ takes some valu
Conditional Distribution of uniform random variable given Order statistic First consider the distribution of the maximum $Z$ conditional on $U=u$. The maximum $Z$ becomes equal to $u$ in the event that $V<u$ with conditional probability $u$. Otherwise, $Z$ takes some value greater than $u$ equal to $V$. The overall conditional distribution will thus be a mixture between a point mass at $u$ (of size u) and a uniform density on $(u,1)$ (integrating to $1-u$). Representing the point mass by the Dirac delta function, the generalised probability density function (gpdf) of this conditional distribution is $$ f_{Z|U=u}(z) = u\delta(z-u) + \begin{cases} 1 & \text{for }u<z<1 \\ 0 &\text{otherwise}. \end{cases} $$ The joint gpdf of $Z$ and $U$ is then \begin{align} f_{Z,U}(z,u) &= f_{Z|U=u}(z)f_U(u) \\ &= u\delta(z-u) + \begin{cases} 1 & \text{for }0<u<z<1 \\ 0 &\text{otherwise}. \end{cases} \end{align} The pdf of the maximum is $f_Z(z)=2z$. Hence, the conditional gpdf of $U$ given the maximum $Z$ becomes \begin{align} f_{U|Z=z}(u) &= \frac{f_{Z,U}(z,u)}{f_Z(z)} \\ &= \frac12\delta(z-u) + \begin{cases} \frac1{2z} & \text{for }0<u<z \\ 0 &\text{otherwise}, \end{cases} \end{align} a mixture between a point mass at $z$ with probability 1/2 and a uniform density on $(0,z)$ integrating to 1/2.
Conditional Distribution of uniform random variable given Order statistic First consider the distribution of the maximum $Z$ conditional on $U=u$. The maximum $Z$ becomes equal to $u$ in the event that $V<u$ with conditional probability $u$. Otherwise, $Z$ takes some valu
25,771
Maximum penalty for ridge regression
The effect of $\lambda$ in the ridge regression estimator is that it "inflates" singular values $s_i$ of $X$ via terms like $(s^2_i+\lambda)/s_i$. Specifically, if SVD of the design matrix is $X=USV^\top$, then $$\hat\beta_\mathrm{ridge} = V^\top \frac{S}{S^2+\lambda I} U y.$$ This is explained multiple times on our website, see e.g. @whuber's detailed exposition here: The proof of shrinking coefficients using ridge regression through "spectral decomposition". This suggests that selecting $\lambda$ much larger than $s_\mathrm{max}^2$ will shrink everything very strongly. I suspect that $$\lambda=\|X\|_2^2=\sum s_i^2$$ will be too big for all practical purposes. I usually normalize my lambdas by the squared Frobenius norm of $X$ and have a cross-validation grid that goes from $0$ to $1$ (on a log scale). Having said that, no value of lambda can be seen as truly "maximum", in contrast to the lasso case. Imagine that predictors are exactly orthogonal to the response, i.e. that the true $\beta=0$. Any finite value of $\lambda<\infty $ for any finite value of sample size $n$ will yield $\hat \beta \ne 0$ and hence could benefit from stronger shrinkage.
Maximum penalty for ridge regression
The effect of $\lambda$ in the ridge regression estimator is that it "inflates" singular values $s_i$ of $X$ via terms like $(s^2_i+\lambda)/s_i$. Specifically, if SVD of the design matrix is $X=USV^
Maximum penalty for ridge regression The effect of $\lambda$ in the ridge regression estimator is that it "inflates" singular values $s_i$ of $X$ via terms like $(s^2_i+\lambda)/s_i$. Specifically, if SVD of the design matrix is $X=USV^\top$, then $$\hat\beta_\mathrm{ridge} = V^\top \frac{S}{S^2+\lambda I} U y.$$ This is explained multiple times on our website, see e.g. @whuber's detailed exposition here: The proof of shrinking coefficients using ridge regression through "spectral decomposition". This suggests that selecting $\lambda$ much larger than $s_\mathrm{max}^2$ will shrink everything very strongly. I suspect that $$\lambda=\|X\|_2^2=\sum s_i^2$$ will be too big for all practical purposes. I usually normalize my lambdas by the squared Frobenius norm of $X$ and have a cross-validation grid that goes from $0$ to $1$ (on a log scale). Having said that, no value of lambda can be seen as truly "maximum", in contrast to the lasso case. Imagine that predictors are exactly orthogonal to the response, i.e. that the true $\beta=0$. Any finite value of $\lambda<\infty $ for any finite value of sample size $n$ will yield $\hat \beta \ne 0$ and hence could benefit from stronger shrinkage.
Maximum penalty for ridge regression The effect of $\lambda$ in the ridge regression estimator is that it "inflates" singular values $s_i$ of $X$ via terms like $(s^2_i+\lambda)/s_i$. Specifically, if SVD of the design matrix is $X=USV^
25,772
Maximum penalty for ridge regression
Maybe not quite answering your question, but instead of using ridge regression with a fixed penalization of your coefficients it would be better to use iterated adaptive ridge regression though, as the latter approximates L0 penalized regression (aka best subset), where the log likelihood of a GLM model is penalized based on a multiple of the number of nonzero coefficients in the model - see Frommlet & Noel 2016. This has the advantage that you don't have to tune the regularization level lambda at all then. Instead, you can then a priori set the regularization level $lambda$ to either $lambda = 2$ if you would like to directly optimize AIC (roughly coinciding with minimizing prediction error) or to $lambda=log(n)$ to optimize BIC (resulting in asymptotically optimal model selection in terms of selection consistency). This is what is done in the l0ara R package. To me this make more sense than first optimizing your coefficients under one objective (e.g. ridge), only to then tune the regularization level of that model based on some other criterion (e.g. minimizing cross validation prediction error, AIC or BIC). The other advantage of L0-penalized regression over ridge regression or LASSO regression is that it gives you unbiased estimates, so you can get rid of the bias-variance tradeoff that plagues most penalized regression approaches. Plus like ridge it also works for high-dimensional problems with $p>n$. If you would like to stick with regular ridge regression, then this presentation gives a good overview of the strategies you can use to tune the ridge penalization factor. Information criteria such as AIC or BIC can also be used to tune regularisation, and they each asymptotically approximate a particular form of cross validation: AIC approximately minimizes the prediction error and is asymptotically equivalent to leave-1-out cross-validation (LOOCV) (Stone 1977); LOOCV in turn is approximated by generalized cross validation (GCV), but LOOCV should always be better than GCV. AIC is not consistent though, which means that even with a very large amount of data ($n$ going to infinity) and if the true model is among the candidate models, the probability of selecting the true model based on the AIC criterion would not approach 1. BIC is an approximation to the integrated marginal likelihood $P(D|M,A) (D=Data, M=model, A=assumptions)$, which under a flat prior is equivalent to seeking the model that maximizes $P(M|D,A)$. Its advantage is that it is consistent, which means that with a very large amount of data ($n$ going to infinity) and if the true model is among the candidate models, the probability of selecting the true model based on the BIC criterion would approach 1. This would come at a slight cost to prediction performance though if $n$ were small. BIC is also equivalent to leave-k-out cross-validation (LKOCV) where $k=n[1−1/(log(n)−1)]$, with $n=$ sample size (Shao 1997). There is many different versions of the BIC though which come down to making different approximations of the marginal likelihood or assuming different priors. E.g. instead of using a prior uniform of all possible models as in the original BIC, EBIC uses a prior uniform of models of fixed size (Chen & Chen 2008) whereas BICq uses a Bernouilli distribution specifying the prior probability for each parameter to be included. Note that the LOOCV error can also be calculated analytically from the residuals and the diagonal of the hat matrix, without having to actually carry out any cross validation. This would always be an alternative to the AIC as an asymptotic approximation of the LOOCV error. References Stone M. (1977) An asymptotic equivalence of choice of model by cross-validation and Akaike’s criterion. Journal of the Royal Statistical Society Series B. 39, 44–7. Shao J. (1997) An asymptotic theory for linear model selection. Statistica Sinica 7, 221-242.
Maximum penalty for ridge regression
Maybe not quite answering your question, but instead of using ridge regression with a fixed penalization of your coefficients it would be better to use iterated adaptive ridge regression though, as th
Maximum penalty for ridge regression Maybe not quite answering your question, but instead of using ridge regression with a fixed penalization of your coefficients it would be better to use iterated adaptive ridge regression though, as the latter approximates L0 penalized regression (aka best subset), where the log likelihood of a GLM model is penalized based on a multiple of the number of nonzero coefficients in the model - see Frommlet & Noel 2016. This has the advantage that you don't have to tune the regularization level lambda at all then. Instead, you can then a priori set the regularization level $lambda$ to either $lambda = 2$ if you would like to directly optimize AIC (roughly coinciding with minimizing prediction error) or to $lambda=log(n)$ to optimize BIC (resulting in asymptotically optimal model selection in terms of selection consistency). This is what is done in the l0ara R package. To me this make more sense than first optimizing your coefficients under one objective (e.g. ridge), only to then tune the regularization level of that model based on some other criterion (e.g. minimizing cross validation prediction error, AIC or BIC). The other advantage of L0-penalized regression over ridge regression or LASSO regression is that it gives you unbiased estimates, so you can get rid of the bias-variance tradeoff that plagues most penalized regression approaches. Plus like ridge it also works for high-dimensional problems with $p>n$. If you would like to stick with regular ridge regression, then this presentation gives a good overview of the strategies you can use to tune the ridge penalization factor. Information criteria such as AIC or BIC can also be used to tune regularisation, and they each asymptotically approximate a particular form of cross validation: AIC approximately minimizes the prediction error and is asymptotically equivalent to leave-1-out cross-validation (LOOCV) (Stone 1977); LOOCV in turn is approximated by generalized cross validation (GCV), but LOOCV should always be better than GCV. AIC is not consistent though, which means that even with a very large amount of data ($n$ going to infinity) and if the true model is among the candidate models, the probability of selecting the true model based on the AIC criterion would not approach 1. BIC is an approximation to the integrated marginal likelihood $P(D|M,A) (D=Data, M=model, A=assumptions)$, which under a flat prior is equivalent to seeking the model that maximizes $P(M|D,A)$. Its advantage is that it is consistent, which means that with a very large amount of data ($n$ going to infinity) and if the true model is among the candidate models, the probability of selecting the true model based on the BIC criterion would approach 1. This would come at a slight cost to prediction performance though if $n$ were small. BIC is also equivalent to leave-k-out cross-validation (LKOCV) where $k=n[1−1/(log(n)−1)]$, with $n=$ sample size (Shao 1997). There is many different versions of the BIC though which come down to making different approximations of the marginal likelihood or assuming different priors. E.g. instead of using a prior uniform of all possible models as in the original BIC, EBIC uses a prior uniform of models of fixed size (Chen & Chen 2008) whereas BICq uses a Bernouilli distribution specifying the prior probability for each parameter to be included. Note that the LOOCV error can also be calculated analytically from the residuals and the diagonal of the hat matrix, without having to actually carry out any cross validation. This would always be an alternative to the AIC as an asymptotic approximation of the LOOCV error. References Stone M. (1977) An asymptotic equivalence of choice of model by cross-validation and Akaike’s criterion. Journal of the Royal Statistical Society Series B. 39, 44–7. Shao J. (1997) An asymptotic theory for linear model selection. Statistica Sinica 7, 221-242.
Maximum penalty for ridge regression Maybe not quite answering your question, but instead of using ridge regression with a fixed penalization of your coefficients it would be better to use iterated adaptive ridge regression though, as th
25,773
Multivariate log-normal probabiltiy density function (PDF)
Just for the sake of completeness, I'll provide an answer here. This is a simple application of the multivariate change of variables theorem: say $Y = \Phi(X)$ where $\Phi$ is a smooth bijective function. Then $$ p_Y(y) = p_X(\Phi^{-1}(y)) \vert \det J_{\Phi^{-1}}(y)\vert $$ where $J_{\Phi^{-1}}$ is the Jacobian matrix of the inverse transformation. So for a multivariate lognormal random variable $Y = \exp(Z)$ where $Z\sim \mathcal{N}(\mu,\Sigma)$, we have $\Phi^{-1}(y) = \ln(y)$ and so $$ J_{\Phi^{-1}}(y) = \text{diag}(1/y_1,\ldots,1/y_n) $$ Hence $$ \vert \det J_{\Phi^{-1}}(y)\vert = \prod_{j=1}^ny_j^{-1} = \frac{1}{y_1y_2\cdots y_n} $$ So, finally we have $$ p_Y(y) = (2\pi)^{-n/2}(\det\Sigma)^{-1/2}\prod_{j=1}^ny_j^{-1}\exp\left(-\frac{1}{2}(\ln(y)-\mu)^t\Sigma^{-1}(\ln(y) - \mu)\right) $$
Multivariate log-normal probabiltiy density function (PDF)
Just for the sake of completeness, I'll provide an answer here. This is a simple application of the multivariate change of variables theorem: say $Y = \Phi(X)$ where $\Phi$ is a smooth bijective func
Multivariate log-normal probabiltiy density function (PDF) Just for the sake of completeness, I'll provide an answer here. This is a simple application of the multivariate change of variables theorem: say $Y = \Phi(X)$ where $\Phi$ is a smooth bijective function. Then $$ p_Y(y) = p_X(\Phi^{-1}(y)) \vert \det J_{\Phi^{-1}}(y)\vert $$ where $J_{\Phi^{-1}}$ is the Jacobian matrix of the inverse transformation. So for a multivariate lognormal random variable $Y = \exp(Z)$ where $Z\sim \mathcal{N}(\mu,\Sigma)$, we have $\Phi^{-1}(y) = \ln(y)$ and so $$ J_{\Phi^{-1}}(y) = \text{diag}(1/y_1,\ldots,1/y_n) $$ Hence $$ \vert \det J_{\Phi^{-1}}(y)\vert = \prod_{j=1}^ny_j^{-1} = \frac{1}{y_1y_2\cdots y_n} $$ So, finally we have $$ p_Y(y) = (2\pi)^{-n/2}(\det\Sigma)^{-1/2}\prod_{j=1}^ny_j^{-1}\exp\left(-\frac{1}{2}(\ln(y)-\mu)^t\Sigma^{-1}(\ln(y) - \mu)\right) $$
Multivariate log-normal probabiltiy density function (PDF) Just for the sake of completeness, I'll provide an answer here. This is a simple application of the multivariate change of variables theorem: say $Y = \Phi(X)$ where $\Phi$ is a smooth bijective func
25,774
Why two 'modes' for a Poisson Distribution with $\lambda$ an integer?
Although the result is easy to verify when one is given a formula for a Poisson distribution, that provides little for the intuition to work with. Instead, what we need is to develop an understanding of this distribution in terms of some probabilistic mechanism that we can see, experiment with, and understand easily: that would be genuinely intuitive. The following answer repeats the original (and standard) development of the Poisson distribution as a limiting value of Binomial distributions, but instead of trying to obtain the probabilities directly (which requires some knowledge of the Gamma function), it focuses on a particularly simple relationship among the various probabilities. The desired result drops out immediately with no calculation at all. Imagine a large number $n$ of bins and a coin with a chance $p$ of falling heads. Flip the coin independently for each bin, "filling" it when the coin falls heads and otherwise leaving it "empty." Suppose $k$ of the bins end up full as shown with the dark shading in the figure, and the remaining $n-k$ are empty. This is the situation depicted at the right (showing $k=4$ full bins). The situation at the left is another possible outcome with only $k-1$ full bins. It was created by choosing one of the $k$ bins at the right. The "$k,1-p$" in the top arrow reminds us of the two chances involved in relating the right to the left: pick one bin out of $k$ (with chance $1/k$ for each such bin) and change the coin's outcome (with chance $1-p$). The bottom arrow shows what changes in moving from the left to the right: one of the $n-(k-1)$ empty bins is chosen and then filled by an outcome having probability $p$. This shows how to relate the chance of filling $k$ bins, which I will write $\pi(k,n,p)$, to the chance of filling $k-1$ bins, $\pi(k-1,n,p)$: $$ \pi(k,n,p)(k)(1-p) = \pi(k-1,n,p)(n-k+1)(p).\tag{1}$$ Suppose now that $n$ becomes arbitrarily large, but as it does, $\lambda = p n$ (the expected proportion of full bins) stays constant. Multiplying both sides by $n/k$ and dividing them by $n-k+1$ preserves the equality $(1)$, enabling us to rewrite it in terms of $\lambda$ with all the dependency on $n$ on one side: $$\pi(k,n,n\lambda)\left(\frac{n-\lambda}{n-k+1}\right) = \pi(k-1,n,n\lambda)\left(\frac{\lambda}{k}\right).\tag{2}$$ For a fixed value of $k$, as $n$ grows the coefficient on the left of $(2)$ becomes uniformly close to $1$. Thus, to an excellent approximation (which is on the order of $1/n$), we may take $$\pi(k,n,n\lambda) \approx \pi(k-1,n,n\lambda)\left(\frac{\lambda}{k}\right)\tag{3}$$ for this particular $k$ (and all smaller values, too). This, of course, recapitulates the construction of the Poisson distribution as a limit of Binomial$(n, \lambda/n)$ distributions. We may now construct the full limiting distribution in terms of the chance of $k=0$ for the Poisson$(\lambda)$ distribution, $$p_\lambda(0) = \lim_{n\to\infty}\pi(0,n,n\lambda).$$ According to $(3)$, this is multiplied by $\lambda/1$ to obtain $p_\lambda(1)$, and that is multiplied by $\lambda/2$ to obtain $p_\lambda(2)$, and so on. Because this works for any finite $k$, it works for all $k$. (The subscript $\lambda$ is dropped in the figure for brevity.) For as long as $k \lt \lambda$, the chances keep increasing. Once $\lambda \gt k$, they decrease. Therefore the Poisson distribution is unimodal. In some special cases, the mode can occur at two adjacent values: this is precisely when $\lambda/k = 1$, for then the two chances $p_\lambda(k-1)$ and $p_\lambda(k)$ are equal. Obviously this happens if and only if $\lambda$ is integral, in which case $k=\lambda$, QED. Note that this is a stronger result than stated in the question, because it demonstrates the converse: when a Poisson distribution's mode occurs at two values, its rate $\lambda$ must be integral. Incidentally, $p_\lambda(0)$--and therefore all the chances--is found by normalizing the sum $$\sum_{k=0}^\infty p_\lambda(k) = p_\lambda(0)\left[1 + \frac{\lambda}{1} + \left(\frac{\lambda}{1}\frac{\lambda}{2}\right) + \cdots + \left(\frac{\lambda}{1}\frac{\lambda}{2}\cdots\frac{\lambda}{k}\right)+\cdots\right]$$ to unity. This sum is easily recognizable as $p_\lambda(0)\exp(\lambda)$, whence finally $p_\lambda(0) = 1/\exp(\lambda) = \exp(-\lambda)$ and therefore $$p_\lambda(k) = \exp(-\lambda)\frac{\lambda^k}{1\cdot 2\cdots (k-1)\cdot k} = \frac{\lambda^k e^{-\lambda}}{k!}$$ for all $k \ge 0$.
Why two 'modes' for a Poisson Distribution with $\lambda$ an integer?
Although the result is easy to verify when one is given a formula for a Poisson distribution, that provides little for the intuition to work with. Instead, what we need is to develop an understanding
Why two 'modes' for a Poisson Distribution with $\lambda$ an integer? Although the result is easy to verify when one is given a formula for a Poisson distribution, that provides little for the intuition to work with. Instead, what we need is to develop an understanding of this distribution in terms of some probabilistic mechanism that we can see, experiment with, and understand easily: that would be genuinely intuitive. The following answer repeats the original (and standard) development of the Poisson distribution as a limiting value of Binomial distributions, but instead of trying to obtain the probabilities directly (which requires some knowledge of the Gamma function), it focuses on a particularly simple relationship among the various probabilities. The desired result drops out immediately with no calculation at all. Imagine a large number $n$ of bins and a coin with a chance $p$ of falling heads. Flip the coin independently for each bin, "filling" it when the coin falls heads and otherwise leaving it "empty." Suppose $k$ of the bins end up full as shown with the dark shading in the figure, and the remaining $n-k$ are empty. This is the situation depicted at the right (showing $k=4$ full bins). The situation at the left is another possible outcome with only $k-1$ full bins. It was created by choosing one of the $k$ bins at the right. The "$k,1-p$" in the top arrow reminds us of the two chances involved in relating the right to the left: pick one bin out of $k$ (with chance $1/k$ for each such bin) and change the coin's outcome (with chance $1-p$). The bottom arrow shows what changes in moving from the left to the right: one of the $n-(k-1)$ empty bins is chosen and then filled by an outcome having probability $p$. This shows how to relate the chance of filling $k$ bins, which I will write $\pi(k,n,p)$, to the chance of filling $k-1$ bins, $\pi(k-1,n,p)$: $$ \pi(k,n,p)(k)(1-p) = \pi(k-1,n,p)(n-k+1)(p).\tag{1}$$ Suppose now that $n$ becomes arbitrarily large, but as it does, $\lambda = p n$ (the expected proportion of full bins) stays constant. Multiplying both sides by $n/k$ and dividing them by $n-k+1$ preserves the equality $(1)$, enabling us to rewrite it in terms of $\lambda$ with all the dependency on $n$ on one side: $$\pi(k,n,n\lambda)\left(\frac{n-\lambda}{n-k+1}\right) = \pi(k-1,n,n\lambda)\left(\frac{\lambda}{k}\right).\tag{2}$$ For a fixed value of $k$, as $n$ grows the coefficient on the left of $(2)$ becomes uniformly close to $1$. Thus, to an excellent approximation (which is on the order of $1/n$), we may take $$\pi(k,n,n\lambda) \approx \pi(k-1,n,n\lambda)\left(\frac{\lambda}{k}\right)\tag{3}$$ for this particular $k$ (and all smaller values, too). This, of course, recapitulates the construction of the Poisson distribution as a limit of Binomial$(n, \lambda/n)$ distributions. We may now construct the full limiting distribution in terms of the chance of $k=0$ for the Poisson$(\lambda)$ distribution, $$p_\lambda(0) = \lim_{n\to\infty}\pi(0,n,n\lambda).$$ According to $(3)$, this is multiplied by $\lambda/1$ to obtain $p_\lambda(1)$, and that is multiplied by $\lambda/2$ to obtain $p_\lambda(2)$, and so on. Because this works for any finite $k$, it works for all $k$. (The subscript $\lambda$ is dropped in the figure for brevity.) For as long as $k \lt \lambda$, the chances keep increasing. Once $\lambda \gt k$, they decrease. Therefore the Poisson distribution is unimodal. In some special cases, the mode can occur at two adjacent values: this is precisely when $\lambda/k = 1$, for then the two chances $p_\lambda(k-1)$ and $p_\lambda(k)$ are equal. Obviously this happens if and only if $\lambda$ is integral, in which case $k=\lambda$, QED. Note that this is a stronger result than stated in the question, because it demonstrates the converse: when a Poisson distribution's mode occurs at two values, its rate $\lambda$ must be integral. Incidentally, $p_\lambda(0)$--and therefore all the chances--is found by normalizing the sum $$\sum_{k=0}^\infty p_\lambda(k) = p_\lambda(0)\left[1 + \frac{\lambda}{1} + \left(\frac{\lambda}{1}\frac{\lambda}{2}\right) + \cdots + \left(\frac{\lambda}{1}\frac{\lambda}{2}\cdots\frac{\lambda}{k}\right)+\cdots\right]$$ to unity. This sum is easily recognizable as $p_\lambda(0)\exp(\lambda)$, whence finally $p_\lambda(0) = 1/\exp(\lambda) = \exp(-\lambda)$ and therefore $$p_\lambda(k) = \exp(-\lambda)\frac{\lambda^k}{1\cdot 2\cdots (k-1)\cdot k} = \frac{\lambda^k e^{-\lambda}}{k!}$$ for all $k \ge 0$.
Why two 'modes' for a Poisson Distribution with $\lambda$ an integer? Although the result is easy to verify when one is given a formula for a Poisson distribution, that provides little for the intuition to work with. Instead, what we need is to develop an understanding
25,775
Why two 'modes' for a Poisson Distribution with $\lambda$ an integer?
Recall the density function for a Poisson RV is $e^{-\lambda}\lambda^x / x!$, you plugged $\lambda$ and $\lambda-1$ in for $x$. It is simple arithmetic to show it's true and that's enough intuition for me. The intuition is that Poisson RVs, for $\lambda \ge 1$, have convex density. If one allowed $x$ to take non-integral values, the curve would show a mode at $\lambda-0.5$. Proving this is easy, but it's simple to connect this with the idea that once $x$ is "forced" to take integral values, there are two modes interpolating this values. curve(exp(4)*4^x/gamma(x+1), from=0, to=10) abline(v=3.5)
Why two 'modes' for a Poisson Distribution with $\lambda$ an integer?
Recall the density function for a Poisson RV is $e^{-\lambda}\lambda^x / x!$, you plugged $\lambda$ and $\lambda-1$ in for $x$. It is simple arithmetic to show it's true and that's enough intuition fo
Why two 'modes' for a Poisson Distribution with $\lambda$ an integer? Recall the density function for a Poisson RV is $e^{-\lambda}\lambda^x / x!$, you plugged $\lambda$ and $\lambda-1$ in for $x$. It is simple arithmetic to show it's true and that's enough intuition for me. The intuition is that Poisson RVs, for $\lambda \ge 1$, have convex density. If one allowed $x$ to take non-integral values, the curve would show a mode at $\lambda-0.5$. Proving this is easy, but it's simple to connect this with the idea that once $x$ is "forced" to take integral values, there are two modes interpolating this values. curve(exp(4)*4^x/gamma(x+1), from=0, to=10) abline(v=3.5)
Why two 'modes' for a Poisson Distribution with $\lambda$ an integer? Recall the density function for a Poisson RV is $e^{-\lambda}\lambda^x / x!$, you plugged $\lambda$ and $\lambda-1$ in for $x$. It is simple arithmetic to show it's true and that's enough intuition fo
25,776
Inverse covariance matrix vs covariance matrix in PCA
Observe that for positive definite covariance matrix $\mathbf \Sigma = \mathbf{UDU}'$ the precision is $\boldsymbol \Sigma^{-1} = \mathbf {U D}^{-1} \mathbf U'$. So the eigenvectors stay the same, but the eigenvalues of the precision are the reciprocals of the eigenvalues of the covariance. That means the biggest eigenvalues of the covariance will be the smallest eigenvalues of the precision. As you have the inverse, positive definiteness guarantees all eigenvalues are greater than zero. Hence if you retain the eigenvectors relating to the $k$ smallest eigenvalues of the precision this corresponds to ordinary PCA. Since we have already taken reciprocals ($\bf D^{-1}$), only the square root of the precision eigenvalues should be used in order to complete the whitening of the transformed data.
Inverse covariance matrix vs covariance matrix in PCA
Observe that for positive definite covariance matrix $\mathbf \Sigma = \mathbf{UDU}'$ the precision is $\boldsymbol \Sigma^{-1} = \mathbf {U D}^{-1} \mathbf U'$. So the eigenvectors stay the same, bu
Inverse covariance matrix vs covariance matrix in PCA Observe that for positive definite covariance matrix $\mathbf \Sigma = \mathbf{UDU}'$ the precision is $\boldsymbol \Sigma^{-1} = \mathbf {U D}^{-1} \mathbf U'$. So the eigenvectors stay the same, but the eigenvalues of the precision are the reciprocals of the eigenvalues of the covariance. That means the biggest eigenvalues of the covariance will be the smallest eigenvalues of the precision. As you have the inverse, positive definiteness guarantees all eigenvalues are greater than zero. Hence if you retain the eigenvectors relating to the $k$ smallest eigenvalues of the precision this corresponds to ordinary PCA. Since we have already taken reciprocals ($\bf D^{-1}$), only the square root of the precision eigenvalues should be used in order to complete the whitening of the transformed data.
Inverse covariance matrix vs covariance matrix in PCA Observe that for positive definite covariance matrix $\mathbf \Sigma = \mathbf{UDU}'$ the precision is $\boldsymbol \Sigma^{-1} = \mathbf {U D}^{-1} \mathbf U'$. So the eigenvectors stay the same, bu
25,777
Inverse covariance matrix vs covariance matrix in PCA
In addition, the inverse covariance matrix is proportionnal to the partial correlation between the vectors: Corr(Xi, Xj | (Xothers ) Correlation between Xi and Xj when all others are fixed, it is very useful for time series.
Inverse covariance matrix vs covariance matrix in PCA
In addition, the inverse covariance matrix is proportionnal to the partial correlation between the vectors: Corr(Xi, Xj | (Xothers ) Correlation between Xi and Xj when all others are fixed, it is ver
Inverse covariance matrix vs covariance matrix in PCA In addition, the inverse covariance matrix is proportionnal to the partial correlation between the vectors: Corr(Xi, Xj | (Xothers ) Correlation between Xi and Xj when all others are fixed, it is very useful for time series.
Inverse covariance matrix vs covariance matrix in PCA In addition, the inverse covariance matrix is proportionnal to the partial correlation between the vectors: Corr(Xi, Xj | (Xothers ) Correlation between Xi and Xj when all others are fixed, it is ver
25,778
Clustering with categorical and numeric data [duplicate]
Distance-based clustering algorithms can handle categorical data You only have to choose an appropriate distance function such as Gower's distance that combines the attributes as desired into a single distance. Then you can run Hierarchical Clustering, DBSCAN, OPTICS, and many more. Sounds good, but it is only part of the story - your choice of distance function has a massive impact on your results. Results will probably never be "sound" with categorical data Nevertheless, clustering may end up never working well on such data. Consider the description from Wikipedia: Cluster analysis or clustering is the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar (in some sense or another) to each other than to those in other groups (clusters). So for clustering, you need a qualitative similarity, so the algorithm knows when objects are "more similar" than others. That is why many algorithms use some form of distance: closer = more similar. It is a very intuitive way of qualifying similarity. With continuous variables, it is challenging enough to properly normalize the data. Most people either ignore data normalization, normalize to $[0;1]$ or standardize to $\mu=0$, $\sigma=1$. With high-dimensional data, people sometimes also do PCA (but more often than not use it in an absurd way, without considering the effect this has on their data). The good thing with continuous variables is that they can be quite "forgiving". If your scaling/weighting is a little off, the outcomes may still be good. Similarly, if there is a small error in your data, it only has a small effect on your distance. Unfortunately, this does not carry over to discrete, likert, or categorical variables. There are plenty of approaches used, such as one-hot encoding (every category becomes its own attribute), binary encodings (first category is 0,0; second is 0,1, third is 1,0, fourth is 1,1) that effectively map your data in a $\mathbb{R}^{d}$ space, where you could use k-means and all that. But these approaches are highly fragile. They tend to work if you have only binary categories unless they vary too much in frequency. But the problem is that you have low discriminability. You may have 0 objects at distance 0 (these would be duplicates), then nothing for a while, and then hundreds of objects at distance 2. But nothing in between. So whichever algorithm you use, it will have to merge all these objects at once, because they have the exact same similarity. In the worst case, your data might go from duplicates-only to everything-is-one-cluster because of this. Now if you would put different weights on every attribute this will be slightly better (you will still have lots of object pairs that differ only in this one attribute, and thus have the same distance) but how do you choose the weights of attributes? There does not appear a statistically sound unsupervised way. So in conclusion, I believe that categorical data does not cluster in the way clustering is commonly defined because the discrete nature yields too little discrimination/ranking of similarities. It may have frequent patterns as detected e.g. by Apriori, but that is a very different definition. And how to combine these two is not obvious. So for categorical data, I recommend frequent patterns. These make much more sense than "clusters".
Clustering with categorical and numeric data [duplicate]
Distance-based clustering algorithms can handle categorical data You only have to choose an appropriate distance function such as Gower's distance that combines the attributes as desired into a single
Clustering with categorical and numeric data [duplicate] Distance-based clustering algorithms can handle categorical data You only have to choose an appropriate distance function such as Gower's distance that combines the attributes as desired into a single distance. Then you can run Hierarchical Clustering, DBSCAN, OPTICS, and many more. Sounds good, but it is only part of the story - your choice of distance function has a massive impact on your results. Results will probably never be "sound" with categorical data Nevertheless, clustering may end up never working well on such data. Consider the description from Wikipedia: Cluster analysis or clustering is the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar (in some sense or another) to each other than to those in other groups (clusters). So for clustering, you need a qualitative similarity, so the algorithm knows when objects are "more similar" than others. That is why many algorithms use some form of distance: closer = more similar. It is a very intuitive way of qualifying similarity. With continuous variables, it is challenging enough to properly normalize the data. Most people either ignore data normalization, normalize to $[0;1]$ or standardize to $\mu=0$, $\sigma=1$. With high-dimensional data, people sometimes also do PCA (but more often than not use it in an absurd way, without considering the effect this has on their data). The good thing with continuous variables is that they can be quite "forgiving". If your scaling/weighting is a little off, the outcomes may still be good. Similarly, if there is a small error in your data, it only has a small effect on your distance. Unfortunately, this does not carry over to discrete, likert, or categorical variables. There are plenty of approaches used, such as one-hot encoding (every category becomes its own attribute), binary encodings (first category is 0,0; second is 0,1, third is 1,0, fourth is 1,1) that effectively map your data in a $\mathbb{R}^{d}$ space, where you could use k-means and all that. But these approaches are highly fragile. They tend to work if you have only binary categories unless they vary too much in frequency. But the problem is that you have low discriminability. You may have 0 objects at distance 0 (these would be duplicates), then nothing for a while, and then hundreds of objects at distance 2. But nothing in between. So whichever algorithm you use, it will have to merge all these objects at once, because they have the exact same similarity. In the worst case, your data might go from duplicates-only to everything-is-one-cluster because of this. Now if you would put different weights on every attribute this will be slightly better (you will still have lots of object pairs that differ only in this one attribute, and thus have the same distance) but how do you choose the weights of attributes? There does not appear a statistically sound unsupervised way. So in conclusion, I believe that categorical data does not cluster in the way clustering is commonly defined because the discrete nature yields too little discrimination/ranking of similarities. It may have frequent patterns as detected e.g. by Apriori, but that is a very different definition. And how to combine these two is not obvious. So for categorical data, I recommend frequent patterns. These make much more sense than "clusters".
Clustering with categorical and numeric data [duplicate] Distance-based clustering algorithms can handle categorical data You only have to choose an appropriate distance function such as Gower's distance that combines the attributes as desired into a single
25,779
Clustering with categorical and numeric data [duplicate]
Check out the R package ClusterOfVar. It handles mixed data. Edit: figured I should mention that k-means isn't actually the best clustering algorithm. It prefers even density, globular clusters, and each cluster has roughly the same size. If those are violated then K-means probably won't perform well. It is used often because you can use a different objective function to apply to many different situations, such as using cos() for high dimensional data. I don't have any experience with Python for clustering, but I've heard the R package I mentioned above is pretty good and incorporates good algorithms.
Clustering with categorical and numeric data [duplicate]
Check out the R package ClusterOfVar. It handles mixed data. Edit: figured I should mention that k-means isn't actually the best clustering algorithm. It prefers even density, globular clusters, and e
Clustering with categorical and numeric data [duplicate] Check out the R package ClusterOfVar. It handles mixed data. Edit: figured I should mention that k-means isn't actually the best clustering algorithm. It prefers even density, globular clusters, and each cluster has roughly the same size. If those are violated then K-means probably won't perform well. It is used often because you can use a different objective function to apply to many different situations, such as using cos() for high dimensional data. I don't have any experience with Python for clustering, but I've heard the R package I mentioned above is pretty good and incorporates good algorithms.
Clustering with categorical and numeric data [duplicate] Check out the R package ClusterOfVar. It handles mixed data. Edit: figured I should mention that k-means isn't actually the best clustering algorithm. It prefers even density, globular clusters, and e
25,780
What is "Multinomial Deviance" in the glmnet package?
Deviance is a specific transformation of a likelihood ratio. In particular, we consider the model-based likelihood after some fitting has been done and compare this to the likelihood of what is called the saturated model. This latter is a model that has as many parameters as data points and achieves a perfect fit, so by looking at the likelihood ratio we're measuring in some sense how far our fitted model is from a "perfect" model. In the multinomial regression case we have data of the form $(x_1, y_1), (x_2, y_2), \ldots , (x_n, y_n)$ where $y_i$ is a $k$-vector which indicates which class observation $i$ belongs to (exactly one entry contains a one and the rest are zero). Now if we fit some model that estimates a vector of probabilities $\hat{p}(x) = (\hat{p}_1(x), \hat{p}_2(x), \ldots, \hat{p}_k(x))$ then the model-based likelihood can be written $$ \prod_{i=1}^{n} \prod_{i=j}^{k} \hat{p}_j(x_i)^{y_{ij}} . $$ The saturated model on the other hand assigns probability one to each event that occurred, which means the vector of probabilities $\hat{p}_i$ is just equal to $y_i$ for each $i$ and we can write the ratio of these likelihoods as $$ \prod_{i=1}^{n} \prod_{j=1}^{k} \left ( \frac{\hat{p}_j(x_i)}{y_{ij}} \right )^{y_{ij}} . $$ To find the deviance we take minus two times the log of this quantity (this transformation has importance in mathematical statistics because of a connection with the $\chi^2$ distribution) to get $$ -2 \sum_{i=1}^{n} \sum_{j=1}^{k} y_{ij} \log \left ( \frac{\hat{p}_j(x_i)}{y_{ij}} \right ) . $$ (It's also worth pointing out that we treat zero times the log of anything as zero in this situation. The reason for this is that it's consistent with the idea that the saturated likelihood should equal one.) The only part of this that's peculiar to glmnet is the way in which the function $\hat{p}(x)$ is estimated. It's doing a constrained maximization of the likelihood and computing the deviance as the upper bound on $\| \beta \|_1$ is varied, with the model that achieves the smallest deviance on test data being considered a "best" model. Regarding the question about log loss, we can simplify the multinomial deviance above by keeping only the non-zero terms and write it as $-2 \sum_{i=1}^{n} \log [\hat{p}_{j_i} (x_i)]$, where $j_i$ is the index of the observed class for observation $i$, which is just the empirical log loss multiplied by a constant. So minimizing the deviance is actually equivalent to minimizing the log loss.
What is "Multinomial Deviance" in the glmnet package?
Deviance is a specific transformation of a likelihood ratio. In particular, we consider the model-based likelihood after some fitting has been done and compare this to the likelihood of what is calle
What is "Multinomial Deviance" in the glmnet package? Deviance is a specific transformation of a likelihood ratio. In particular, we consider the model-based likelihood after some fitting has been done and compare this to the likelihood of what is called the saturated model. This latter is a model that has as many parameters as data points and achieves a perfect fit, so by looking at the likelihood ratio we're measuring in some sense how far our fitted model is from a "perfect" model. In the multinomial regression case we have data of the form $(x_1, y_1), (x_2, y_2), \ldots , (x_n, y_n)$ where $y_i$ is a $k$-vector which indicates which class observation $i$ belongs to (exactly one entry contains a one and the rest are zero). Now if we fit some model that estimates a vector of probabilities $\hat{p}(x) = (\hat{p}_1(x), \hat{p}_2(x), \ldots, \hat{p}_k(x))$ then the model-based likelihood can be written $$ \prod_{i=1}^{n} \prod_{i=j}^{k} \hat{p}_j(x_i)^{y_{ij}} . $$ The saturated model on the other hand assigns probability one to each event that occurred, which means the vector of probabilities $\hat{p}_i$ is just equal to $y_i$ for each $i$ and we can write the ratio of these likelihoods as $$ \prod_{i=1}^{n} \prod_{j=1}^{k} \left ( \frac{\hat{p}_j(x_i)}{y_{ij}} \right )^{y_{ij}} . $$ To find the deviance we take minus two times the log of this quantity (this transformation has importance in mathematical statistics because of a connection with the $\chi^2$ distribution) to get $$ -2 \sum_{i=1}^{n} \sum_{j=1}^{k} y_{ij} \log \left ( \frac{\hat{p}_j(x_i)}{y_{ij}} \right ) . $$ (It's also worth pointing out that we treat zero times the log of anything as zero in this situation. The reason for this is that it's consistent with the idea that the saturated likelihood should equal one.) The only part of this that's peculiar to glmnet is the way in which the function $\hat{p}(x)$ is estimated. It's doing a constrained maximization of the likelihood and computing the deviance as the upper bound on $\| \beta \|_1$ is varied, with the model that achieves the smallest deviance on test data being considered a "best" model. Regarding the question about log loss, we can simplify the multinomial deviance above by keeping only the non-zero terms and write it as $-2 \sum_{i=1}^{n} \log [\hat{p}_{j_i} (x_i)]$, where $j_i$ is the index of the observed class for observation $i$, which is just the empirical log loss multiplied by a constant. So minimizing the deviance is actually equivalent to minimizing the log loss.
What is "Multinomial Deviance" in the glmnet package? Deviance is a specific transformation of a likelihood ratio. In particular, we consider the model-based likelihood after some fitting has been done and compare this to the likelihood of what is calle
25,781
Approximating $\log( E(X))$
By the Delta method, the variance of a function of an RV is approximately equal to the variance of the RV times the squared derivative evaluated at the mean. Hence $$\mathrm{var}(\log(X)) \approx \frac{1}{ \left[E(X)\right] ^2 } \mathrm{var}(X)$$ and there you have it. Your derivation was right of course.
Approximating $\log( E(X))$
By the Delta method, the variance of a function of an RV is approximately equal to the variance of the RV times the squared derivative evaluated at the mean. Hence $$\mathrm{var}(\log(X)) \approx \fra
Approximating $\log( E(X))$ By the Delta method, the variance of a function of an RV is approximately equal to the variance of the RV times the squared derivative evaluated at the mean. Hence $$\mathrm{var}(\log(X)) \approx \frac{1}{ \left[E(X)\right] ^2 } \mathrm{var}(X)$$ and there you have it. Your derivation was right of course.
Approximating $\log( E(X))$ By the Delta method, the variance of a function of an RV is approximately equal to the variance of the RV times the squared derivative evaluated at the mean. Hence $$\mathrm{var}(\log(X)) \approx \fra
25,782
Why does the intercept column in model.matrix replace the first factor?
Consider the following: require(mlbench) data(HouseVotes84, package = "mlbench") head(HouseVotes84) labels <- model.matrix(~ V1, data=HouseVotes84) head(labels) labels1 <- model.matrix(~ V1+1, data=HouseVotes84) head(labels1) labels0 <- model.matrix(~ V1+0, data=HouseVotes84) head(labels0) labels_1 <- model.matrix(~ V1-1, data=HouseVotes84) head(labels_1) The first two commands are identical. The last two commands specifies not to produce the intercept and keeps the two dummy variables produced.
Why does the intercept column in model.matrix replace the first factor?
Consider the following: require(mlbench) data(HouseVotes84, package = "mlbench") head(HouseVotes84) labels <- model.matrix(~ V1, data=HouseVotes84) head(labels) labels1 <- model.matrix(~ V1+1, data
Why does the intercept column in model.matrix replace the first factor? Consider the following: require(mlbench) data(HouseVotes84, package = "mlbench") head(HouseVotes84) labels <- model.matrix(~ V1, data=HouseVotes84) head(labels) labels1 <- model.matrix(~ V1+1, data=HouseVotes84) head(labels1) labels0 <- model.matrix(~ V1+0, data=HouseVotes84) head(labels0) labels_1 <- model.matrix(~ V1-1, data=HouseVotes84) head(labels_1) The first two commands are identical. The last two commands specifies not to produce the intercept and keeps the two dummy variables produced.
Why does the intercept column in model.matrix replace the first factor? Consider the following: require(mlbench) data(HouseVotes84, package = "mlbench") head(HouseVotes84) labels <- model.matrix(~ V1, data=HouseVotes84) head(labels) labels1 <- model.matrix(~ V1+1, data
25,783
Why does the intercept column in model.matrix replace the first factor?
In statistics, when we have a factor variable with $k$ levels, we need to convert it to $k - 1$ indicator variables. We choose one level as the baseline, and then have an indicator variable for each of the remaining levels. First let me explain why this isn't throwing away any information. Say there are levels A, B, C, and we have $I_B$ and $I_C$, the indicators for being in level B and C. An individual is in level A if and only if $I_B = 0$ (not in B) and $I_C = 0$ (not in C). So we still have kept track of the individuals in level A. This works for any number of levels. Now as you note we could code the same information with three indicator variables $I_A$, $I_B$ and $I_C$. The reason why we don't is known as multicollinearity. In short, the columns of the regression matrix won't be linearly independent. This means the matrix $X^T X$ is not invertible, so we can't perform linear regression, as we need to calculate this inverse to calculate the regression estimates $\hat{\beta} = \left(X^T X\right)^{-1}X^T y$. To take a really simple example, say we have two individuals, one in each of two levels A and B, and an intercept term in our regression. The regression matrix $X$ will be \begin{equation} X = \begin{bmatrix} 1 & 1 & 0 \\ 1 & 0 & 1 \\ \end{bmatrix} \end{equation} Then \begin{align} X^T X & = \begin{bmatrix} 1 & 1\\ 1 & 0\\ 0 & 1\\ \end{bmatrix} \begin{bmatrix} 1 & 1 & 0 \\ 1 & 0 & 1 \\ \end{bmatrix}\\ & = \begin{bmatrix} 2 & 1 & 1 \\ 1 & 1 & 0 \\ 1 & 0 & 1\\ \end{bmatrix} \end{align} You can then see that adding the second and third columns of $X^T X$ gives the first column, so the inverse can't be computed. This applies in general the Wikipedia page on multicollinearity gives more of an explanation. If there is an exact linear relationship (perfect multicollinearity) among the independent variables, at least one of the columns of $X$ is a linear combination of the others, and so the rank of $X$ (and therefore of $X^T X$) is less than $k+1$, and the matrix $X^T X$ will not be invertible. It is ok to include an indicator for all levels of the factor if you don't include the intercept term, and this encodes the exact same information. (The intercept term minus all other indicators gives the indicator for the baseline factor). But if you have more than one factor in the model this runs into the multicollinearity problem, so you can only include all levels if there is only one factor variable and no intercept term in the model.
Why does the intercept column in model.matrix replace the first factor?
In statistics, when we have a factor variable with $k$ levels, we need to convert it to $k - 1$ indicator variables. We choose one level as the baseline, and then have an indicator variable for each o
Why does the intercept column in model.matrix replace the first factor? In statistics, when we have a factor variable with $k$ levels, we need to convert it to $k - 1$ indicator variables. We choose one level as the baseline, and then have an indicator variable for each of the remaining levels. First let me explain why this isn't throwing away any information. Say there are levels A, B, C, and we have $I_B$ and $I_C$, the indicators for being in level B and C. An individual is in level A if and only if $I_B = 0$ (not in B) and $I_C = 0$ (not in C). So we still have kept track of the individuals in level A. This works for any number of levels. Now as you note we could code the same information with three indicator variables $I_A$, $I_B$ and $I_C$. The reason why we don't is known as multicollinearity. In short, the columns of the regression matrix won't be linearly independent. This means the matrix $X^T X$ is not invertible, so we can't perform linear regression, as we need to calculate this inverse to calculate the regression estimates $\hat{\beta} = \left(X^T X\right)^{-1}X^T y$. To take a really simple example, say we have two individuals, one in each of two levels A and B, and an intercept term in our regression. The regression matrix $X$ will be \begin{equation} X = \begin{bmatrix} 1 & 1 & 0 \\ 1 & 0 & 1 \\ \end{bmatrix} \end{equation} Then \begin{align} X^T X & = \begin{bmatrix} 1 & 1\\ 1 & 0\\ 0 & 1\\ \end{bmatrix} \begin{bmatrix} 1 & 1 & 0 \\ 1 & 0 & 1 \\ \end{bmatrix}\\ & = \begin{bmatrix} 2 & 1 & 1 \\ 1 & 1 & 0 \\ 1 & 0 & 1\\ \end{bmatrix} \end{align} You can then see that adding the second and third columns of $X^T X$ gives the first column, so the inverse can't be computed. This applies in general the Wikipedia page on multicollinearity gives more of an explanation. If there is an exact linear relationship (perfect multicollinearity) among the independent variables, at least one of the columns of $X$ is a linear combination of the others, and so the rank of $X$ (and therefore of $X^T X$) is less than $k+1$, and the matrix $X^T X$ will not be invertible. It is ok to include an indicator for all levels of the factor if you don't include the intercept term, and this encodes the exact same information. (The intercept term minus all other indicators gives the indicator for the baseline factor). But if you have more than one factor in the model this runs into the multicollinearity problem, so you can only include all levels if there is only one factor variable and no intercept term in the model.
Why does the intercept column in model.matrix replace the first factor? In statistics, when we have a factor variable with $k$ levels, we need to convert it to $k - 1$ indicator variables. We choose one level as the baseline, and then have an indicator variable for each o
25,784
What is the difference between Multitask and Multiclass learning
Just to give a more clear understanding, I have explained each terminology with examples Multiclass classification/(One-Vs-One and One-Vs-ALL): Classification task with >2 classes! Assumption is that each sample is assigned to one and only one label E.g. MNIST E.g. a set of images of fruits which may be oranges, apples, or pears. Last layer activation function would be softmax-softmax activation function generalizes the logistic activation function to C classes rather than just two classes.(single label to single example) Eg saying each image is either pedestrians or car or detect stop signs! Eg.saying each image is either of the numbers between 0-9(MNIST)! Or you can use 4 different logistic regression classifers- each neuron in the last layer has sigmoid activation function (extension of one-vs-all method!)! Multilabel classification: This Classification task assigns a set of target labels to each sample. E.g. Building a classifier for a self-driving car that would need to detect several different things such as pedestrians, detect other cars, detect stop signs in an image!. E.g. A document could have multiple topics! Loss function used would be "logLoss" Multioutput regression/ Multitarget regression/multidimensional linear regression: This task assigns a sample to a set of target values! E.g.predicting several properties for each data-point, such as wind direction and magnitude at a certain location Last layer activation should be linear Loss function used would be "MSE" Now let's comes to the difference between multi-task learning(one subset is a multilabel classification or multioutput regression) and multiclass classification problem! : Multi-class classification: You are assigning a single label (could be multiple labels such as MNIST problem) to the input image as explained above. Multi-task learning (one subset of it is multi-label classification) You're asking for each picture, does it have a pedestrian, or a car a stop-sign or traffic-light, and multiple objects could appear in the same image (one image can have multiple labels!). In other words, If you train a neural network to minimize this cost function (Log loss) you are carrying out multi-task learning because what you're doing is building a single neural network that is looking at each image and basically solving four different classification problems. It's trying to tell you does each image have each of these four objects in it?. Or you could achieve it by just training four separate neural networks instead of train one network to do four things! Note: But if some of the earlier features in the neural network can be shared between these different types of objects, then you find that training one NN to do four things, results in better performance than training four completely separate neural networks to do the four tasks separately. That's the power of Multi-task learning! To put everything into perspective, Multi-task learning will make more sense when you have the below requirements: Training on a set of tasks that could benefit from having shared lower-level features! If the amount of data you have for each task is quite similar! @RockTheStar, I think your transfer learning suggestion isn't correct! What you are trying to say & have similar(but weak) meaning for transfer learning, I will try to explain with the help of an example. Suppose you have 100 different tasks and you have 1000 train examples for each! If you build you separate NN for classifying each class you won't do much good! due to a limited number of training example (1000) but if you build a single network for solving 100 different, let's say classification problem then, you have (1000*1000)(Million instead of just 1000 for each separate task) training examples that can provide some knowledge that helps every other task among these 100 tasks. This is a big boost! Can train a big enough NN to do well on all the tasks!
What is the difference between Multitask and Multiclass learning
Just to give a more clear understanding, I have explained each terminology with examples Multiclass classification/(One-Vs-One and One-Vs-ALL): Classification task with >2 classes! Assumption is
What is the difference between Multitask and Multiclass learning Just to give a more clear understanding, I have explained each terminology with examples Multiclass classification/(One-Vs-One and One-Vs-ALL): Classification task with >2 classes! Assumption is that each sample is assigned to one and only one label E.g. MNIST E.g. a set of images of fruits which may be oranges, apples, or pears. Last layer activation function would be softmax-softmax activation function generalizes the logistic activation function to C classes rather than just two classes.(single label to single example) Eg saying each image is either pedestrians or car or detect stop signs! Eg.saying each image is either of the numbers between 0-9(MNIST)! Or you can use 4 different logistic regression classifers- each neuron in the last layer has sigmoid activation function (extension of one-vs-all method!)! Multilabel classification: This Classification task assigns a set of target labels to each sample. E.g. Building a classifier for a self-driving car that would need to detect several different things such as pedestrians, detect other cars, detect stop signs in an image!. E.g. A document could have multiple topics! Loss function used would be "logLoss" Multioutput regression/ Multitarget regression/multidimensional linear regression: This task assigns a sample to a set of target values! E.g.predicting several properties for each data-point, such as wind direction and magnitude at a certain location Last layer activation should be linear Loss function used would be "MSE" Now let's comes to the difference between multi-task learning(one subset is a multilabel classification or multioutput regression) and multiclass classification problem! : Multi-class classification: You are assigning a single label (could be multiple labels such as MNIST problem) to the input image as explained above. Multi-task learning (one subset of it is multi-label classification) You're asking for each picture, does it have a pedestrian, or a car a stop-sign or traffic-light, and multiple objects could appear in the same image (one image can have multiple labels!). In other words, If you train a neural network to minimize this cost function (Log loss) you are carrying out multi-task learning because what you're doing is building a single neural network that is looking at each image and basically solving four different classification problems. It's trying to tell you does each image have each of these four objects in it?. Or you could achieve it by just training four separate neural networks instead of train one network to do four things! Note: But if some of the earlier features in the neural network can be shared between these different types of objects, then you find that training one NN to do four things, results in better performance than training four completely separate neural networks to do the four tasks separately. That's the power of Multi-task learning! To put everything into perspective, Multi-task learning will make more sense when you have the below requirements: Training on a set of tasks that could benefit from having shared lower-level features! If the amount of data you have for each task is quite similar! @RockTheStar, I think your transfer learning suggestion isn't correct! What you are trying to say & have similar(but weak) meaning for transfer learning, I will try to explain with the help of an example. Suppose you have 100 different tasks and you have 1000 train examples for each! If you build you separate NN for classifying each class you won't do much good! due to a limited number of training example (1000) but if you build a single network for solving 100 different, let's say classification problem then, you have (1000*1000)(Million instead of just 1000 for each separate task) training examples that can provide some knowledge that helps every other task among these 100 tasks. This is a big boost! Can train a big enough NN to do well on all the tasks!
What is the difference between Multitask and Multiclass learning Just to give a more clear understanding, I have explained each terminology with examples Multiclass classification/(One-Vs-One and One-Vs-ALL): Classification task with >2 classes! Assumption is
25,785
What is the difference between Multitask and Multiclass learning
Slight correction on @RockTheStar answer. Multi-task learning is not when you learn for one task and then transfer to another as was suggested, instead the tasks are learned in parallel similar to the usual multi-class classification setup. I suppose the simple distinction that can be made is that the outputs are not necessarily classes of the same of a single task, but two or more loosely related tasks that are sharing information.
What is the difference between Multitask and Multiclass learning
Slight correction on @RockTheStar answer. Multi-task learning is not when you learn for one task and then transfer to another as was suggested, instead the tasks are learned in parallel similar to the
What is the difference between Multitask and Multiclass learning Slight correction on @RockTheStar answer. Multi-task learning is not when you learn for one task and then transfer to another as was suggested, instead the tasks are learned in parallel similar to the usual multi-class classification setup. I suppose the simple distinction that can be made is that the outputs are not necessarily classes of the same of a single task, but two or more loosely related tasks that are sharing information.
What is the difference between Multitask and Multiclass learning Slight correction on @RockTheStar answer. Multi-task learning is not when you learn for one task and then transfer to another as was suggested, instead the tasks are learned in parallel similar to the
25,786
What is the difference between Multitask and Multiclass learning
Multi-class learning: have multiple class labels that you want to classify. For example, I have labels cat, dog, and pig. These are animals. I want to make a DNN to classify them. That's a multi-class learning. Multi-task learning: is somewhat like transfer learning. Basically, you create one model for one classification task and them use it in another classification task (after modification). In you case, you can create a two-label DNN to classify if the image is human or not. Then use that model parameters parameters to start to build another classifier that classify moving or not. I will consider your case more like multi-task learning because the subjects of interests are different.
What is the difference between Multitask and Multiclass learning
Multi-class learning: have multiple class labels that you want to classify. For example, I have labels cat, dog, and pig. These are animals. I want to make a DNN to classify them. That's a multi-class
What is the difference between Multitask and Multiclass learning Multi-class learning: have multiple class labels that you want to classify. For example, I have labels cat, dog, and pig. These are animals. I want to make a DNN to classify them. That's a multi-class learning. Multi-task learning: is somewhat like transfer learning. Basically, you create one model for one classification task and them use it in another classification task (after modification). In you case, you can create a two-label DNN to classify if the image is human or not. Then use that model parameters parameters to start to build another classifier that classify moving or not. I will consider your case more like multi-task learning because the subjects of interests are different.
What is the difference between Multitask and Multiclass learning Multi-class learning: have multiple class labels that you want to classify. For example, I have labels cat, dog, and pig. These are animals. I want to make a DNN to classify them. That's a multi-class
25,787
What is the difference between Multitask and Multiclass learning
I notice in MTL a image can have multiple labels, but usually in multiclass an image is assigned only one - is this the difference?` Yes. In multi-task learning, you can detect multiple objects (i.e. 'car', 'human', 'cat', 'tree') in one given image. If there exist both a human and a car in your model, Your labels are [1,1,0,0] (from ['car', 'human', 'cat', 'tree']). In multiclass classification, you will have only one gold (1) in your labels, [1,0,0,0].
What is the difference between Multitask and Multiclass learning
I notice in MTL a image can have multiple labels, but usually in multiclass an image is assigned only one - is this the difference?` Yes. In multi-task learning, you can detect multiple objects (i
What is the difference between Multitask and Multiclass learning I notice in MTL a image can have multiple labels, but usually in multiclass an image is assigned only one - is this the difference?` Yes. In multi-task learning, you can detect multiple objects (i.e. 'car', 'human', 'cat', 'tree') in one given image. If there exist both a human and a car in your model, Your labels are [1,1,0,0] (from ['car', 'human', 'cat', 'tree']). In multiclass classification, you will have only one gold (1) in your labels, [1,0,0,0].
What is the difference between Multitask and Multiclass learning I notice in MTL a image can have multiple labels, but usually in multiclass an image is assigned only one - is this the difference?` Yes. In multi-task learning, you can detect multiple objects (i
25,788
What is the difference between Multitask and Multiclass learning
There is quite some information in all of the answers provided thus far, but maybe a summary answer might be useful for people with the same / a similar question: Multi-class learning is the terminology used when you predict a single label for each input, but each label is a single element from a set of possible labels. Taking the example from this answer: you have an image of an animal and the goal is to label whether it is a cat OR a dog OR a pig. It can only be one of these animals, but there are multiple options. To train a network on this kind of problems, you would generally use the Cross-entropy loss function. Multi-task learning is when you have different problems that need to be solved simultaneously (as stated in this answer. Each problem could be a binary classification problem (as the OP example) or another multi-class problem. Taking the example of the animal images again: a second task could be to predict whether the environment on the picture is sunny OR cloudy OR indoor. So now the goal is to find the animal label AND the environment label. The key idea is that solving one task could help solving the second task (in this example: cats are more likely to appear indoors than pigs). For training a network in this case, each output can have its own loss function. The loss functions can be combined by summing them up, using weights to balance the importance of each task. Multi-label learning (as mentioned in this answer) can be considered a special case of multi-task learning. In this case, there could be one or more animals in the image and you want a label for every animal in the image. In practice this is solved by breaking down this task in multiple binary problems. If the possible labels would be dog, cat and pig, the binary problems would be (1) Is there a dog in the image, (2) Is there a cat in the image, (3) is there a pig in the image. These sub-problems can then be tackled by multi-task methods. Note that I ignored regression as a whole, but multi-task learning could also combine classification and regression problems.
What is the difference between Multitask and Multiclass learning
There is quite some information in all of the answers provided thus far, but maybe a summary answer might be useful for people with the same / a similar question: Multi-class learning is the terminol
What is the difference between Multitask and Multiclass learning There is quite some information in all of the answers provided thus far, but maybe a summary answer might be useful for people with the same / a similar question: Multi-class learning is the terminology used when you predict a single label for each input, but each label is a single element from a set of possible labels. Taking the example from this answer: you have an image of an animal and the goal is to label whether it is a cat OR a dog OR a pig. It can only be one of these animals, but there are multiple options. To train a network on this kind of problems, you would generally use the Cross-entropy loss function. Multi-task learning is when you have different problems that need to be solved simultaneously (as stated in this answer. Each problem could be a binary classification problem (as the OP example) or another multi-class problem. Taking the example of the animal images again: a second task could be to predict whether the environment on the picture is sunny OR cloudy OR indoor. So now the goal is to find the animal label AND the environment label. The key idea is that solving one task could help solving the second task (in this example: cats are more likely to appear indoors than pigs). For training a network in this case, each output can have its own loss function. The loss functions can be combined by summing them up, using weights to balance the importance of each task. Multi-label learning (as mentioned in this answer) can be considered a special case of multi-task learning. In this case, there could be one or more animals in the image and you want a label for every animal in the image. In practice this is solved by breaking down this task in multiple binary problems. If the possible labels would be dog, cat and pig, the binary problems would be (1) Is there a dog in the image, (2) Is there a cat in the image, (3) is there a pig in the image. These sub-problems can then be tackled by multi-task methods. Note that I ignored regression as a whole, but multi-task learning could also combine classification and regression problems.
What is the difference between Multitask and Multiclass learning There is quite some information in all of the answers provided thus far, but maybe a summary answer might be useful for people with the same / a similar question: Multi-class learning is the terminol
25,789
What exactly is the procedure to compute principal components in kernel PCA?
To find PCs in classical PCA, one can perform singular value decomposition of the centred data matrix (with variables in columns) $\mathbf X = \mathbf U \mathbf S \mathbf V^\top$; columns of $\mathbf U \mathbf S$ are called principal components (i.e. projections of the original data onto the eigenvectors of the covariance matrix). Observe that the so called Gram matrix $\mathbf G = \mathbf X \mathbf X^\top = \mathbf U \mathbf S^2 \mathbf U^\top$ has eigenvectors $\mathbf U$ and eigenvalues $\mathbf S^2$, so another way to compute principal components is to scale eigenvectors of the Gram matrix by the square roots of the respective eigenvalues. In full analogy, here is a complete algorithm to compute kernel principal components: Choose a kernel function $k(\mathbf x, \mathbf y)$ that conceptually is a scalar product in the target space. Compute a Gram/kernel matrix $\mathbf K$ with $K_{ij} = k(\mathbf x_{(i)}, \mathbf x_{(j)})$. Center the kernel matrix via the following trick: $$\mathbf K_\mathrm{centered} = \mathbf K - \mathbf 1_n \mathbf K - \mathbf K \mathbf 1_n + \mathbf 1_n \mathbf K \mathbf 1_n=(\mathbf I - \mathbf 1_n)\mathbf K(\mathbf I - \mathbf 1_n) ,$$ where $\mathbf 1_n$ is a $n \times n$ matrix with all elements equal to $\frac{1}{n}$, and $n$ is the number of data points. Find eigenvectors $\mathbf U$ and eigenvalues $\mathbf S^2$ of the centered kernel matrix. Multiply each eigenvector by the square root of the respective eigenvalue. Done. These are the kernel principal components. Answering your question specifically, I don't see any need of scaling either eigenvectors or eigenvalues by $n$ in steps 4--5. A good reference is the original paper: Scholkopf B, Smola A, and Müller KR, Kernel principal component analysis, 1999. Note that it presents the same algorithm in a somewhat more complicated way: you are supposed to find eigenvectors of $K$ and then multiply them by $K$ (as you wrote in your question). But multiplying a matrix and its eigenvector results in the same eigenvector scaled by the eigenvalue (by definition).
What exactly is the procedure to compute principal components in kernel PCA?
To find PCs in classical PCA, one can perform singular value decomposition of the centred data matrix (with variables in columns) $\mathbf X = \mathbf U \mathbf S \mathbf V^\top$; columns of $\mathbf
What exactly is the procedure to compute principal components in kernel PCA? To find PCs in classical PCA, one can perform singular value decomposition of the centred data matrix (with variables in columns) $\mathbf X = \mathbf U \mathbf S \mathbf V^\top$; columns of $\mathbf U \mathbf S$ are called principal components (i.e. projections of the original data onto the eigenvectors of the covariance matrix). Observe that the so called Gram matrix $\mathbf G = \mathbf X \mathbf X^\top = \mathbf U \mathbf S^2 \mathbf U^\top$ has eigenvectors $\mathbf U$ and eigenvalues $\mathbf S^2$, so another way to compute principal components is to scale eigenvectors of the Gram matrix by the square roots of the respective eigenvalues. In full analogy, here is a complete algorithm to compute kernel principal components: Choose a kernel function $k(\mathbf x, \mathbf y)$ that conceptually is a scalar product in the target space. Compute a Gram/kernel matrix $\mathbf K$ with $K_{ij} = k(\mathbf x_{(i)}, \mathbf x_{(j)})$. Center the kernel matrix via the following trick: $$\mathbf K_\mathrm{centered} = \mathbf K - \mathbf 1_n \mathbf K - \mathbf K \mathbf 1_n + \mathbf 1_n \mathbf K \mathbf 1_n=(\mathbf I - \mathbf 1_n)\mathbf K(\mathbf I - \mathbf 1_n) ,$$ where $\mathbf 1_n$ is a $n \times n$ matrix with all elements equal to $\frac{1}{n}$, and $n$ is the number of data points. Find eigenvectors $\mathbf U$ and eigenvalues $\mathbf S^2$ of the centered kernel matrix. Multiply each eigenvector by the square root of the respective eigenvalue. Done. These are the kernel principal components. Answering your question specifically, I don't see any need of scaling either eigenvectors or eigenvalues by $n$ in steps 4--5. A good reference is the original paper: Scholkopf B, Smola A, and Müller KR, Kernel principal component analysis, 1999. Note that it presents the same algorithm in a somewhat more complicated way: you are supposed to find eigenvectors of $K$ and then multiply them by $K$ (as you wrote in your question). But multiplying a matrix and its eigenvector results in the same eigenvector scaled by the eigenvalue (by definition).
What exactly is the procedure to compute principal components in kernel PCA? To find PCs in classical PCA, one can perform singular value decomposition of the centred data matrix (with variables in columns) $\mathbf X = \mathbf U \mathbf S \mathbf V^\top$; columns of $\mathbf
25,790
Why take transpose of regressor variable in linear regression
Let me begin by saying it seems as though you're not being very careful when you write mathematical expressions. Nevertheless, I think I can understand what you're asking, so I will try to answer. To begin, we ought to straighten out the notation being used. Doing this will enable us to communicate more clearly and identify any misunderstandings that may exist. When you write $f(x,y):y= ax + b$, I take it that you really mean the following $$ y = ax + b $$ where $a$ and $b$ are constants and real numbers (although, strictly speaking they need not be real numbers). Furthermore, $y$ is a function of only one variable, $x$, so we write $f(x)$ instead of $f(x,y)$. Pay particular attention to the fact that the commutative property of multiplication is satisfied when multiplying both $a$ and $x$ together. In other words, the order in which $a$ and $x$ are multiplied does not matter. Now enter the other equation; namely, what you've written as $y = \beta X^{T} + \epsilon$. This is actually matrix notation and it has a different meaning to the (more everyday?) algebraic notation shown in the previous paragraph. The linear regression model can, in fact, be more commonly written in the following form $$ y = X \beta + \epsilon $$ where $y$ is a $(T \times 1)$ vector, $X$ is a $(T \times K)$ matrix, $\beta$ is a $(K \times 1)$ vector, and $\epsilon$ is a $(T \times 1)$ vector. The notation being used in brackets refers to the dimensions of each vector or matrix, where the first number refers to the number of rows and the second to the number of columns. So, for example, $X$ is a matrix with $T$ rows and $K$ columns. Note the distinction! $X$ and $\beta$ are matrices not like $a$ and $x$, which are just scalar values. Crucially, the commutative property of (matrix) multiplication is not always satisfied in the world of linear algebra; the general case is that it is not satisfied. In other words, in general, $X\beta \neq \beta X$. Furthermore, such operation may not even be permitted, since in matrix algebra, matrices must be conformable for multiplication if they are to be multiplied. In order for two matrices to be conformable for matrix multiplication, we say that the number of columns of the left matrix must be the same as the number of rows of the right matrix. In the linear regression model, $X \beta$ is possible because $X$, the left matrix, has $K$ columns and $\beta$, the right matrix, has $K$ rows. On the other hand, $\beta X$ would not be possible because $\beta$, the first matrix, has $1$ column while $X$, the second matrix, has $T$ rows - unless, of course, $T = 1$. At this stage, please revise what you meant when you wrote: $y = \beta X^{T} + \epsilon$. Lastly, the Wikipedia page that you link us to shows that the linear regression model can also be written in a form involving a transpose: $$ y_{i} = x_{i}^{T} \beta + \epsilon_{i} $$ where both $x_{i}$ and $\beta$ are column vectors of dimension $(p \times 1)$. If anything I've written has made sense, you should be able to decipher why $x_{i}^{T} \beta$ and not $x_{i} \beta$.
Why take transpose of regressor variable in linear regression
Let me begin by saying it seems as though you're not being very careful when you write mathematical expressions. Nevertheless, I think I can understand what you're asking, so I will try to answer. To
Why take transpose of regressor variable in linear regression Let me begin by saying it seems as though you're not being very careful when you write mathematical expressions. Nevertheless, I think I can understand what you're asking, so I will try to answer. To begin, we ought to straighten out the notation being used. Doing this will enable us to communicate more clearly and identify any misunderstandings that may exist. When you write $f(x,y):y= ax + b$, I take it that you really mean the following $$ y = ax + b $$ where $a$ and $b$ are constants and real numbers (although, strictly speaking they need not be real numbers). Furthermore, $y$ is a function of only one variable, $x$, so we write $f(x)$ instead of $f(x,y)$. Pay particular attention to the fact that the commutative property of multiplication is satisfied when multiplying both $a$ and $x$ together. In other words, the order in which $a$ and $x$ are multiplied does not matter. Now enter the other equation; namely, what you've written as $y = \beta X^{T} + \epsilon$. This is actually matrix notation and it has a different meaning to the (more everyday?) algebraic notation shown in the previous paragraph. The linear regression model can, in fact, be more commonly written in the following form $$ y = X \beta + \epsilon $$ where $y$ is a $(T \times 1)$ vector, $X$ is a $(T \times K)$ matrix, $\beta$ is a $(K \times 1)$ vector, and $\epsilon$ is a $(T \times 1)$ vector. The notation being used in brackets refers to the dimensions of each vector or matrix, where the first number refers to the number of rows and the second to the number of columns. So, for example, $X$ is a matrix with $T$ rows and $K$ columns. Note the distinction! $X$ and $\beta$ are matrices not like $a$ and $x$, which are just scalar values. Crucially, the commutative property of (matrix) multiplication is not always satisfied in the world of linear algebra; the general case is that it is not satisfied. In other words, in general, $X\beta \neq \beta X$. Furthermore, such operation may not even be permitted, since in matrix algebra, matrices must be conformable for multiplication if they are to be multiplied. In order for two matrices to be conformable for matrix multiplication, we say that the number of columns of the left matrix must be the same as the number of rows of the right matrix. In the linear regression model, $X \beta$ is possible because $X$, the left matrix, has $K$ columns and $\beta$, the right matrix, has $K$ rows. On the other hand, $\beta X$ would not be possible because $\beta$, the first matrix, has $1$ column while $X$, the second matrix, has $T$ rows - unless, of course, $T = 1$. At this stage, please revise what you meant when you wrote: $y = \beta X^{T} + \epsilon$. Lastly, the Wikipedia page that you link us to shows that the linear regression model can also be written in a form involving a transpose: $$ y_{i} = x_{i}^{T} \beta + \epsilon_{i} $$ where both $x_{i}$ and $\beta$ are column vectors of dimension $(p \times 1)$. If anything I've written has made sense, you should be able to decipher why $x_{i}^{T} \beta$ and not $x_{i} \beta$.
Why take transpose of regressor variable in linear regression Let me begin by saying it seems as though you're not being very careful when you write mathematical expressions. Nevertheless, I think I can understand what you're asking, so I will try to answer. To
25,791
Why is this multiple imputation low quality?
Given that you are using six cases [records] and three variables, the quality of your imputation will be quite low. To see why this will be the case, remember that multiple imputation works by filling in missing values with plausible imputed values. These imputed values are calculated in $m$ separate datasets (I will return to how these imputed values are derived later in this answer). The imputed values will vary slightly from dataset to dataset. Thus, given a statistical quantity of interest $q$ (e.g., a mean, a regression coefficient, etc), one can use the $m$ datasets to estimate the average standard error for $q$ within the $m$ datasets (a quantity that I will call the within-imputation variance, or $\bar{U}$) and the degree to which $q$ varies across the $m$ datasets (a quantity that I will call the between-imputation variance, or $B$). The relationship between imputation quality, $B$, and $\bar{U}$ One can use the within-imputation variance $\bar{U}$ and the between-imputation variance $B$ to derive an estimate of the degree to which an imputed estimate of a statistical quantity has been influenced by missing information. Of course, the more information has been lost, the poorer the quality of the imputation. The estimate of information lost to missingness is labeled $\gamma$, and is given by the following formula: $$\gamma = \frac{r + \frac{2}{df + 3}}{r + 1}$$ $r$ in this formula is a ratio of the between-imputation variance $B$ to the within-imputation-variance $\bar{U}$: $$r = \frac{(1 + \frac1m)B}{\bar{U}}$$ Thus, high values of $B$ result in high values of $r$, which in turn will result in high values of $\gamma$. A high value of $\gamma$, in turn, indicates more information lost due to missing data and a poorer quality imputation. $df$ in the formula for $\gamma$ is also a function of $B$ and $\bar{U}$. Specifically, $df$ is estimated by $$df = (m - 1)\left(1 + \frac{m\bar{U}}{(m + 1)B}\right)^2$$ Thus, in addition to increasing the ratio of between-imputation variance to within-imputation variance, increasing $B$ also decreases $df$. This will result in a higher value of $\gamma$, indicating more information lost to missingness and a poorer quality imputation. In sum, higher values of the between-imputation variance $B$ affect imputation quality in two ways: Higher values of $B$ increase the ratio of the variance between imputations to the variance within imputations, decreasing imputation quality Higher values of $B$ decrease the available degrees of freedom, decreasing imputation quality The relationship between the number of cases and $B$ Given two otherwise similar datasets, a dataset with a smaller number of cases will have a larger between-imputation variance $B$. This will occur because, as I describe above, the between-imputation variance is computed by computing a statistical quantity of interest $q$ within each of $m$ imputed datasets and computing the degree to which $q$ varies across each of the $m$ datasets. If a given dataset has a higher quantity of cases but a similar quantity of missing values as another, a smaller proportion of values will be free to vary across each of the $m$ imputed datasets, meaning that there will be lower overall variation in $q$ across the imputed datasets. Thus, in general, increasing the number of cases (or, more precisely, decreasing the proportion of missing values) will increase imputation quality. The relationship between the number of variables and $B$ Given two otherwise similar datasets, a dataset with a larger number of variables will have a smaller between-imputation variance $B$, as long as those extra variables are informative about the missing values. This will occur because, in general, missing values for a given variable are "filled in" by using information from other variables to generate plausible estimates of the missing values (the specific details of how these estimates are generated will vary depending on the MI implementation you're using). More information in the form of extra variables will result in more stable imputed values, resulting in less variation in statistical quantity of interest $q$ across each of the $m$ imputed datasets. Thus, in general, increasing the number of variables available in a dataset will increase imputation quality, as long as those extra variables are informative about the missing values. References Rubin, D. B. (1996). Multiple imputation after 18+ years. Journal of the American Statistical Association, 91, 473-489. Schafer, J. L. (1999). Multiple imputation: A primer. Statistical Methods in Medical Research, 8, 3-15.
Why is this multiple imputation low quality?
Given that you are using six cases [records] and three variables, the quality of your imputation will be quite low. To see why this will be the case, remember that multiple imputation works by filling
Why is this multiple imputation low quality? Given that you are using six cases [records] and three variables, the quality of your imputation will be quite low. To see why this will be the case, remember that multiple imputation works by filling in missing values with plausible imputed values. These imputed values are calculated in $m$ separate datasets (I will return to how these imputed values are derived later in this answer). The imputed values will vary slightly from dataset to dataset. Thus, given a statistical quantity of interest $q$ (e.g., a mean, a regression coefficient, etc), one can use the $m$ datasets to estimate the average standard error for $q$ within the $m$ datasets (a quantity that I will call the within-imputation variance, or $\bar{U}$) and the degree to which $q$ varies across the $m$ datasets (a quantity that I will call the between-imputation variance, or $B$). The relationship between imputation quality, $B$, and $\bar{U}$ One can use the within-imputation variance $\bar{U}$ and the between-imputation variance $B$ to derive an estimate of the degree to which an imputed estimate of a statistical quantity has been influenced by missing information. Of course, the more information has been lost, the poorer the quality of the imputation. The estimate of information lost to missingness is labeled $\gamma$, and is given by the following formula: $$\gamma = \frac{r + \frac{2}{df + 3}}{r + 1}$$ $r$ in this formula is a ratio of the between-imputation variance $B$ to the within-imputation-variance $\bar{U}$: $$r = \frac{(1 + \frac1m)B}{\bar{U}}$$ Thus, high values of $B$ result in high values of $r$, which in turn will result in high values of $\gamma$. A high value of $\gamma$, in turn, indicates more information lost due to missing data and a poorer quality imputation. $df$ in the formula for $\gamma$ is also a function of $B$ and $\bar{U}$. Specifically, $df$ is estimated by $$df = (m - 1)\left(1 + \frac{m\bar{U}}{(m + 1)B}\right)^2$$ Thus, in addition to increasing the ratio of between-imputation variance to within-imputation variance, increasing $B$ also decreases $df$. This will result in a higher value of $\gamma$, indicating more information lost to missingness and a poorer quality imputation. In sum, higher values of the between-imputation variance $B$ affect imputation quality in two ways: Higher values of $B$ increase the ratio of the variance between imputations to the variance within imputations, decreasing imputation quality Higher values of $B$ decrease the available degrees of freedom, decreasing imputation quality The relationship between the number of cases and $B$ Given two otherwise similar datasets, a dataset with a smaller number of cases will have a larger between-imputation variance $B$. This will occur because, as I describe above, the between-imputation variance is computed by computing a statistical quantity of interest $q$ within each of $m$ imputed datasets and computing the degree to which $q$ varies across each of the $m$ datasets. If a given dataset has a higher quantity of cases but a similar quantity of missing values as another, a smaller proportion of values will be free to vary across each of the $m$ imputed datasets, meaning that there will be lower overall variation in $q$ across the imputed datasets. Thus, in general, increasing the number of cases (or, more precisely, decreasing the proportion of missing values) will increase imputation quality. The relationship between the number of variables and $B$ Given two otherwise similar datasets, a dataset with a larger number of variables will have a smaller between-imputation variance $B$, as long as those extra variables are informative about the missing values. This will occur because, in general, missing values for a given variable are "filled in" by using information from other variables to generate plausible estimates of the missing values (the specific details of how these estimates are generated will vary depending on the MI implementation you're using). More information in the form of extra variables will result in more stable imputed values, resulting in less variation in statistical quantity of interest $q$ across each of the $m$ imputed datasets. Thus, in general, increasing the number of variables available in a dataset will increase imputation quality, as long as those extra variables are informative about the missing values. References Rubin, D. B. (1996). Multiple imputation after 18+ years. Journal of the American Statistical Association, 91, 473-489. Schafer, J. L. (1999). Multiple imputation: A primer. Statistical Methods in Medical Research, 8, 3-15.
Why is this multiple imputation low quality? Given that you are using six cases [records] and three variables, the quality of your imputation will be quite low. To see why this will be the case, remember that multiple imputation works by filling
25,792
Is f-measure synonymous with accuracy?
First of all, I find "accuracy" sometimes a bit misleading, as it refers to distinct things: The term accuracy in general for evaluating systems or methods (I'm analytical chemist) refers to the bias of predictions, i.e. it answers the question how good predictions are on average. As you know, there are lots of different performance measures that answer different aspects of performance for classifiers. One of them happens to be called accuracy as well. If your paper is not for a machine learning/classification audience, I'recommend to make this distinction very clear. Even for this more specific meaning of accuracy I'd be very explicit of what I call accuracy as again several ways of dealing with class imbalance may occur. Typically, class imbalance is ignored, leading to the well-known $\frac{TP+TN}{all~cases}$ calculation. However, you may also use the average of sensitivity and specificity, which amounts to controlling class imbalance by weighting your average. The F$_1$-score is often introduced as harmonic mean of precision and recall (or positive predictive value and sensitivity). For your question I think it helpful to spell this out a bit further and simplify it: $F_1 = \frac{2 \cdot precision \cdot recall}{precision + recall} = \frac{2 \frac{TP}{all~P} \frac{TP}{all T}}{\frac{TP}{all~P} + \frac{TP}{all T}} = \frac{2 \frac{TP^2}{all~P \cdot all T}}{\frac{TP \cdot all~T}{all~P \cdot all T} + \frac{TP \cdot all~P}{all~P \cdot all T}} = \frac{2~TP^2}{TP \cdot all~T + TP \cdot all~P} = \frac{2~TP}{all~T + all~P} $ The last expression is not a fraction of anything that I can think of as a certain group of test cases. In particular, a (heavy) overlap between the TRUE and the POSITIVE cases is expected. This would keep me from expressing an F-score as percentage as that kind of implies a proportion of cases. Actually, I think I'd warn the reader that F-score does not have such an interpretation. What makes me particularly uneasy combining these measure is that when we look at sensitivity = precision and specificity on the one hand, and positive and negative predictive values (PPV = recall) at the other hand, they are conditional probabilities, where sensitivity/precision and specificity are conditioned on the true class membership and the predictive values and recall are conditioned on the predicted class membership. To get the latter from the former, we can use Bayes rule and the prior probabilities of the classes. So F-score(s) average (by harmonic mean, but my point would stay the same with arithmetic or geometric mean) together figures of merit that are so-to-speak before and after the Bayes rule. I.e., we produce a metric that is neither completely here nor there.
Is f-measure synonymous with accuracy?
First of all, I find "accuracy" sometimes a bit misleading, as it refers to distinct things: The term accuracy in general for evaluating systems or methods (I'm analytical chemist) refers to the bias
Is f-measure synonymous with accuracy? First of all, I find "accuracy" sometimes a bit misleading, as it refers to distinct things: The term accuracy in general for evaluating systems or methods (I'm analytical chemist) refers to the bias of predictions, i.e. it answers the question how good predictions are on average. As you know, there are lots of different performance measures that answer different aspects of performance for classifiers. One of them happens to be called accuracy as well. If your paper is not for a machine learning/classification audience, I'recommend to make this distinction very clear. Even for this more specific meaning of accuracy I'd be very explicit of what I call accuracy as again several ways of dealing with class imbalance may occur. Typically, class imbalance is ignored, leading to the well-known $\frac{TP+TN}{all~cases}$ calculation. However, you may also use the average of sensitivity and specificity, which amounts to controlling class imbalance by weighting your average. The F$_1$-score is often introduced as harmonic mean of precision and recall (or positive predictive value and sensitivity). For your question I think it helpful to spell this out a bit further and simplify it: $F_1 = \frac{2 \cdot precision \cdot recall}{precision + recall} = \frac{2 \frac{TP}{all~P} \frac{TP}{all T}}{\frac{TP}{all~P} + \frac{TP}{all T}} = \frac{2 \frac{TP^2}{all~P \cdot all T}}{\frac{TP \cdot all~T}{all~P \cdot all T} + \frac{TP \cdot all~P}{all~P \cdot all T}} = \frac{2~TP^2}{TP \cdot all~T + TP \cdot all~P} = \frac{2~TP}{all~T + all~P} $ The last expression is not a fraction of anything that I can think of as a certain group of test cases. In particular, a (heavy) overlap between the TRUE and the POSITIVE cases is expected. This would keep me from expressing an F-score as percentage as that kind of implies a proportion of cases. Actually, I think I'd warn the reader that F-score does not have such an interpretation. What makes me particularly uneasy combining these measure is that when we look at sensitivity = precision and specificity on the one hand, and positive and negative predictive values (PPV = recall) at the other hand, they are conditional probabilities, where sensitivity/precision and specificity are conditioned on the true class membership and the predictive values and recall are conditioned on the predicted class membership. To get the latter from the former, we can use Bayes rule and the prior probabilities of the classes. So F-score(s) average (by harmonic mean, but my point would stay the same with arithmetic or geometric mean) together figures of merit that are so-to-speak before and after the Bayes rule. I.e., we produce a metric that is neither completely here nor there.
Is f-measure synonymous with accuracy? First of all, I find "accuracy" sometimes a bit misleading, as it refers to distinct things: The term accuracy in general for evaluating systems or methods (I'm analytical chemist) refers to the bias
25,793
Is f-measure synonymous with accuracy?
Quick Answer: No, F-measure formula does not consist of TN factor, and it is useful on retrieve problems (doc). Thus, it's (F-measure) the correct approach to evaluate the imbalanced datasets or in retrieval problems case instead of accuracy and ROC. Accuracy = (TP+TN) / (TP+FP+FN+TN) F1_Score = 2*(Recall * Precision) / (Recall + Precision) # or F1_Score = 2*TP / (2*TP + FP + FN) [NOTE]: Precision = TP / (TP+FP) Recall = TP / (TP+FN)
Is f-measure synonymous with accuracy?
Quick Answer: No, F-measure formula does not consist of TN factor, and it is useful on retrieve problems (doc). Thus, it's (F-measure) the correct approach to evaluate the imbalanced datasets or in re
Is f-measure synonymous with accuracy? Quick Answer: No, F-measure formula does not consist of TN factor, and it is useful on retrieve problems (doc). Thus, it's (F-measure) the correct approach to evaluate the imbalanced datasets or in retrieval problems case instead of accuracy and ROC. Accuracy = (TP+TN) / (TP+FP+FN+TN) F1_Score = 2*(Recall * Precision) / (Recall + Precision) # or F1_Score = 2*TP / (2*TP + FP + FN) [NOTE]: Precision = TP / (TP+FP) Recall = TP / (TP+FN)
Is f-measure synonymous with accuracy? Quick Answer: No, F-measure formula does not consist of TN factor, and it is useful on retrieve problems (doc). Thus, it's (F-measure) the correct approach to evaluate the imbalanced datasets or in re
25,794
How does the proof of Rejection Sampling make sense?
You should think of the algorithm as producing draws from a random variable, to show that the algorithm works, it suffices to show that the algorithm draws from the random variable you want it to. Let $X$ and $Y$ be scalar random variables with pdfs $f_X$ and $f_Y$ respectively, where $Y$ is something we already know how to sample from. We can also know that we can bound $f_X$ by $Mf_Y$ where $M\ge1$. We now form a new random variable $A$ where $A | y \sim \text{Bernoulli } \left (\frac{f_X(y)}{Mf_Y(y)}\right )$, this takes the value $1$ with probability $\frac{f_X(y)}{Mf_Y(y)} $ and $0$ otherwise. This represents the algorithm 'accepting' a draw from $Y$. Now we run the algorithm and collect all the draws from $Y$ that are accepted, lets call this random variable $Z = Y|A=1$. To show that $Z \equiv X$, for any event $E$, we must show that $P(Z \in E) =P(X \in E)$. So let's try that, first use Bayes' rule: $P(Z \in E) = P(Y \in E | A =1) = \frac{P(Y \in E \& A=1)}{P(A=1)}$, and the top part we write as \begin{align*}P(Y \in E \& A=1) &= \int_E f_{Y, A}(y,1) \, dy \\ &= \int_E f_{A|Y}(1,y)f_Y(y) \, dy =\int_E f_Y(y) \frac{f_X(y)}{Mf_Y(y)} \, dy =\frac{P(X \in E)}{M}.\end{align*} And then the bottom part is simply $P(A=1) = \int_{-\infty}^{\infty}f_{Y,A}(y,1) \, dy = \frac{1}{M}$, by the same reasoning as above, setting $E=(-\infty, +\infty)$. And these combine to give $P(X \in E)$, which is what we wanted, $Z \equiv X$. That is how the algorithm works, but at the end of your question you seem to be concerned about a more general idea, that is when does an empirical distribution converge to the distribution sampled from? This is a general phenomenon concerning any sampling whatsoever if I understand you correctly. In this case, let $X_1, \dots, X_n$ be iid random variables all with distribution $\equiv X$. Then for any event $E$, $\frac{\sum_{i=1}^n1_{X_i \in E}}{n}$ has expectation $P(X \in E)$ by the linearity of expectation. Furthermore, given suitable assumptions you could use the strong law of large numbers to show that the empirical probability converges almost surely to the true probability.
How does the proof of Rejection Sampling make sense?
You should think of the algorithm as producing draws from a random variable, to show that the algorithm works, it suffices to show that the algorithm draws from the random variable you want it to. Let
How does the proof of Rejection Sampling make sense? You should think of the algorithm as producing draws from a random variable, to show that the algorithm works, it suffices to show that the algorithm draws from the random variable you want it to. Let $X$ and $Y$ be scalar random variables with pdfs $f_X$ and $f_Y$ respectively, where $Y$ is something we already know how to sample from. We can also know that we can bound $f_X$ by $Mf_Y$ where $M\ge1$. We now form a new random variable $A$ where $A | y \sim \text{Bernoulli } \left (\frac{f_X(y)}{Mf_Y(y)}\right )$, this takes the value $1$ with probability $\frac{f_X(y)}{Mf_Y(y)} $ and $0$ otherwise. This represents the algorithm 'accepting' a draw from $Y$. Now we run the algorithm and collect all the draws from $Y$ that are accepted, lets call this random variable $Z = Y|A=1$. To show that $Z \equiv X$, for any event $E$, we must show that $P(Z \in E) =P(X \in E)$. So let's try that, first use Bayes' rule: $P(Z \in E) = P(Y \in E | A =1) = \frac{P(Y \in E \& A=1)}{P(A=1)}$, and the top part we write as \begin{align*}P(Y \in E \& A=1) &= \int_E f_{Y, A}(y,1) \, dy \\ &= \int_E f_{A|Y}(1,y)f_Y(y) \, dy =\int_E f_Y(y) \frac{f_X(y)}{Mf_Y(y)} \, dy =\frac{P(X \in E)}{M}.\end{align*} And then the bottom part is simply $P(A=1) = \int_{-\infty}^{\infty}f_{Y,A}(y,1) \, dy = \frac{1}{M}$, by the same reasoning as above, setting $E=(-\infty, +\infty)$. And these combine to give $P(X \in E)$, which is what we wanted, $Z \equiv X$. That is how the algorithm works, but at the end of your question you seem to be concerned about a more general idea, that is when does an empirical distribution converge to the distribution sampled from? This is a general phenomenon concerning any sampling whatsoever if I understand you correctly. In this case, let $X_1, \dots, X_n$ be iid random variables all with distribution $\equiv X$. Then for any event $E$, $\frac{\sum_{i=1}^n1_{X_i \in E}}{n}$ has expectation $P(X \in E)$ by the linearity of expectation. Furthermore, given suitable assumptions you could use the strong law of large numbers to show that the empirical probability converges almost surely to the true probability.
How does the proof of Rejection Sampling make sense? You should think of the algorithm as producing draws from a random variable, to show that the algorithm works, it suffices to show that the algorithm draws from the random variable you want it to. Let
25,795
How does the proof of Rejection Sampling make sense?
First, keep in mind that a complete procedure of the rejection sampling method only produces a single random variable. When some $x_i$ is accepted, the procedure stops, and there is no $x_{i+1}$ anymore. If you want multiple random variables, just repeat the procedure multiple times. In some textbook, they denote the event of acceptance by $A$ and calculate the probability $$ \begin{aligned} P(A) =& \int_{-\infty}^{\infty}dx\int_0^{\frac{f(x)}{cg(x)}}g(x)du \\ =& \int_{-\infty}^{\infty}\frac{1}{c}f(x)dx \\ =& \frac{1}{c}. \end{aligned} $$ And $$ \begin{aligned} f_X(x|A) =& \frac{f_X(x) \cdot P(A|x)}{P(A)}\\ =& \frac{g(x) \cdot \frac{f(x)}{cg(x)}}{\frac{1}{c}} \\ =& f(x). \end{aligned} $$ The confusing thing is that the acceptance $A$ here appears to be acceptance of a single sample of $x_i$, but the whole procedure may reject multiple $x_i$'s. Yes, a more rigorous proof should consider the probability of acceptance at different steps. Let $X_i$ denote the $i$th sample, $f_{X_i}$ denote the probability density function of $X_i$, $A_i$ denote the $i$th acceptance, and $X_\infty$ denote the final accepted value. Then the probability density function of $X_\infty$ is $$ f_{X_\infty}(x) = P(A_1) f_{X_1}(x|A_1) + P(A_2) f_{X_2}(x|A_2) + \dots. $$ $P(A_1)$ is $\frac{1}{c}$ and $f_{X_1}(x|A_1)$ is $f(x)$ as calculated before. Note $P(A_2)$ is $\left(1-\frac{1}{c}\right)\frac{1}{c}$ where $1-\frac{1}{c}$ is the probability of the rejection of $X_1$ since only when $X_1$ is rejected have we a chance to choose an $X_2$. And $f_{X_2}(x|A_2)$ is $f(x)$ too because the second step is not affected by previous steps, its probability should be the same as the first step. If this explanation doesn't convince you, we can also work it out rigorously. Be careful $X_2$ is not defined when $X_1$ is accepted (or you can define it to be an arbitrary number when $X_1$ is accepted if undefined value makes you uncomfortable), so for probabilities concerning $X_2$, only conditional probabilities given $A_1^c$ or subsets of $A_1^c$ make sense. Now $$ \begin{aligned} f_{X_2}(x|A_2) =& \frac{P(A_1^c)f_{X_2}(x|A_1^c)P(A_2|X_2=x)}{P(A_2)} \\ =& \frac{P(A_1^c)f_{X_2}(x|A_1^c)P(A_2|X_2=x)}{P(A_1^c)P(A_2|A_1^c)} \\ =& \frac{f_{X_2}(x|A_1^c)P(A_2|X_2=x)}{P(A_2|A_1^c)} \\ =& \frac{g(x) \cdot \frac{f(x)}{cg(x)}}{\frac{1}{c}} \\ =& f(x). \end{aligned} $$ So $$ \begin{aligned} f_{X_\infty}(x) =& P(A_1) f(x) + P(A_2) f(x) + \dots \\ =& (P(A_1) + P(A_2) + \dots) f(x) \\ =& \left(\frac{1}{c} + \left(1-\frac{1}{c}\right)\frac{1}{c} + \left(1-\frac{1}{c}\right)^2\frac{1}{c} + \dots\right) f(x) \\ =& f(x). \end{aligned} $$ That is the desired result. Note $P(A_1) + P(A_2) + \dots$ = 1 has an intuitive meaning, that is eventually one sample will be accepted at some step $i$.
How does the proof of Rejection Sampling make sense?
First, keep in mind that a complete procedure of the rejection sampling method only produces a single random variable. When some $x_i$ is accepted, the procedure stops, and there is no $x_{i+1}$ anymo
How does the proof of Rejection Sampling make sense? First, keep in mind that a complete procedure of the rejection sampling method only produces a single random variable. When some $x_i$ is accepted, the procedure stops, and there is no $x_{i+1}$ anymore. If you want multiple random variables, just repeat the procedure multiple times. In some textbook, they denote the event of acceptance by $A$ and calculate the probability $$ \begin{aligned} P(A) =& \int_{-\infty}^{\infty}dx\int_0^{\frac{f(x)}{cg(x)}}g(x)du \\ =& \int_{-\infty}^{\infty}\frac{1}{c}f(x)dx \\ =& \frac{1}{c}. \end{aligned} $$ And $$ \begin{aligned} f_X(x|A) =& \frac{f_X(x) \cdot P(A|x)}{P(A)}\\ =& \frac{g(x) \cdot \frac{f(x)}{cg(x)}}{\frac{1}{c}} \\ =& f(x). \end{aligned} $$ The confusing thing is that the acceptance $A$ here appears to be acceptance of a single sample of $x_i$, but the whole procedure may reject multiple $x_i$'s. Yes, a more rigorous proof should consider the probability of acceptance at different steps. Let $X_i$ denote the $i$th sample, $f_{X_i}$ denote the probability density function of $X_i$, $A_i$ denote the $i$th acceptance, and $X_\infty$ denote the final accepted value. Then the probability density function of $X_\infty$ is $$ f_{X_\infty}(x) = P(A_1) f_{X_1}(x|A_1) + P(A_2) f_{X_2}(x|A_2) + \dots. $$ $P(A_1)$ is $\frac{1}{c}$ and $f_{X_1}(x|A_1)$ is $f(x)$ as calculated before. Note $P(A_2)$ is $\left(1-\frac{1}{c}\right)\frac{1}{c}$ where $1-\frac{1}{c}$ is the probability of the rejection of $X_1$ since only when $X_1$ is rejected have we a chance to choose an $X_2$. And $f_{X_2}(x|A_2)$ is $f(x)$ too because the second step is not affected by previous steps, its probability should be the same as the first step. If this explanation doesn't convince you, we can also work it out rigorously. Be careful $X_2$ is not defined when $X_1$ is accepted (or you can define it to be an arbitrary number when $X_1$ is accepted if undefined value makes you uncomfortable), so for probabilities concerning $X_2$, only conditional probabilities given $A_1^c$ or subsets of $A_1^c$ make sense. Now $$ \begin{aligned} f_{X_2}(x|A_2) =& \frac{P(A_1^c)f_{X_2}(x|A_1^c)P(A_2|X_2=x)}{P(A_2)} \\ =& \frac{P(A_1^c)f_{X_2}(x|A_1^c)P(A_2|X_2=x)}{P(A_1^c)P(A_2|A_1^c)} \\ =& \frac{f_{X_2}(x|A_1^c)P(A_2|X_2=x)}{P(A_2|A_1^c)} \\ =& \frac{g(x) \cdot \frac{f(x)}{cg(x)}}{\frac{1}{c}} \\ =& f(x). \end{aligned} $$ So $$ \begin{aligned} f_{X_\infty}(x) =& P(A_1) f(x) + P(A_2) f(x) + \dots \\ =& (P(A_1) + P(A_2) + \dots) f(x) \\ =& \left(\frac{1}{c} + \left(1-\frac{1}{c}\right)\frac{1}{c} + \left(1-\frac{1}{c}\right)^2\frac{1}{c} + \dots\right) f(x) \\ =& f(x). \end{aligned} $$ That is the desired result. Note $P(A_1) + P(A_2) + \dots$ = 1 has an intuitive meaning, that is eventually one sample will be accepted at some step $i$.
How does the proof of Rejection Sampling make sense? First, keep in mind that a complete procedure of the rejection sampling method only produces a single random variable. When some $x_i$ is accepted, the procedure stops, and there is no $x_{i+1}$ anymo
25,796
Confidence interval for cross-validated classification accuracy
Influence of instability in the predictions of different surrogate models However, one of the assumptions behind the binomial analysis is the same probability of success for each trial, and I'm not sure if the method behind the classification of 'right' or 'wrong' in the cross-validation can be considered to have the same probability of success. Well, usually that equvalence is an assumption that is also needed to allow you to pool the results of the different surrogate models. In practice, your intuition that this assumption may be violated is often true. But you can measure whether this is the case. That is where I find iterated cross validation helpful: The stability of predictions for the same case by different surrogate models lets you judge whether the models are equivalent (stable predictions) or not. Here's a scheme of iterated (aka repeated) $k$-fold cross validation: Classes are red and blue. The circles on the right symbolize the predictions. In each iteration, each sample is predicted exactly once. Usually, the grand mean is used as performance estimate, implicitly assuming that the performance of the $i \cdot k$ surrogate models is equal. If you look for each sample at the predictions made by different surrogate models (i.e. across the columns), you can see how stable the predictions are for this sample. You can also calculate the performance for each iteration (block of 3 rows in the drawing). Any variance between these means that the assumption that surrogate models are equivalent (to each other and furthermore to the "grand model" built on all cases) is not met. But this also tells you how much instability you have. For the binomial proportion I think as long as the true performance is the same (i.e. independent whether always the same cases are wrongly predicted or whether the same number but different cases are wrongly predicted). I don't know whether one could sensibly assume a particular distribution for the performance of the surrogate models. But I think it is in any case an advantage over the currently common reporting of classification errors if you report that instability at all. I think you could report this variance and argue that as $k$ surrogate models were pooled already for each of the iterations, the instability variance is roughly $k$ times the observed variance between the iterations. I usually have to work with far less than 120 independent cases, so I put very strong regularization on my models. I'm then usually able to show that the instability variance is $\ll$ than the finite test sample size variance. (And I think this is sensible for the modeling as humans are biased towards detecting patterns and thus drawn towards building too complex models and thus overfitting). I usually report percentiles of the observed instability variance over the iterations (and $n$, $k$ and $i$) and binomial confidence intervals on the average observed performance for the finite test sample size. The drawing is a newer version of fig. 5 in this paper: Beleites, C. & Salzer, R.: Assessing and improving the stability of chemometric models in small sample size situations, Anal Bioanal Chem, 390, 1261-1271 (2008). DOI: 10.1007/s00216-007-1818-6 Note that when we wrote the paper I had not yet fully realized the different sources of variance which I explained here - keep that in mind. I therefore think that the argumentation for effective sample size estimation given there is not correct, even though the application conclusion that different tissue types within each patient contribute about as much overall information as a new patient with a given tissue type is probably still valid (I have a totally different type of evidence which also points that way). However, I'm not yet completely sure about this (nor how to do it better and thus be able to check), and this issue is unrelated to your question. Which performance to use for the binomial confidence interval? So far, I've been using the average observed performance. You could also use the worst observed performance: the closer the observed performance is to 0.5, the larger the variance and thus the confidence interval. Thus, confidence intervals of the observed performance nearest to 0.5 give you some conservative "safety margin". Note that some methods to calculate binomial confidence intervals work also if the observed number of successes is not an integer. I use the "integration of the Bayesian posterior probability" as described in Ross, T. D.: Accurate confidence intervals for binomial proportion and Poisson rate estimation, Comput Biol Med, 33, 509-531 (2003). DOI: 10.1016/S0010-4825(03)00019-2 (I don't know for Matlab, but in R you can use binom::binom.bayes with both shape parameters set to 1). These thoughts apply to predictions models built on this training data set yield for unknown new cases. If you need to generatlize to other training data sets drawn from the same population of cases, you'd need to estimate how much models trained on a new training samples of size $n$ vary. (I have no idea how to do that other than by getting "physically" new training data sets) See also: Bengio, Y. and Grandvalet, Y.: No Unbiased Estimator of the Variance of K-Fold Cross-Validation, Journal of Machine Learning Research, 2004, 5, 1089-1105. (Thinking more about these things is on my research todo-list..., but as I'm coming from experimental science I like to complement the theoretical and simulation conclusions with experimental data - which is difficult here as I'd need a large set of independent cases for reference testing) Update: is it justified to assume a biomial distribution? I see the k-fold CV a like the following coin-throwing experiment: instead of throwing one coin a large number of times, $k$ coins produced by the same machine are thrown a smaller number of times. In this picture, I think @Tal points out that the coins are not the same. Which is obviously true. I think what should and what can be done depends on the equivalence assumption for the surrogate models. If there actually is a difference in performance between the surrogate models (coins), the "traditional" assumption that the surrogate models are equivalent does not hold. In that case, not only is the distribution not binomial (as I said above, I have no idea what distribution to use: it should be the sum of binomials for each surrogate model / each coin). Note however, that this means that the pooling of the results of the surrogate models is not allowed. So neither is a binomial for $n$ tests a good approximation (I try to improve the approximation by saying we have an additional source of variation: the instability) nor can the average performance be used as point estimate without further justification. If on the other hand the (true) performance of the surrogate is the same, that is when I mean with "the models are equivalent" (one symptom is that the predictions are stable). I think in this case the results of all surrogate models can be pooled, and a binomial distribution for all $n$ tests should be OK to use: I think in that case we are justified to approximate the true $p$s of the surrogate models to be equal, and thus describe the test as equivalent to the throwing of one coin $n$ times.
Confidence interval for cross-validated classification accuracy
Influence of instability in the predictions of different surrogate models However, one of the assumptions behind the binomial analysis is the same probability of success for each trial, and I'm not s
Confidence interval for cross-validated classification accuracy Influence of instability in the predictions of different surrogate models However, one of the assumptions behind the binomial analysis is the same probability of success for each trial, and I'm not sure if the method behind the classification of 'right' or 'wrong' in the cross-validation can be considered to have the same probability of success. Well, usually that equvalence is an assumption that is also needed to allow you to pool the results of the different surrogate models. In practice, your intuition that this assumption may be violated is often true. But you can measure whether this is the case. That is where I find iterated cross validation helpful: The stability of predictions for the same case by different surrogate models lets you judge whether the models are equivalent (stable predictions) or not. Here's a scheme of iterated (aka repeated) $k$-fold cross validation: Classes are red and blue. The circles on the right symbolize the predictions. In each iteration, each sample is predicted exactly once. Usually, the grand mean is used as performance estimate, implicitly assuming that the performance of the $i \cdot k$ surrogate models is equal. If you look for each sample at the predictions made by different surrogate models (i.e. across the columns), you can see how stable the predictions are for this sample. You can also calculate the performance for each iteration (block of 3 rows in the drawing). Any variance between these means that the assumption that surrogate models are equivalent (to each other and furthermore to the "grand model" built on all cases) is not met. But this also tells you how much instability you have. For the binomial proportion I think as long as the true performance is the same (i.e. independent whether always the same cases are wrongly predicted or whether the same number but different cases are wrongly predicted). I don't know whether one could sensibly assume a particular distribution for the performance of the surrogate models. But I think it is in any case an advantage over the currently common reporting of classification errors if you report that instability at all. I think you could report this variance and argue that as $k$ surrogate models were pooled already for each of the iterations, the instability variance is roughly $k$ times the observed variance between the iterations. I usually have to work with far less than 120 independent cases, so I put very strong regularization on my models. I'm then usually able to show that the instability variance is $\ll$ than the finite test sample size variance. (And I think this is sensible for the modeling as humans are biased towards detecting patterns and thus drawn towards building too complex models and thus overfitting). I usually report percentiles of the observed instability variance over the iterations (and $n$, $k$ and $i$) and binomial confidence intervals on the average observed performance for the finite test sample size. The drawing is a newer version of fig. 5 in this paper: Beleites, C. & Salzer, R.: Assessing and improving the stability of chemometric models in small sample size situations, Anal Bioanal Chem, 390, 1261-1271 (2008). DOI: 10.1007/s00216-007-1818-6 Note that when we wrote the paper I had not yet fully realized the different sources of variance which I explained here - keep that in mind. I therefore think that the argumentation for effective sample size estimation given there is not correct, even though the application conclusion that different tissue types within each patient contribute about as much overall information as a new patient with a given tissue type is probably still valid (I have a totally different type of evidence which also points that way). However, I'm not yet completely sure about this (nor how to do it better and thus be able to check), and this issue is unrelated to your question. Which performance to use for the binomial confidence interval? So far, I've been using the average observed performance. You could also use the worst observed performance: the closer the observed performance is to 0.5, the larger the variance and thus the confidence interval. Thus, confidence intervals of the observed performance nearest to 0.5 give you some conservative "safety margin". Note that some methods to calculate binomial confidence intervals work also if the observed number of successes is not an integer. I use the "integration of the Bayesian posterior probability" as described in Ross, T. D.: Accurate confidence intervals for binomial proportion and Poisson rate estimation, Comput Biol Med, 33, 509-531 (2003). DOI: 10.1016/S0010-4825(03)00019-2 (I don't know for Matlab, but in R you can use binom::binom.bayes with both shape parameters set to 1). These thoughts apply to predictions models built on this training data set yield for unknown new cases. If you need to generatlize to other training data sets drawn from the same population of cases, you'd need to estimate how much models trained on a new training samples of size $n$ vary. (I have no idea how to do that other than by getting "physically" new training data sets) See also: Bengio, Y. and Grandvalet, Y.: No Unbiased Estimator of the Variance of K-Fold Cross-Validation, Journal of Machine Learning Research, 2004, 5, 1089-1105. (Thinking more about these things is on my research todo-list..., but as I'm coming from experimental science I like to complement the theoretical and simulation conclusions with experimental data - which is difficult here as I'd need a large set of independent cases for reference testing) Update: is it justified to assume a biomial distribution? I see the k-fold CV a like the following coin-throwing experiment: instead of throwing one coin a large number of times, $k$ coins produced by the same machine are thrown a smaller number of times. In this picture, I think @Tal points out that the coins are not the same. Which is obviously true. I think what should and what can be done depends on the equivalence assumption for the surrogate models. If there actually is a difference in performance between the surrogate models (coins), the "traditional" assumption that the surrogate models are equivalent does not hold. In that case, not only is the distribution not binomial (as I said above, I have no idea what distribution to use: it should be the sum of binomials for each surrogate model / each coin). Note however, that this means that the pooling of the results of the surrogate models is not allowed. So neither is a binomial for $n$ tests a good approximation (I try to improve the approximation by saying we have an additional source of variation: the instability) nor can the average performance be used as point estimate without further justification. If on the other hand the (true) performance of the surrogate is the same, that is when I mean with "the models are equivalent" (one symptom is that the predictions are stable). I think in this case the results of all surrogate models can be pooled, and a binomial distribution for all $n$ tests should be OK to use: I think in that case we are justified to approximate the true $p$s of the surrogate models to be equal, and thus describe the test as equivalent to the throwing of one coin $n$ times.
Confidence interval for cross-validated classification accuracy Influence of instability in the predictions of different surrogate models However, one of the assumptions behind the binomial analysis is the same probability of success for each trial, and I'm not s
25,797
Confidence interval for cross-validated classification accuracy
I think your idea of repeating cross-validation many times is right on the mark. Repeat your CV let's say 1000 times, each time splitting your data into 10 parts (for 10-fold CV) in a different way (do not shuffle the labels). You will get 1000 estimations of the classification accuracy. Of course you will be reusing the same data, so these 1000 estimations are not going to be independent. But this is akin to bootstrap procedure: you can take standard deviation over these accuracies as the standard error of the mean of your overall accuracy estimator. Or a 95% percentile interval as the 95% confidence interval. Alternatively, you can combine cross-validation loop and the bootstrap loop, and simply select random (maybe stratified random) 10% of your data as a test set, and do this 1000 times. The same reasoning as above applies here as well. However, this will result in higher variance over repetitions, so I think the above procedure is better. If your misclassification rate is 0.00, your classifier makes zero errors and if this happens on each bootstrap iteration, you will get zero wide confidence interval. But this would simply mean that your classifier is pretty much perfect, so good for you.
Confidence interval for cross-validated classification accuracy
I think your idea of repeating cross-validation many times is right on the mark. Repeat your CV let's say 1000 times, each time splitting your data into 10 parts (for 10-fold CV) in a different way (d
Confidence interval for cross-validated classification accuracy I think your idea of repeating cross-validation many times is right on the mark. Repeat your CV let's say 1000 times, each time splitting your data into 10 parts (for 10-fold CV) in a different way (do not shuffle the labels). You will get 1000 estimations of the classification accuracy. Of course you will be reusing the same data, so these 1000 estimations are not going to be independent. But this is akin to bootstrap procedure: you can take standard deviation over these accuracies as the standard error of the mean of your overall accuracy estimator. Or a 95% percentile interval as the 95% confidence interval. Alternatively, you can combine cross-validation loop and the bootstrap loop, and simply select random (maybe stratified random) 10% of your data as a test set, and do this 1000 times. The same reasoning as above applies here as well. However, this will result in higher variance over repetitions, so I think the above procedure is better. If your misclassification rate is 0.00, your classifier makes zero errors and if this happens on each bootstrap iteration, you will get zero wide confidence interval. But this would simply mean that your classifier is pretty much perfect, so good for you.
Confidence interval for cross-validated classification accuracy I think your idea of repeating cross-validation many times is right on the mark. Repeat your CV let's say 1000 times, each time splitting your data into 10 parts (for 10-fold CV) in a different way (d
25,798
Confidence interval for cross-validated classification accuracy
Classification error is both discontinuous and an improper scoring rule. It has low precision, and optimizing it selects on the wrong features and gives them the wrong weights.
Confidence interval for cross-validated classification accuracy
Classification error is both discontinuous and an improper scoring rule. It has low precision, and optimizing it selects on the wrong features and gives them the wrong weights.
Confidence interval for cross-validated classification accuracy Classification error is both discontinuous and an improper scoring rule. It has low precision, and optimizing it selects on the wrong features and gives them the wrong weights.
Confidence interval for cross-validated classification accuracy Classification error is both discontinuous and an improper scoring rule. It has low precision, and optimizing it selects on the wrong features and gives them the wrong weights.
25,799
Simple linear regression fit manually via matrix equations does not match lm() output
You've made two mistakes in your R code for b. solve is used for matrix inversion. Raising X to the $-1$ power inverts each element of X, which can occasionally be useful, but is not what we want here. R uses the operator %*% for matrix multiplication. Otherwise, it does element-wise multiplication and requires your arrays to be conformable according to R's handling of vectors. Again, occasionally useful. This is all explained in more detail in the R documentation, or the nigh-uncountable intro to R materials online, such as this one. b<-solve(t(X)%*%X)%*%t(X)%*%y is the literal representation of the normal equations, while b<-solve(crossprod(X), crossprod(X,y)) is faster and more idiomatic, and matches the output of lm(). But you definitely don't want to explicitly compute the normal equations directly for numerical reasons (and R won't warn you until you lose all significant figures). The lm method uses QR decomposition by default, which is more numerically stable. If you apply the correct "hand cranked" computation and it still differs from the R output, it's plausibly because of loss of numerical precision due to the explicit inversion of $X^TX$. Don't forget to add a column of $1$ for the intercept!
Simple linear regression fit manually via matrix equations does not match lm() output
You've made two mistakes in your R code for b. solve is used for matrix inversion. Raising X to the $-1$ power inverts each element of X, which can occasionally be useful, but is not what we want her
Simple linear regression fit manually via matrix equations does not match lm() output You've made two mistakes in your R code for b. solve is used for matrix inversion. Raising X to the $-1$ power inverts each element of X, which can occasionally be useful, but is not what we want here. R uses the operator %*% for matrix multiplication. Otherwise, it does element-wise multiplication and requires your arrays to be conformable according to R's handling of vectors. Again, occasionally useful. This is all explained in more detail in the R documentation, or the nigh-uncountable intro to R materials online, such as this one. b<-solve(t(X)%*%X)%*%t(X)%*%y is the literal representation of the normal equations, while b<-solve(crossprod(X), crossprod(X,y)) is faster and more idiomatic, and matches the output of lm(). But you definitely don't want to explicitly compute the normal equations directly for numerical reasons (and R won't warn you until you lose all significant figures). The lm method uses QR decomposition by default, which is more numerically stable. If you apply the correct "hand cranked" computation and it still differs from the R output, it's plausibly because of loss of numerical precision due to the explicit inversion of $X^TX$. Don't forget to add a column of $1$ for the intercept!
Simple linear regression fit manually via matrix equations does not match lm() output You've made two mistakes in your R code for b. solve is used for matrix inversion. Raising X to the $-1$ power inverts each element of X, which can occasionally be useful, but is not what we want her
25,800
Simple linear regression fit manually via matrix equations does not match lm() output
You need to include a column of ones in your matrix x, which corresponds to the intercept. The lm() function does this for you automatically, but you need to add this yourself when you calculate the answer using the normal equations. See this previous question on this site: Using the normal equations to calculate coefficients in multiple linear regression. There is example code which you should be able to copy-and-paste directly. This is a great introductory book that explains why you have to add the column of ones: http://www.amazon.com/Applied-Regression-Models-Edition-Student/dp/0073014664 You will also need to follow the advice given by @user777
Simple linear regression fit manually via matrix equations does not match lm() output
You need to include a column of ones in your matrix x, which corresponds to the intercept. The lm() function does this for you automatically, but you need to add this yourself when you calculate the a
Simple linear regression fit manually via matrix equations does not match lm() output You need to include a column of ones in your matrix x, which corresponds to the intercept. The lm() function does this for you automatically, but you need to add this yourself when you calculate the answer using the normal equations. See this previous question on this site: Using the normal equations to calculate coefficients in multiple linear regression. There is example code which you should be able to copy-and-paste directly. This is a great introductory book that explains why you have to add the column of ones: http://www.amazon.com/Applied-Regression-Models-Edition-Student/dp/0073014664 You will also need to follow the advice given by @user777
Simple linear regression fit manually via matrix equations does not match lm() output You need to include a column of ones in your matrix x, which corresponds to the intercept. The lm() function does this for you automatically, but you need to add this yourself when you calculate the a