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
28,201
Why do we want to maximize the variance in Principal Component Analysis?
One answer is that maximizing variance minimizes squared error – a perhaps more immediately plausible goal. Assume we want to reduce the dimensionality of a number of data points $\mathbf{x}_1,\cdots, \mathbf{x}_N$ to 1 by projecting onto a unit vector $\mathbf{v}$, and we want to keep the squared error small: $$\underset{\mathbf{v}}{\text{minimize}} \, \sum_{n = 1}^N \left\|\mathbf{x}_n - (\mathbf{v}^\top \mathbf{x}_n)\mathbf{v}\right\|^2 \text{ subject to } \|\mathbf{v}\| = 1$$ This optimization problem can be turned into the equivalent problem $$\underset{\mathbf{v}}{\text{maximize}} \,\, \mathbf{v}^\top \mathbf{C}\mathbf{v} \text{ subject to } \|\mathbf{v}\| = 1,$$ where $\mathbf{C} = 1/N\sum_{n = 1}^N \mathbf{x}_n\mathbf{x}_n^\top$. I.e., minimizing squared error is equivalent to maximizing variance along the direction of $\mathbf{v}$ (for centered data). Another answer is that PCA is trying to fit a Gaussian model to the data (squared error and the Gaussian model are closely related). If you tried to fit another model to your data, you'd observe other moments as well (e.g., kurtosis becomes important when fitting a model via independent component analysis).
Why do we want to maximize the variance in Principal Component Analysis?
One answer is that maximizing variance minimizes squared error – a perhaps more immediately plausible goal. Assume we want to reduce the dimensionality of a number of data points $\mathbf{x}_1,\cdots,
Why do we want to maximize the variance in Principal Component Analysis? One answer is that maximizing variance minimizes squared error – a perhaps more immediately plausible goal. Assume we want to reduce the dimensionality of a number of data points $\mathbf{x}_1,\cdots, \mathbf{x}_N$ to 1 by projecting onto a unit vector $\mathbf{v}$, and we want to keep the squared error small: $$\underset{\mathbf{v}}{\text{minimize}} \, \sum_{n = 1}^N \left\|\mathbf{x}_n - (\mathbf{v}^\top \mathbf{x}_n)\mathbf{v}\right\|^2 \text{ subject to } \|\mathbf{v}\| = 1$$ This optimization problem can be turned into the equivalent problem $$\underset{\mathbf{v}}{\text{maximize}} \,\, \mathbf{v}^\top \mathbf{C}\mathbf{v} \text{ subject to } \|\mathbf{v}\| = 1,$$ where $\mathbf{C} = 1/N\sum_{n = 1}^N \mathbf{x}_n\mathbf{x}_n^\top$. I.e., minimizing squared error is equivalent to maximizing variance along the direction of $\mathbf{v}$ (for centered data). Another answer is that PCA is trying to fit a Gaussian model to the data (squared error and the Gaussian model are closely related). If you tried to fit another model to your data, you'd observe other moments as well (e.g., kurtosis becomes important when fitting a model via independent component analysis).
Why do we want to maximize the variance in Principal Component Analysis? One answer is that maximizing variance minimizes squared error – a perhaps more immediately plausible goal. Assume we want to reduce the dimensionality of a number of data points $\mathbf{x}_1,\cdots,
28,202
Why do we want to maximize the variance in Principal Component Analysis?
Another answer is, "we really don't care at all about maximizing variance." After all, once we get the PCs, we multiply them by 10 if we like, we rotate them, etc. For example, if the PC coefficients are very similar, like .25, .30, .27, etc, we simply re-scale the coefficients so that they are close to 1.0 and call the PC a "summate." Clearly, this destroys the variance maximization subject to unit length constraint, calling into question whether variance maximization subject to unit length constraint has any relevance. We provide an alternative to variance maximization in our article, "Teaching Principal Components Using Correlations," recently published in Multivariate Behavioral Research, https://www.ncbi.nlm.nih.gov/pubmed/28715259 Rather than define PCs as linear combinations that maximize variance, we summarize a (somewhat obscure) stream of literature that defines them as linear combinations that maximize average squared correlation between the linear combinations and the original variables. Then neither variance maximization nor the unit length constraint is needed. Re-scaling is allowed (encouraged even), and (non-singular) rotations are also allowed; all provide maximum average squared correlation with the original variables.
Why do we want to maximize the variance in Principal Component Analysis?
Another answer is, "we really don't care at all about maximizing variance." After all, once we get the PCs, we multiply them by 10 if we like, we rotate them, etc. For example, if the PC coefficients
Why do we want to maximize the variance in Principal Component Analysis? Another answer is, "we really don't care at all about maximizing variance." After all, once we get the PCs, we multiply them by 10 if we like, we rotate them, etc. For example, if the PC coefficients are very similar, like .25, .30, .27, etc, we simply re-scale the coefficients so that they are close to 1.0 and call the PC a "summate." Clearly, this destroys the variance maximization subject to unit length constraint, calling into question whether variance maximization subject to unit length constraint has any relevance. We provide an alternative to variance maximization in our article, "Teaching Principal Components Using Correlations," recently published in Multivariate Behavioral Research, https://www.ncbi.nlm.nih.gov/pubmed/28715259 Rather than define PCs as linear combinations that maximize variance, we summarize a (somewhat obscure) stream of literature that defines them as linear combinations that maximize average squared correlation between the linear combinations and the original variables. Then neither variance maximization nor the unit length constraint is needed. Re-scaling is allowed (encouraged even), and (non-singular) rotations are also allowed; all provide maximum average squared correlation with the original variables.
Why do we want to maximize the variance in Principal Component Analysis? Another answer is, "we really don't care at all about maximizing variance." After all, once we get the PCs, we multiply them by 10 if we like, we rotate them, etc. For example, if the PC coefficients
28,203
Why do we want to maximize the variance in Principal Component Analysis?
YAA (yet another answer). The first distribution we encounter is the normal distribution. In many important examples of statistics in use (linear regression, I'm looking at you) some hypothesis of normality is tacit. When statistics is taught, the normal distribution is the taught as the first and foremost example of a continuous distribution. The connection is that the normal distribution is completely characterized by it's mean and variance, which are it's first and second moment. So in any case of trying to understand some distribution in terms of it's moments, using any higher moment won't work sensibly if the normal distribution is among the possible outcomes.
Why do we want to maximize the variance in Principal Component Analysis?
YAA (yet another answer). The first distribution we encounter is the normal distribution. In many important examples of statistics in use (linear regression, I'm looking at you) some hypothesis of n
Why do we want to maximize the variance in Principal Component Analysis? YAA (yet another answer). The first distribution we encounter is the normal distribution. In many important examples of statistics in use (linear regression, I'm looking at you) some hypothesis of normality is tacit. When statistics is taught, the normal distribution is the taught as the first and foremost example of a continuous distribution. The connection is that the normal distribution is completely characterized by it's mean and variance, which are it's first and second moment. So in any case of trying to understand some distribution in terms of it's moments, using any higher moment won't work sensibly if the normal distribution is among the possible outcomes.
Why do we want to maximize the variance in Principal Component Analysis? YAA (yet another answer). The first distribution we encounter is the normal distribution. In many important examples of statistics in use (linear regression, I'm looking at you) some hypothesis of n
28,204
Linear Regression + confounder
You need to adjust X as well as Y for the confounder The first approach (using multiple regression) is always correct. Your second approach is not correct as you have stated it, but can be made nearly correct with a slight change. To make the second approach right, you need to regress both $Y$ and $X$ separately on $Z$. I like to write $Y.Z$ for the residuals from the regression of $Y$ on $Z$ and $X.Z$ for the residuals from the regression of $X$ and $Z$. We can interpret $Y.Z$ as $Y$ adjusted for $Z$ (same as your $R$) and $X.Z$ as $X$ adjusted for $Z$. You can then regress $Y.Z$ on $X.Z$. With this change, the two approaches will give the same regression coefficient and the same residuals. However the second approach will still incorrectly compute the residual degrees of freedom as $n-1$ instead of $n-2$ (where $n$ is the number of data values for each variable). As a result, the test statistic for $X$ from the second approach will be slightly too large and the p-value will be slightly too small. If the number of observations $n$ is large, then the two approaches will converge and this difference won't matter. It's easy to see why the residual degrees of freedom from the second approach won't be quite right. Both approaches regress $Y$ on both $X$ and $Z$. The first approach does it in one step while the second approach does it in two steps. However the second approach "forgets" that $Y.Z$ resulted from a regression on $Z$ and so neglects to subtract the degree of freedom for this variable. The added variable plot Sanford Weisberg (Applied Linear Regression, 1985) used to recommend plotting $Y.Z$ vs $X.Z$ in a scatterplot. This was called an added variable plot, and it gave an effective visual representation of the relationship between $Y$ and $X$ after adjusting for $Z$. If you don't adjust X then you under-estimate the regression coefficient The second approach as you originally stated it, regressing $Y.Z$ on $X$, is too conservative. It will understate the significance of the relationship between $Y$ and $X$ adjusting for $Z$ because it underestimates the size of the regression coefficient. This occurs because you are regressing $Y.Z$ on the whole of $X$ instead of just on the part of $X$ that is independent to $Z$. In the standard formula for the regression coefficient in simple linear regression, the numerator (covariance of $Y.Z$ with $X$) will be correct but the denominator (the variance of $X$) will be too large. The correct covariate $X.Z$ always has a smaller variance than does $X$. To make this precise, your Method 2 will under-estimate the partial regression coefficient for $X$ by a factor of $1-r^2$ where $r$ is the Pearson correlation coefficient between $X$ and $Z$. A numerical example Here is a small numerical example to show that the added variable method represents the regression coefficient of $Y$ on $X$ correctly whereas your second approach (Method 2) can be arbitrarily wrong. First we simulate $X$, $Z$ and $Y$: > set.seed(20180525) > Z <- 10*rnorm(10) > X <- Z+rnorm(10) > Y <- X+Z Here $Y=X+Z$ so the true regression coefficients for $X$ and $Z$ are both 1 and the intercept is 0. Then we form the two residual vectors $R$ (same as my $Y.Z$) and $X.Z$: > R <- Y.Z <- residuals(lm(Y~Z)) > X.Z <- residuals(lm(X~Z)) The full multiple regression with both $X$ and $Y$ as predictors gives the true regression coefficients exactly: > coef(lm(Y~X+Z)) (Intercept) X Z 5.62e-16 1.00e+00 1.00e+00 The added variable approach (Method 3) also gives the coefficient for $X$ exactly correct: > coef(lm(R~X.Z)) (Intercept) X.Z -6.14e-17 1.00e+00 By contrast, your Method 2 finds the regression coefficient to be only 0.01: > coef(lm(R~X)) (Intercept) X 0.00121 0.01170 So your Method 2 underestimates the true effect size by 99%. The under-estimation factor is given by the correlation between $X$ and $Z$: > 1-cor(X,Z)^2 [1] 0.0117 To see all this visually, the added variable plot of $R$ vs $X.Z$ shows a perfect linear relationship with unit slope, representing the true marginal relationship between $Y$ and $X$: By contrast, the plot of $R$ vs the unadjusted $X$ shows no relationship at all. The true relationship has been entirely lost:
Linear Regression + confounder
You need to adjust X as well as Y for the confounder The first approach (using multiple regression) is always correct. Your second approach is not correct as you have stated it, but can be made nearly
Linear Regression + confounder You need to adjust X as well as Y for the confounder The first approach (using multiple regression) is always correct. Your second approach is not correct as you have stated it, but can be made nearly correct with a slight change. To make the second approach right, you need to regress both $Y$ and $X$ separately on $Z$. I like to write $Y.Z$ for the residuals from the regression of $Y$ on $Z$ and $X.Z$ for the residuals from the regression of $X$ and $Z$. We can interpret $Y.Z$ as $Y$ adjusted for $Z$ (same as your $R$) and $X.Z$ as $X$ adjusted for $Z$. You can then regress $Y.Z$ on $X.Z$. With this change, the two approaches will give the same regression coefficient and the same residuals. However the second approach will still incorrectly compute the residual degrees of freedom as $n-1$ instead of $n-2$ (where $n$ is the number of data values for each variable). As a result, the test statistic for $X$ from the second approach will be slightly too large and the p-value will be slightly too small. If the number of observations $n$ is large, then the two approaches will converge and this difference won't matter. It's easy to see why the residual degrees of freedom from the second approach won't be quite right. Both approaches regress $Y$ on both $X$ and $Z$. The first approach does it in one step while the second approach does it in two steps. However the second approach "forgets" that $Y.Z$ resulted from a regression on $Z$ and so neglects to subtract the degree of freedom for this variable. The added variable plot Sanford Weisberg (Applied Linear Regression, 1985) used to recommend plotting $Y.Z$ vs $X.Z$ in a scatterplot. This was called an added variable plot, and it gave an effective visual representation of the relationship between $Y$ and $X$ after adjusting for $Z$. If you don't adjust X then you under-estimate the regression coefficient The second approach as you originally stated it, regressing $Y.Z$ on $X$, is too conservative. It will understate the significance of the relationship between $Y$ and $X$ adjusting for $Z$ because it underestimates the size of the regression coefficient. This occurs because you are regressing $Y.Z$ on the whole of $X$ instead of just on the part of $X$ that is independent to $Z$. In the standard formula for the regression coefficient in simple linear regression, the numerator (covariance of $Y.Z$ with $X$) will be correct but the denominator (the variance of $X$) will be too large. The correct covariate $X.Z$ always has a smaller variance than does $X$. To make this precise, your Method 2 will under-estimate the partial regression coefficient for $X$ by a factor of $1-r^2$ where $r$ is the Pearson correlation coefficient between $X$ and $Z$. A numerical example Here is a small numerical example to show that the added variable method represents the regression coefficient of $Y$ on $X$ correctly whereas your second approach (Method 2) can be arbitrarily wrong. First we simulate $X$, $Z$ and $Y$: > set.seed(20180525) > Z <- 10*rnorm(10) > X <- Z+rnorm(10) > Y <- X+Z Here $Y=X+Z$ so the true regression coefficients for $X$ and $Z$ are both 1 and the intercept is 0. Then we form the two residual vectors $R$ (same as my $Y.Z$) and $X.Z$: > R <- Y.Z <- residuals(lm(Y~Z)) > X.Z <- residuals(lm(X~Z)) The full multiple regression with both $X$ and $Y$ as predictors gives the true regression coefficients exactly: > coef(lm(Y~X+Z)) (Intercept) X Z 5.62e-16 1.00e+00 1.00e+00 The added variable approach (Method 3) also gives the coefficient for $X$ exactly correct: > coef(lm(R~X.Z)) (Intercept) X.Z -6.14e-17 1.00e+00 By contrast, your Method 2 finds the regression coefficient to be only 0.01: > coef(lm(R~X)) (Intercept) X 0.00121 0.01170 So your Method 2 underestimates the true effect size by 99%. The under-estimation factor is given by the correlation between $X$ and $Z$: > 1-cor(X,Z)^2 [1] 0.0117 To see all this visually, the added variable plot of $R$ vs $X.Z$ shows a perfect linear relationship with unit slope, representing the true marginal relationship between $Y$ and $X$: By contrast, the plot of $R$ vs the unadjusted $X$ shows no relationship at all. The true relationship has been entirely lost:
Linear Regression + confounder You need to adjust X as well as Y for the confounder The first approach (using multiple regression) is always correct. Your second approach is not correct as you have stated it, but can be made nearly
28,205
What exactly is a "solver" in optimization?
I suggest a solver is: a software package that incorporates one or more algorithms for finding solutions to one or more classes of problem The classes of problem is part of it. It is a X solver. So I would call Gurobi "a MIP/LP solver". And I would say "Matlab incorperates a QP solver, that it exposes via the Quadprog function.", In this case the actual "QP solver" may or may not exist as a stand alone product. Concorde is a TSP solver Concorde incorporates QSopt, which is a LP solver I think this usage is in line with (for example) the JuMP documentation JuMP is a domain-specific modeling language for mathematical optimization embedded in Julia. It currently supports a number of open-source and commercial solvers (see below) for a variety of problem classes, including linear programming, mixed-integer programming, second-order conic programming, semidefinite programming, and nonlinear programming. Here is a list of things that JuMP calls solvers. None of them are algorithms, all are specific programs
What exactly is a "solver" in optimization?
I suggest a solver is: a software package that incorporates one or more algorithms for finding solutions to one or more classes of problem The classes of problem is part of it. It is a X solver. So
What exactly is a "solver" in optimization? I suggest a solver is: a software package that incorporates one or more algorithms for finding solutions to one or more classes of problem The classes of problem is part of it. It is a X solver. So I would call Gurobi "a MIP/LP solver". And I would say "Matlab incorperates a QP solver, that it exposes via the Quadprog function.", In this case the actual "QP solver" may or may not exist as a stand alone product. Concorde is a TSP solver Concorde incorporates QSopt, which is a LP solver I think this usage is in line with (for example) the JuMP documentation JuMP is a domain-specific modeling language for mathematical optimization embedded in Julia. It currently supports a number of open-source and commercial solvers (see below) for a variety of problem classes, including linear programming, mixed-integer programming, second-order conic programming, semidefinite programming, and nonlinear programming. Here is a list of things that JuMP calls solvers. None of them are algorithms, all are specific programs
What exactly is a "solver" in optimization? I suggest a solver is: a software package that incorporates one or more algorithms for finding solutions to one or more classes of problem The classes of problem is part of it. It is a X solver. So
28,206
What exactly is a "solver" in optimization?
A solver is a routine for finding exact numerical answers for determined systems. For example, when using Newton-Raphson to find root(s). When a system is overdetermined then one generally uses approximate solutions, for example, regression. One would generally not refer to regression as a solver, although, predictably language can be misused, and many routines that are approximate are loosely called solvers. For example, the CUTEr optimization software package contains algorithms at least some of which are for overdetermined systems, and some of which are solvers, so it becomes easy to say, I am downloading a "solver". Both solvers and regression methods are examples of optimization methods.
What exactly is a "solver" in optimization?
A solver is a routine for finding exact numerical answers for determined systems. For example, when using Newton-Raphson to find root(s). When a system is overdetermined then one generally uses approx
What exactly is a "solver" in optimization? A solver is a routine for finding exact numerical answers for determined systems. For example, when using Newton-Raphson to find root(s). When a system is overdetermined then one generally uses approximate solutions, for example, regression. One would generally not refer to regression as a solver, although, predictably language can be misused, and many routines that are approximate are loosely called solvers. For example, the CUTEr optimization software package contains algorithms at least some of which are for overdetermined systems, and some of which are solvers, so it becomes easy to say, I am downloading a "solver". Both solvers and regression methods are examples of optimization methods.
What exactly is a "solver" in optimization? A solver is a routine for finding exact numerical answers for determined systems. For example, when using Newton-Raphson to find root(s). When a system is overdetermined then one generally uses approx
28,207
What exactly is a "solver" in optimization?
I usually hear "solver" used to describe software, meaning it applies to a particular implementation of an algorithm. For example, this seems to apply to most of the SciComp.SE questions tagged solver. Generally the term seems to be reserved for mathematical problems with a "well-defined solution". A unique solution would qualify as "well defined" sufficient, as noted by Sycorax in the comments. (The Gurobi solvers seem to be for problems in this class; for what its worth, Gurobi looks like a suite or library of solvers to me). But I do not think unique is necessary. For example both local and global optimization problems can have well-defined but non-unique solutions (e.g. the function $f[x]=\sin[\pi x]^2$ has global minimum $f[k]=0$ for $k\in\mathbb{Z}$). I disagree with this answer, which seems to be discussing "equation-system solvers" rather than "optimization solvers". For example in linear least squares, the linear algebra problem is over-determined, but the optimization problem is convex, with a unique solution (in non-degenerate cases). Note also that the Wikipedia "solver" page linked in that answer lists "Linear and non-linear optimisation problems, Shortest path problems, Minimum spanning tree problems" among its examples. In response to the comment, I will clarify what I mean in the "regression" case. Given a function $F:\mathbb{R}^n\to\mathbb{R}^m$, a solution to the system of equations specified by $$F[x]=0$$ is a vector $x\in\mathbb{R}^n$ such that all $m$ components of $F[x]$ are zero. Depending on the function $F$, there can be no solutions, a single unique solution, or many solutions (typically infinitely many), depending on the dimension of the null-space of $F$. In the case where $F$ is linear, i.e. $F[x]=Ax-b$ for some $A\in\mathbb{R}^{m\times{n}},b\in\mathbb{R}^m$, then no solution can exist unless $m\leq\mathrm{rank}[A]\leq n$. On the other hand for a given objective function $E_F:\mathbb{R}^n\to\mathbb{R}$ and feasible set $\Omega_F\subset\mathbb{R}^n$, which depend on $F$, a solution to the optimization problem specified by $$\epsilon=\min_{x\in\Omega_F}E_F[x]$$ is a vector $x\in\Omega_F$ such that $E_F[x]\leq E_F[y]$ for all $y\in\Omega_F$. In "least squares" optimization, the function $E_F$ is a sum of squares. The two most common least squares problems are 1) $$E_F[x]=\|F[x]\|^2 \text{ , } \Omega_F=\mathbb{R}^n$$ where $F$ corresponds to an overdetermined system of equations, and 2) $$E_F[x]=\|x\|^2 \text{ , } \Omega_F=\{y\in\mathbb{R}^n\ \mid F[y]=0\}$$ where $F$ corresponds to an underdetermined system of equations. Common linear algebra platforms, such as Matlab, may combine these three distinct mathematical problems "under the hood" in convenience function such as linsolve(). However low-level ("solver") libraries, such as LAPACK, will not. Two final points of clarification: A "solver" will typically correspond to a well-defined but abstracted mathematical problem. For example, "statistical inference" or "sucessful prediction" are not such problems. In the language of Computational Science, you verify a solver, you validate a model. The ideas of unique/non-unique or exact/approximate are not fully clear cut. Say we focus just on the case of square systems of equations, which should remove most points of contention. It is ubiquitous to talk of "iterative solvers" in this field (e.g. ~600,000 hits on Google Scholar). So the de facto definition of "solver" must include this class of algorithms, which by definition are essentially inexact.
What exactly is a "solver" in optimization?
I usually hear "solver" used to describe software, meaning it applies to a particular implementation of an algorithm. For example, this seems to apply to most of the SciComp.SE questions tagged solver
What exactly is a "solver" in optimization? I usually hear "solver" used to describe software, meaning it applies to a particular implementation of an algorithm. For example, this seems to apply to most of the SciComp.SE questions tagged solver. Generally the term seems to be reserved for mathematical problems with a "well-defined solution". A unique solution would qualify as "well defined" sufficient, as noted by Sycorax in the comments. (The Gurobi solvers seem to be for problems in this class; for what its worth, Gurobi looks like a suite or library of solvers to me). But I do not think unique is necessary. For example both local and global optimization problems can have well-defined but non-unique solutions (e.g. the function $f[x]=\sin[\pi x]^2$ has global minimum $f[k]=0$ for $k\in\mathbb{Z}$). I disagree with this answer, which seems to be discussing "equation-system solvers" rather than "optimization solvers". For example in linear least squares, the linear algebra problem is over-determined, but the optimization problem is convex, with a unique solution (in non-degenerate cases). Note also that the Wikipedia "solver" page linked in that answer lists "Linear and non-linear optimisation problems, Shortest path problems, Minimum spanning tree problems" among its examples. In response to the comment, I will clarify what I mean in the "regression" case. Given a function $F:\mathbb{R}^n\to\mathbb{R}^m$, a solution to the system of equations specified by $$F[x]=0$$ is a vector $x\in\mathbb{R}^n$ such that all $m$ components of $F[x]$ are zero. Depending on the function $F$, there can be no solutions, a single unique solution, or many solutions (typically infinitely many), depending on the dimension of the null-space of $F$. In the case where $F$ is linear, i.e. $F[x]=Ax-b$ for some $A\in\mathbb{R}^{m\times{n}},b\in\mathbb{R}^m$, then no solution can exist unless $m\leq\mathrm{rank}[A]\leq n$. On the other hand for a given objective function $E_F:\mathbb{R}^n\to\mathbb{R}$ and feasible set $\Omega_F\subset\mathbb{R}^n$, which depend on $F$, a solution to the optimization problem specified by $$\epsilon=\min_{x\in\Omega_F}E_F[x]$$ is a vector $x\in\Omega_F$ such that $E_F[x]\leq E_F[y]$ for all $y\in\Omega_F$. In "least squares" optimization, the function $E_F$ is a sum of squares. The two most common least squares problems are 1) $$E_F[x]=\|F[x]\|^2 \text{ , } \Omega_F=\mathbb{R}^n$$ where $F$ corresponds to an overdetermined system of equations, and 2) $$E_F[x]=\|x\|^2 \text{ , } \Omega_F=\{y\in\mathbb{R}^n\ \mid F[y]=0\}$$ where $F$ corresponds to an underdetermined system of equations. Common linear algebra platforms, such as Matlab, may combine these three distinct mathematical problems "under the hood" in convenience function such as linsolve(). However low-level ("solver") libraries, such as LAPACK, will not. Two final points of clarification: A "solver" will typically correspond to a well-defined but abstracted mathematical problem. For example, "statistical inference" or "sucessful prediction" are not such problems. In the language of Computational Science, you verify a solver, you validate a model. The ideas of unique/non-unique or exact/approximate are not fully clear cut. Say we focus just on the case of square systems of equations, which should remove most points of contention. It is ubiquitous to talk of "iterative solvers" in this field (e.g. ~600,000 hits on Google Scholar). So the de facto definition of "solver" must include this class of algorithms, which by definition are essentially inexact.
What exactly is a "solver" in optimization? I usually hear "solver" used to describe software, meaning it applies to a particular implementation of an algorithm. For example, this seems to apply to most of the SciComp.SE questions tagged solver
28,208
What exactly is a "solver" in optimization?
I think that the word solver comes from the similar functionality of solving some feasible solution, as there is in Solver add-on of Excel the option "value of", which tries to find $X$ such that $f(X) = Y$ and some more equality and inequality constraints. In mathematica the function solve does the same. English (especially thanks to the media of US) has a tendency to evolve by mistakes being copied like 'cracker'~'hacker'. Solver could be similar. It is nicely abstract enough to hide the names of actual optimisation algorithms. Often the actual implementations are not that purely a single algorithm.
What exactly is a "solver" in optimization?
I think that the word solver comes from the similar functionality of solving some feasible solution, as there is in Solver add-on of Excel the option "value of", which tries to find $X$ such that $f(X
What exactly is a "solver" in optimization? I think that the word solver comes from the similar functionality of solving some feasible solution, as there is in Solver add-on of Excel the option "value of", which tries to find $X$ such that $f(X) = Y$ and some more equality and inequality constraints. In mathematica the function solve does the same. English (especially thanks to the media of US) has a tendency to evolve by mistakes being copied like 'cracker'~'hacker'. Solver could be similar. It is nicely abstract enough to hide the names of actual optimisation algorithms. Often the actual implementations are not that purely a single algorithm.
What exactly is a "solver" in optimization? I think that the word solver comes from the similar functionality of solving some feasible solution, as there is in Solver add-on of Excel the option "value of", which tries to find $X$ such that $f(X
28,209
Interpretation of the Fisher-exact test
The fisher's exact test in R by default tests whether the odds ratio associated with the first cell being 1 or not. That said, you can interpret the odds ratio 0.53 as: the odds of being male for a non-overwieght subject is 0.53 times that for an overweighted subject. Note the p-value is significant and the confidence interval doesn't contain 1. Therefore, you reject the null hypothesis of the odds ratio being 1. However, you might want to exchange the columns and rows of the 2-by-2 contingency table, so that you could interpret "Sex" as an explanatory variable and "Overweight or not" as the response, which seems more nature. In this case, the estimate of the odds ratio should still be 0.53. But you can more naturally interpret it as: the odds of being non-overweight for a male person is 0.53 times that for a female person.
Interpretation of the Fisher-exact test
The fisher's exact test in R by default tests whether the odds ratio associated with the first cell being 1 or not. That said, you can interpret the odds ratio 0.53 as: the odds of being male for a no
Interpretation of the Fisher-exact test The fisher's exact test in R by default tests whether the odds ratio associated with the first cell being 1 or not. That said, you can interpret the odds ratio 0.53 as: the odds of being male for a non-overwieght subject is 0.53 times that for an overweighted subject. Note the p-value is significant and the confidence interval doesn't contain 1. Therefore, you reject the null hypothesis of the odds ratio being 1. However, you might want to exchange the columns and rows of the 2-by-2 contingency table, so that you could interpret "Sex" as an explanatory variable and "Overweight or not" as the response, which seems more nature. In this case, the estimate of the odds ratio should still be 0.53. But you can more naturally interpret it as: the odds of being non-overweight for a male person is 0.53 times that for a female person.
Interpretation of the Fisher-exact test The fisher's exact test in R by default tests whether the odds ratio associated with the first cell being 1 or not. That said, you can interpret the odds ratio 0.53 as: the odds of being male for a no
28,210
Interpretation of the Fisher-exact test
The odds ratio is a measure of how far from independence the 2x2 table is. In your problem, the odds ratio is P(overweight|female)/(1-P(overweight|female)) (odds for overweight for females) divided by P(overweight|male)/(1-P(overweight|male)) (odds for overweight for males). Being a ratio of two sets of odds, it's called an odds ratio. If the table is drawn from a population where the factors are independent, those two population odds will be equal, so the population odds ratio will be 1 (or the log odds-ratio will be 0). The most common estimate of the odds ratio is obtained by replacing the probabilities by the sample proportions (which simplifies to cross-multiplying the counts and dividing the on-diagonal product by the off-diagonal product, or $ad/bc$ in the table $\begin{smallmatrix}a&b\\c&d\end{smallmatrix}$), which gives 0.5356 on your numbers, but that's not the estimator corresponding to a Fisher exact test. That uses the MLE of the odds ratio given the table margins (just as the Fisher test conditions on the table margins). In your case that gives the slightly larger estimate of 0.5358. So this particular odds ratio gives a way of estimating how far from independence your table is that more or less corresponds to Fisher exact test (whether the interval for it includes 1 isn't guaranteed to correspond to the result of the test but they generally go together).
Interpretation of the Fisher-exact test
The odds ratio is a measure of how far from independence the 2x2 table is. In your problem, the odds ratio is P(overweight|female)/(1-P(overweight|female)) (odds for overweight for females) divided by
Interpretation of the Fisher-exact test The odds ratio is a measure of how far from independence the 2x2 table is. In your problem, the odds ratio is P(overweight|female)/(1-P(overweight|female)) (odds for overweight for females) divided by P(overweight|male)/(1-P(overweight|male)) (odds for overweight for males). Being a ratio of two sets of odds, it's called an odds ratio. If the table is drawn from a population where the factors are independent, those two population odds will be equal, so the population odds ratio will be 1 (or the log odds-ratio will be 0). The most common estimate of the odds ratio is obtained by replacing the probabilities by the sample proportions (which simplifies to cross-multiplying the counts and dividing the on-diagonal product by the off-diagonal product, or $ad/bc$ in the table $\begin{smallmatrix}a&b\\c&d\end{smallmatrix}$), which gives 0.5356 on your numbers, but that's not the estimator corresponding to a Fisher exact test. That uses the MLE of the odds ratio given the table margins (just as the Fisher test conditions on the table margins). In your case that gives the slightly larger estimate of 0.5358. So this particular odds ratio gives a way of estimating how far from independence your table is that more or less corresponds to Fisher exact test (whether the interval for it includes 1 isn't guaranteed to correspond to the result of the test but they generally go together).
Interpretation of the Fisher-exact test The odds ratio is a measure of how far from independence the 2x2 table is. In your problem, the odds ratio is P(overweight|female)/(1-P(overweight|female)) (odds for overweight for females) divided by
28,211
Is bias a property of the estimator, or of particular estimates?
In statistics, bias is clearly a property of the estimator. I share your observation that bias is often incorrectly applied to estimates. Your example seems rather innocent in that regard, because a well-meaning instructor could argue that your students assumed that the error of the estimates is so small that it's OK to equate the estimate with the estimator. A more extreme example would be the use of the word "bias" for the error of a particular estimate, as in: we know the true value is 5, but our estimate was biased upwards. I feel this is indeed a misuse of terminology that will eventually lead to confusion, and one should therefore flag it as inappropriate.
Is bias a property of the estimator, or of particular estimates?
In statistics, bias is clearly a property of the estimator. I share your observation that bias is often incorrectly applied to estimates. Your example seems rather innocent in that regard, because a w
Is bias a property of the estimator, or of particular estimates? In statistics, bias is clearly a property of the estimator. I share your observation that bias is often incorrectly applied to estimates. Your example seems rather innocent in that regard, because a well-meaning instructor could argue that your students assumed that the error of the estimates is so small that it's OK to equate the estimate with the estimator. A more extreme example would be the use of the word "bias" for the error of a particular estimate, as in: we know the true value is 5, but our estimate was biased upwards. I feel this is indeed a misuse of terminology that will eventually lead to confusion, and one should therefore flag it as inappropriate.
Is bias a property of the estimator, or of particular estimates? In statistics, bias is clearly a property of the estimator. I share your observation that bias is often incorrectly applied to estimates. Your example seems rather innocent in that regard, because a w
28,212
Is bias a property of the estimator, or of particular estimates?
Bias is the property of an estimator. An estimator is itself a random variable and has a distribution (with a mean and variance). When an estimator has an expected value that is equal to the true, unknown value that it's trying to estimate we say the estimator is unbiased. Now, when we calculate an estimate we are looking at one observation from the distribution of the estimator. So, even if we go with the (incorrect yet innocuous in this context) definition of bias the student seems to be using, there's a problem. The single observation (the estimate), may be very far from the expected value of the estimator's distribution. In other words, it's possible the value of the estimate is very far from the true underlying value where the student seems to be implying that the Observed $R^2$ is very close to it's true value.
Is bias a property of the estimator, or of particular estimates?
Bias is the property of an estimator. An estimator is itself a random variable and has a distribution (with a mean and variance). When an estimator has an expected value that is equal to the true, un
Is bias a property of the estimator, or of particular estimates? Bias is the property of an estimator. An estimator is itself a random variable and has a distribution (with a mean and variance). When an estimator has an expected value that is equal to the true, unknown value that it's trying to estimate we say the estimator is unbiased. Now, when we calculate an estimate we are looking at one observation from the distribution of the estimator. So, even if we go with the (incorrect yet innocuous in this context) definition of bias the student seems to be using, there's a problem. The single observation (the estimate), may be very far from the expected value of the estimator's distribution. In other words, it's possible the value of the estimate is very far from the true underlying value where the student seems to be implying that the Observed $R^2$ is very close to it's true value.
Is bias a property of the estimator, or of particular estimates? Bias is the property of an estimator. An estimator is itself a random variable and has a distribution (with a mean and variance). When an estimator has an expected value that is equal to the true, un
28,213
Why does the Rao-Blackwell Theorem require $\Bbb E(\hat{\theta}^2) < \infty$?
No, $\theta^*$ is a better estimator than $\hat\theta$ but not necessarily the best (whatever that means!) If the estimator has no variance, then its risk is infinite and there is no guarantee that $\theta^*$ has a finite risk (even though this may happen as pointed out by Horst Grünbusch in his comments). Under finite variance for $\hat\theta$, the inequality is strict because of the variance decomposition as the sum of the expected conditional variance plus the variance of the conditional expectation $$\text{var}(\hat\theta)=\mathbb{E}_T[\text{var}(\hat\theta|T)]+ \text{var}_T(\mathbb{E}[\hat\theta|T])=\mathbb{E}_T[\text{var}(\theta|T)]+\text{var}_T(\theta^*)$$ Unless the expected conditional variance is zero, which amounts to $\hat\theta$ a function of $T$ only.
Why does the Rao-Blackwell Theorem require $\Bbb E(\hat{\theta}^2) < \infty$?
No, $\theta^*$ is a better estimator than $\hat\theta$ but not necessarily the best (whatever that means!) If the estimator has no variance, then its risk is infinite and there is no guarantee that $\
Why does the Rao-Blackwell Theorem require $\Bbb E(\hat{\theta}^2) < \infty$? No, $\theta^*$ is a better estimator than $\hat\theta$ but not necessarily the best (whatever that means!) If the estimator has no variance, then its risk is infinite and there is no guarantee that $\theta^*$ has a finite risk (even though this may happen as pointed out by Horst Grünbusch in his comments). Under finite variance for $\hat\theta$, the inequality is strict because of the variance decomposition as the sum of the expected conditional variance plus the variance of the conditional expectation $$\text{var}(\hat\theta)=\mathbb{E}_T[\text{var}(\hat\theta|T)]+ \text{var}_T(\mathbb{E}[\hat\theta|T])=\mathbb{E}_T[\text{var}(\theta|T)]+\text{var}_T(\theta^*)$$ Unless the expected conditional variance is zero, which amounts to $\hat\theta$ a function of $T$ only.
Why does the Rao-Blackwell Theorem require $\Bbb E(\hat{\theta}^2) < \infty$? No, $\theta^*$ is a better estimator than $\hat\theta$ but not necessarily the best (whatever that means!) If the estimator has no variance, then its risk is infinite and there is no guarantee that $\
28,214
Why does the Rao-Blackwell Theorem require $\Bbb E(\hat{\theta}^2) < \infty$?
Note that being a sufficient statistic is not unique. Trivially, the whole data are sufficient, but conditioning an estimator on them doesn't change anything. So a sufficient statistic alone is not sufficient (pun!) for having minimal mean squared error. See the Lehmann-Scheffé-theorem, which uses the Rao-Blackwell-theorem in the proof, for a sufficient sufficiency (in fact, being sufficient and complete). If both are infinite, the weak inequality is always true. But then, as a counterexample, you can construct a sufficient statistic that is not a function of $T$ but has still infinite variance (such that only $\leq$ holds). Take for example $C_1 \sim t_2 + \mu$, a shifted $t_2$-distributed random variable with $E(C_1) = \mu$ and $Var(C_1) = \infty$, and as another independent random variable $C_2 \sim t_2$. The parameter to estimate is $\mu$. Original estimator is $\hat{\theta} = C_1 + C_2$. A sufficient statistic is of course $C_1$. Both the Rao-Blackwell estimator $E(\hat{\theta}|C_1)=C_1$ and $\hat{\theta}$ have infinite variance. So the inequality would hold weakly. On the other hand, $C_1+C_2$ is not a mere function of $C_1$: It involves the other random variable, so that would be a contradiction to the last sentence you asked your 3rd question about. In fact, some textbooks admit infinite variance for the original estimator, but in turn they cannot state when $<$ holds. If $\hat{\theta}$ is a function of $T$, you can prove by the factorization theorem that $\hat{\theta}$ is already sufficient for $\theta$. So again we end up with improving nothing. Apart from this case, the inequality is strict, and that's the non-trivial assertion of the theorem.
Why does the Rao-Blackwell Theorem require $\Bbb E(\hat{\theta}^2) < \infty$?
Note that being a sufficient statistic is not unique. Trivially, the whole data are sufficient, but conditioning an estimator on them doesn't change anything. So a sufficient statistic alone is not su
Why does the Rao-Blackwell Theorem require $\Bbb E(\hat{\theta}^2) < \infty$? Note that being a sufficient statistic is not unique. Trivially, the whole data are sufficient, but conditioning an estimator on them doesn't change anything. So a sufficient statistic alone is not sufficient (pun!) for having minimal mean squared error. See the Lehmann-Scheffé-theorem, which uses the Rao-Blackwell-theorem in the proof, for a sufficient sufficiency (in fact, being sufficient and complete). If both are infinite, the weak inequality is always true. But then, as a counterexample, you can construct a sufficient statistic that is not a function of $T$ but has still infinite variance (such that only $\leq$ holds). Take for example $C_1 \sim t_2 + \mu$, a shifted $t_2$-distributed random variable with $E(C_1) = \mu$ and $Var(C_1) = \infty$, and as another independent random variable $C_2 \sim t_2$. The parameter to estimate is $\mu$. Original estimator is $\hat{\theta} = C_1 + C_2$. A sufficient statistic is of course $C_1$. Both the Rao-Blackwell estimator $E(\hat{\theta}|C_1)=C_1$ and $\hat{\theta}$ have infinite variance. So the inequality would hold weakly. On the other hand, $C_1+C_2$ is not a mere function of $C_1$: It involves the other random variable, so that would be a contradiction to the last sentence you asked your 3rd question about. In fact, some textbooks admit infinite variance for the original estimator, but in turn they cannot state when $<$ holds. If $\hat{\theta}$ is a function of $T$, you can prove by the factorization theorem that $\hat{\theta}$ is already sufficient for $\theta$. So again we end up with improving nothing. Apart from this case, the inequality is strict, and that's the non-trivial assertion of the theorem.
Why does the Rao-Blackwell Theorem require $\Bbb E(\hat{\theta}^2) < \infty$? Note that being a sufficient statistic is not unique. Trivially, the whole data are sufficient, but conditioning an estimator on them doesn't change anything. So a sufficient statistic alone is not su
28,215
difference between overtraining and overfitting
I think the authors are simply using the word "overfitting" to refer to overparametrizing. In the case of neural networks, overfitting is a consequence of overtraining an overparametrized (i.e. overly complex) model. As far as I can tell, there is no difference between an overtrained and an overfitted model, insofar as the prefix "over" already implies that a line has been crossed. Moreover, "fit" and "training" are basically the same thing. A good indication of this is the fact that Wikipedia redirects you to overfitting when you search for overtraining. Overfitting can occur when the model is too complex. However, a very complex but well regularized model can still do well, as the function space it searches within is restricted or penalized in certain regions. In fact, some regard deep neural networks as overparametrized but carefully trained and regularized models. Cross validation can help you get a more or less reliable estimate of how your model is likely to do in the wild. More than avoiding overfitting, it prevents you from relying on the overly optimistic prospect brought by the error obtained by an overfitted model on the training set. It can also help you find a set of hyperparameters that will prevent your model from overfitting, by trying to get good performance on the validation splits.
difference between overtraining and overfitting
I think the authors are simply using the word "overfitting" to refer to overparametrizing. In the case of neural networks, overfitting is a consequence of overtraining an overparametrized (i.e. overly
difference between overtraining and overfitting I think the authors are simply using the word "overfitting" to refer to overparametrizing. In the case of neural networks, overfitting is a consequence of overtraining an overparametrized (i.e. overly complex) model. As far as I can tell, there is no difference between an overtrained and an overfitted model, insofar as the prefix "over" already implies that a line has been crossed. Moreover, "fit" and "training" are basically the same thing. A good indication of this is the fact that Wikipedia redirects you to overfitting when you search for overtraining. Overfitting can occur when the model is too complex. However, a very complex but well regularized model can still do well, as the function space it searches within is restricted or penalized in certain regions. In fact, some regard deep neural networks as overparametrized but carefully trained and regularized models. Cross validation can help you get a more or less reliable estimate of how your model is likely to do in the wild. More than avoiding overfitting, it prevents you from relying on the overly optimistic prospect brought by the error obtained by an overfitted model on the training set. It can also help you find a set of hyperparameters that will prevent your model from overfitting, by trying to get good performance on the validation splits.
difference between overtraining and overfitting I think the authors are simply using the word "overfitting" to refer to overparametrizing. In the case of neural networks, overfitting is a consequence of overtraining an overparametrized (i.e. overly
28,216
difference between overtraining and overfitting
I think the best thing to do is discard terms like "over-fitting" and "over-training" entirely and just consider bias and variance. Keep in mind that when people say a model is "overfit," they typically mean that the model's variance is higher than the value of variance corresponding to minimum out-of-sample loss. From there, think about how each of the hyperparameters of your model affect both bias and variance. As an example, consider a single-hidden-layer feedforward neural network with MSE loss (and bear in mind that $\hat{MSE}=\hat{\text{var}}+\hat{\text{bias}^2}$). We'll assume that the training dataset is stationary, and that all observations are drawn from the same multivariate distribution. 1) as $N_{iter}$ (number of training iterations) increases, $\hat{\text{var}}$ increases, and $\hat{\text{bias}^2}$ decreases. I believe this is what "over-training" refers to. 2) As $N_{obs}$ (number of observations in the training set) increases, $\hat{\text{var}}$ decreases, and $\hat{\text{bias}^2}$ is unaffected. Clearly, as long as our assumptions hold, larger $N_{obs}$ is always better. In practice, non-stationarity due to temporal changes in the relationships between the predictors and response can create situations where some finite value of $N_{obs}$ is optimal. 3) as $P$ (the number of parameters, or connection weights, in the network) increases , $\hat{\text{var}}$ increases, and $\hat{\text{bias}^2}$ is unaffected. 4) as $\lambda$ (the L2 regularization penalty) increases, $\hat{\text{var}}$ decreases, and $\hat{\text{bias}^2}$ increases. My preferred approach -- although expensive -- is to determine the topology of the network first (and thus fix $P$, or at least parameterize it in terms of the number of predictors), and then adjust $\lambda$ (or whatever parameter governs your chosen form of regularization) such that the model converges in a way that generalizes well out-of-sample even for arbitrarily large $N_{iter}$. In the second link I provided above there is a plot of bias, variance, and MSE in the context of ridge regression. It's worth noting that the minimum value of $\hat{MSE}$ does not necessarily coincide with the minimum of $\hat{\text{var}}$. Therefore, targeting the minimum $\hat{\text{var}}$ (and it's $\hat{\text{var}}$ that's generally associated with "overfitting") doesn't necessarily yield you the optimal model in terms of $\hat{MSE}$ when $\hat{\text{bias}^2}>0$. Note also that increasing regularization hyperparameters like $\lambda$, while having the benefit of decreasing $\hat{\text{var}}$, typically have the (generally undesirable) side effect of increasing $\hat{\text{bias}^2}$. Hence the bias-variance tradeoff. On a somewhat separate note, you can decrease $\hat{\text{var}}$ without increasing $\hat{\text{bias}^2}$ by ensembling (bagging) multiple neural networks trained on the same data with different initializations. But there's no free lunch to be found because the computational cost scales linearly with the number of networks you train.
difference between overtraining and overfitting
I think the best thing to do is discard terms like "over-fitting" and "over-training" entirely and just consider bias and variance. Keep in mind that when people say a model is "overfit," they typical
difference between overtraining and overfitting I think the best thing to do is discard terms like "over-fitting" and "over-training" entirely and just consider bias and variance. Keep in mind that when people say a model is "overfit," they typically mean that the model's variance is higher than the value of variance corresponding to minimum out-of-sample loss. From there, think about how each of the hyperparameters of your model affect both bias and variance. As an example, consider a single-hidden-layer feedforward neural network with MSE loss (and bear in mind that $\hat{MSE}=\hat{\text{var}}+\hat{\text{bias}^2}$). We'll assume that the training dataset is stationary, and that all observations are drawn from the same multivariate distribution. 1) as $N_{iter}$ (number of training iterations) increases, $\hat{\text{var}}$ increases, and $\hat{\text{bias}^2}$ decreases. I believe this is what "over-training" refers to. 2) As $N_{obs}$ (number of observations in the training set) increases, $\hat{\text{var}}$ decreases, and $\hat{\text{bias}^2}$ is unaffected. Clearly, as long as our assumptions hold, larger $N_{obs}$ is always better. In practice, non-stationarity due to temporal changes in the relationships between the predictors and response can create situations where some finite value of $N_{obs}$ is optimal. 3) as $P$ (the number of parameters, or connection weights, in the network) increases , $\hat{\text{var}}$ increases, and $\hat{\text{bias}^2}$ is unaffected. 4) as $\lambda$ (the L2 regularization penalty) increases, $\hat{\text{var}}$ decreases, and $\hat{\text{bias}^2}$ increases. My preferred approach -- although expensive -- is to determine the topology of the network first (and thus fix $P$, or at least parameterize it in terms of the number of predictors), and then adjust $\lambda$ (or whatever parameter governs your chosen form of regularization) such that the model converges in a way that generalizes well out-of-sample even for arbitrarily large $N_{iter}$. In the second link I provided above there is a plot of bias, variance, and MSE in the context of ridge regression. It's worth noting that the minimum value of $\hat{MSE}$ does not necessarily coincide with the minimum of $\hat{\text{var}}$. Therefore, targeting the minimum $\hat{\text{var}}$ (and it's $\hat{\text{var}}$ that's generally associated with "overfitting") doesn't necessarily yield you the optimal model in terms of $\hat{MSE}$ when $\hat{\text{bias}^2}>0$. Note also that increasing regularization hyperparameters like $\lambda$, while having the benefit of decreasing $\hat{\text{var}}$, typically have the (generally undesirable) side effect of increasing $\hat{\text{bias}^2}$. Hence the bias-variance tradeoff. On a somewhat separate note, you can decrease $\hat{\text{var}}$ without increasing $\hat{\text{bias}^2}$ by ensembling (bagging) multiple neural networks trained on the same data with different initializations. But there's no free lunch to be found because the computational cost scales linearly with the number of networks you train.
difference between overtraining and overfitting I think the best thing to do is discard terms like "over-fitting" and "over-training" entirely and just consider bias and variance. Keep in mind that when people say a model is "overfit," they typical
28,217
difference between overtraining and overfitting
I'm very much of the opinion that these terms should be separated. Although many people use over-fitting as a catch-all term, it doesn't really capture what is happening in a machine learning setting. That is because many machine learning implementations aren't actually FITTING anything (e.g. as in linear regression or GAM where you're trying to find an equation that best fits the data). There are also no 'goodness of fit' tests performed in most of the machine learning world (although there are metrics used to measure model accuracy). An overly complicated model in machine learning is over-LEARNED or over-TRAINED however in that the method may have learned exactly all the relationships in the dataset perfectly, but it isn't generalized enough for inference or prediction.
difference between overtraining and overfitting
I'm very much of the opinion that these terms should be separated. Although many people use over-fitting as a catch-all term, it doesn't really capture what is happening in a machine learning setting
difference between overtraining and overfitting I'm very much of the opinion that these terms should be separated. Although many people use over-fitting as a catch-all term, it doesn't really capture what is happening in a machine learning setting. That is because many machine learning implementations aren't actually FITTING anything (e.g. as in linear regression or GAM where you're trying to find an equation that best fits the data). There are also no 'goodness of fit' tests performed in most of the machine learning world (although there are metrics used to measure model accuracy). An overly complicated model in machine learning is over-LEARNED or over-TRAINED however in that the method may have learned exactly all the relationships in the dataset perfectly, but it isn't generalized enough for inference or prediction.
difference between overtraining and overfitting I'm very much of the opinion that these terms should be separated. Although many people use over-fitting as a catch-all term, it doesn't really capture what is happening in a machine learning setting
28,218
Is decision tree output a prediction or class probabilities?
Just build the tree so that the leaves contain not just a single class estimate, but also a probability estimate as well. This could be done simply by running any standard decision tree algorithm, and running a bunch of data through it and counting what portion of the time the predicted label was correct in each leaf; this is what sklearn does. These are sometimes called "probability estimation trees," and though they don't give perfect probability estimates, they can be useful. There was a bunch of work investigating them in the early '00s, sometimes with fancier approaches, but the simple one in sklearn is decent for use in forests. If you don't set max_depth or similar parameters, then the tree will always keep splitting until every leaf is pure, and all the probabilities will be 1 (as Soren says). Note that this tree is not nondeterministic; rather, given an input, it deterministically produces both a class prediction and a confidence score in the form of a probability. Verification that this is what's happening: >>> import numpy as np >>> from sklearn.tree import DecisionTreeClassifier >>> from sklearn.datasets import make_classification >>> from sklearn.cross_validation import train_test_split >>> X, y = make_classification(n_informative=10, n_samples=1000) >>> Xtrain, Xtest, ytrain, ytest = train_test_split(X, y) >>> clf = DecisionTreeClassifier(max_depth=5) >>> clf.fit(Xtrain, ytrain) >>> clf.predict_proba(Xtest[:5]) array([[ 0.19607843, 0.80392157], [ 0.9017094 , 0.0982906 ], [ 0.9017094 , 0.0982906 ], [ 0.02631579, 0.97368421], [ 0.9017094 , 0.0982906 ]]) >>> from sklearn.utils import check_array >>> from sklearn.tree.tree import DTYPE >>> def get_node(X): ... return clf.tree_.apply(check_array(X, dtype=DTYPE)) ... >>> node_idx, = get_node(Xtest[:1]) >>> ytrain[get_node(Xtrain) == node_idx].mean() 0.80392156862745101 (In the not-yet-released sklearn 0.17, this get_node helper can be replaced by clf.apply.)
Is decision tree output a prediction or class probabilities?
Just build the tree so that the leaves contain not just a single class estimate, but also a probability estimate as well. This could be done simply by running any standard decision tree algorithm, and
Is decision tree output a prediction or class probabilities? Just build the tree so that the leaves contain not just a single class estimate, but also a probability estimate as well. This could be done simply by running any standard decision tree algorithm, and running a bunch of data through it and counting what portion of the time the predicted label was correct in each leaf; this is what sklearn does. These are sometimes called "probability estimation trees," and though they don't give perfect probability estimates, they can be useful. There was a bunch of work investigating them in the early '00s, sometimes with fancier approaches, but the simple one in sklearn is decent for use in forests. If you don't set max_depth or similar parameters, then the tree will always keep splitting until every leaf is pure, and all the probabilities will be 1 (as Soren says). Note that this tree is not nondeterministic; rather, given an input, it deterministically produces both a class prediction and a confidence score in the form of a probability. Verification that this is what's happening: >>> import numpy as np >>> from sklearn.tree import DecisionTreeClassifier >>> from sklearn.datasets import make_classification >>> from sklearn.cross_validation import train_test_split >>> X, y = make_classification(n_informative=10, n_samples=1000) >>> Xtrain, Xtest, ytrain, ytest = train_test_split(X, y) >>> clf = DecisionTreeClassifier(max_depth=5) >>> clf.fit(Xtrain, ytrain) >>> clf.predict_proba(Xtest[:5]) array([[ 0.19607843, 0.80392157], [ 0.9017094 , 0.0982906 ], [ 0.9017094 , 0.0982906 ], [ 0.02631579, 0.97368421], [ 0.9017094 , 0.0982906 ]]) >>> from sklearn.utils import check_array >>> from sklearn.tree.tree import DTYPE >>> def get_node(X): ... return clf.tree_.apply(check_array(X, dtype=DTYPE)) ... >>> node_idx, = get_node(Xtest[:1]) >>> ytrain[get_node(Xtrain) == node_idx].mean() 0.80392156862745101 (In the not-yet-released sklearn 0.17, this get_node helper can be replaced by clf.apply.)
Is decision tree output a prediction or class probabilities? Just build the tree so that the leaves contain not just a single class estimate, but also a probability estimate as well. This could be done simply by running any standard decision tree algorithm, and
28,219
Is decision tree output a prediction or class probabilities?
I have not used the sklearn implementation of random forest that much. [EDIT] It seems sklearn actually provides the full probabilistic state of terminal nodes. R, randomForest, does not. See also this thread. So depending on implementation: predicted probability is either (a) the mean terminal leaf probability across all trees or (b) the fraction of trees voting either class. If out-of-bag(OOB) prediction, then only in trees where sample is OOB. For a single fully grown tree, I would guess the predicted probability only could be 0 or 1 for any class, because all terminal nodes are pure(same label). If the single tree is not fully grown and/or more trees are grown, then the predicted probability can be a positive rational number from 0 to 1.
Is decision tree output a prediction or class probabilities?
I have not used the sklearn implementation of random forest that much. [EDIT] It seems sklearn actually provides the full probabilistic state of terminal nodes. R, randomForest, does not. See also thi
Is decision tree output a prediction or class probabilities? I have not used the sklearn implementation of random forest that much. [EDIT] It seems sklearn actually provides the full probabilistic state of terminal nodes. R, randomForest, does not. See also this thread. So depending on implementation: predicted probability is either (a) the mean terminal leaf probability across all trees or (b) the fraction of trees voting either class. If out-of-bag(OOB) prediction, then only in trees where sample is OOB. For a single fully grown tree, I would guess the predicted probability only could be 0 or 1 for any class, because all terminal nodes are pure(same label). If the single tree is not fully grown and/or more trees are grown, then the predicted probability can be a positive rational number from 0 to 1.
Is decision tree output a prediction or class probabilities? I have not used the sklearn implementation of random forest that much. [EDIT] It seems sklearn actually provides the full probabilistic state of terminal nodes. R, randomForest, does not. See also thi
28,220
What are the statistical methods I can use to find popular or common combinations of categorical variables?
There are only 1024 possible combinations of the drugs to be used together (if there were only 10 drugs) assuming each user has used at least 1 drug. You could simply convert your 0/1 variables into string and concatenate them and run frequency analyses on the string to see which combinations turn up most frequently. Taking a toy example, say only 3 drugs, A, B, and C, were in your study. If a participant used drug A and C, then the variable alldrugs could be coded 101. A participant who use only drug B would be coded 010. Run frequencies on these to find the one selected most often. Most software should be able process this in seconds.
What are the statistical methods I can use to find popular or common combinations of categorical var
There are only 1024 possible combinations of the drugs to be used together (if there were only 10 drugs) assuming each user has used at least 1 drug. You could simply convert your 0/1 variables into s
What are the statistical methods I can use to find popular or common combinations of categorical variables? There are only 1024 possible combinations of the drugs to be used together (if there were only 10 drugs) assuming each user has used at least 1 drug. You could simply convert your 0/1 variables into string and concatenate them and run frequency analyses on the string to see which combinations turn up most frequently. Taking a toy example, say only 3 drugs, A, B, and C, were in your study. If a participant used drug A and C, then the variable alldrugs could be coded 101. A participant who use only drug B would be coded 010. Run frequencies on these to find the one selected most often. Most software should be able process this in seconds.
What are the statistical methods I can use to find popular or common combinations of categorical var There are only 1024 possible combinations of the drugs to be used together (if there were only 10 drugs) assuming each user has used at least 1 drug. You could simply convert your 0/1 variables into s
28,221
What are the statistical methods I can use to find popular or common combinations of categorical variables?
Latent class modeling would be one, supervised learning approach to finding underlying, "hidden" partitions or groupings of drugs and drug users. LC is a very flexible method with two broad approaches: replications based on repeated measures for a single subject vs replications based on cross-classifying a set of categorical variables. Your data would fit the second type. LCs flexibility is a function of its ability to absorb "mixtures" of variables with differing scalings (e.g., categorical or continuous). Since the approach finds hidden partitions, segments or clusters in data, it can also be considered a dimension reduction technique. All LC models have 2 stages: in stage 1, a dependent or target variable is identified and a regression model is built. In stage 2, the residual (a single "latent" vector) from the stage 1 model is analyzed and partitions are created capturing the variability (or heterogeneity) -- the "latent classes" -- in that vector. Freeware is out there for downloading that would probably work pretty well for you. One of these is an R module called polCA available here: http://www.jstatsoft.org/article/view/v042i10 If you have about $1,000 to spend on a commercial product, Latent Gold is available from www.statisticalinnovations.com Having used on Latent Gold for years, I'm a big fan of that product for its analytic power and range of solutions. For instance, polCA is only useful for LC models with categorical information whereas LG works across the board...plus, their developers are always adding new modules. The most recent addition builds LC models using hidden Markov chains. But bear in mind that LG is not an "end-to-end" data platform, i.e., it is not good for heavy data manipulation or lifting. Otherwise, there are tons of other approaches to analyzing categorical information that are widely supported by statistical software such as R, SPSS, SAS, Python, etc. These include contingency table analysis, log-linear models, finite mixture models, Bayesian tensor regression, and so on. The literature in this area is extensive and began with Bishop, et al., Discrete Multivariate Analysis in 1975, extends through Leo Goodman's RC models based on his work done since the 80s, Agresti's Categorical Data Analysis, books by Stephen Fienberg and includes Thomas Wickens' excellent book Multiway Contingency Tables Analysis for the Social Sciences published in 1989. Bayesian Tensor Regression is the title of a paper by David Dunson at Duke and is kind of the "state-of-the-art" in being a very recent method for modeling massively multiway contingency tables.
What are the statistical methods I can use to find popular or common combinations of categorical var
Latent class modeling would be one, supervised learning approach to finding underlying, "hidden" partitions or groupings of drugs and drug users. LC is a very flexible method with two broad approaches
What are the statistical methods I can use to find popular or common combinations of categorical variables? Latent class modeling would be one, supervised learning approach to finding underlying, "hidden" partitions or groupings of drugs and drug users. LC is a very flexible method with two broad approaches: replications based on repeated measures for a single subject vs replications based on cross-classifying a set of categorical variables. Your data would fit the second type. LCs flexibility is a function of its ability to absorb "mixtures" of variables with differing scalings (e.g., categorical or continuous). Since the approach finds hidden partitions, segments or clusters in data, it can also be considered a dimension reduction technique. All LC models have 2 stages: in stage 1, a dependent or target variable is identified and a regression model is built. In stage 2, the residual (a single "latent" vector) from the stage 1 model is analyzed and partitions are created capturing the variability (or heterogeneity) -- the "latent classes" -- in that vector. Freeware is out there for downloading that would probably work pretty well for you. One of these is an R module called polCA available here: http://www.jstatsoft.org/article/view/v042i10 If you have about $1,000 to spend on a commercial product, Latent Gold is available from www.statisticalinnovations.com Having used on Latent Gold for years, I'm a big fan of that product for its analytic power and range of solutions. For instance, polCA is only useful for LC models with categorical information whereas LG works across the board...plus, their developers are always adding new modules. The most recent addition builds LC models using hidden Markov chains. But bear in mind that LG is not an "end-to-end" data platform, i.e., it is not good for heavy data manipulation or lifting. Otherwise, there are tons of other approaches to analyzing categorical information that are widely supported by statistical software such as R, SPSS, SAS, Python, etc. These include contingency table analysis, log-linear models, finite mixture models, Bayesian tensor regression, and so on. The literature in this area is extensive and began with Bishop, et al., Discrete Multivariate Analysis in 1975, extends through Leo Goodman's RC models based on his work done since the 80s, Agresti's Categorical Data Analysis, books by Stephen Fienberg and includes Thomas Wickens' excellent book Multiway Contingency Tables Analysis for the Social Sciences published in 1989. Bayesian Tensor Regression is the title of a paper by David Dunson at Duke and is kind of the "state-of-the-art" in being a very recent method for modeling massively multiway contingency tables.
What are the statistical methods I can use to find popular or common combinations of categorical var Latent class modeling would be one, supervised learning approach to finding underlying, "hidden" partitions or groupings of drugs and drug users. LC is a very flexible method with two broad approaches
28,222
What are the statistical methods I can use to find popular or common combinations of categorical variables?
What comes to your mind intuitively? You want to count the combinations, why not just find all the possible combinations and simply count? I suggest you look into Frequent item set mining. Wikipedia - Apriori Here are a few implementations of the same: Frequency Pattern Mining
What are the statistical methods I can use to find popular or common combinations of categorical var
What comes to your mind intuitively? You want to count the combinations, why not just find all the possible combinations and simply count? I suggest you look into Frequent item set mining. Wikipedia
What are the statistical methods I can use to find popular or common combinations of categorical variables? What comes to your mind intuitively? You want to count the combinations, why not just find all the possible combinations and simply count? I suggest you look into Frequent item set mining. Wikipedia - Apriori Here are a few implementations of the same: Frequency Pattern Mining
What are the statistical methods I can use to find popular or common combinations of categorical var What comes to your mind intuitively? You want to count the combinations, why not just find all the possible combinations and simply count? I suggest you look into Frequent item set mining. Wikipedia
28,223
Proving the Convolution of PDFs gives a PDF
You are looking at a final result rather than where the convolution came from. Starting from an earlier point makes the proof easier. If $X$ and $Y$ are independent random variables with densities $f$ and $g$ respectively, then \begin{align} P\{X+Y \leq z\} &= \int_{-\infty}^\infty P\{X+Y \leq z \mid Y = y\}g(y)\,\mathrm dy & \scriptstyle{\text{law of total probability}}\\ &= \int_{-\infty}^\infty P\{X \leq z-y \mid Y = y\}g(y)\,\mathrm dy\\ &=\int_{-\infty}^\infty P\{X \leq z-y\}g(y)\,\mathrm dy& \scriptstyle{\text{independence of}~X~\text{and}~Y}\\ P\{X+Y \leq z\} &=\int_{-\infty}^\infty \left[ \int_{-\infty}^{z-y} f(x)\,\mathrm dx\right]g(y)\,\mathrm dy \tag{1} \end{align} Note that the left side of $(1)$ has limiting value $1$ as $z \to \infty$; in fact, the value of that double integral on the right is the CDF of the random variable $Z = X+Y$. The Fundamental Theorem of Calculus applied to $(1)$ gives us $$f_{X+Y}(z) = \frac{\mathrm d}{\mathrm dz}P\{X+Y \leq z\} = \int_{-\infty}^\infty f(z-y)g(y)\,\mathrm dy = f\star g$$ and so $\displaystyle \int_{\mathbb R} f\star g = 1$ as you wish to prove.
Proving the Convolution of PDFs gives a PDF
You are looking at a final result rather than where the convolution came from. Starting from an earlier point makes the proof easier. If $X$ and $Y$ are independent random variables with densities $
Proving the Convolution of PDFs gives a PDF You are looking at a final result rather than where the convolution came from. Starting from an earlier point makes the proof easier. If $X$ and $Y$ are independent random variables with densities $f$ and $g$ respectively, then \begin{align} P\{X+Y \leq z\} &= \int_{-\infty}^\infty P\{X+Y \leq z \mid Y = y\}g(y)\,\mathrm dy & \scriptstyle{\text{law of total probability}}\\ &= \int_{-\infty}^\infty P\{X \leq z-y \mid Y = y\}g(y)\,\mathrm dy\\ &=\int_{-\infty}^\infty P\{X \leq z-y\}g(y)\,\mathrm dy& \scriptstyle{\text{independence of}~X~\text{and}~Y}\\ P\{X+Y \leq z\} &=\int_{-\infty}^\infty \left[ \int_{-\infty}^{z-y} f(x)\,\mathrm dx\right]g(y)\,\mathrm dy \tag{1} \end{align} Note that the left side of $(1)$ has limiting value $1$ as $z \to \infty$; in fact, the value of that double integral on the right is the CDF of the random variable $Z = X+Y$. The Fundamental Theorem of Calculus applied to $(1)$ gives us $$f_{X+Y}(z) = \frac{\mathrm d}{\mathrm dz}P\{X+Y \leq z\} = \int_{-\infty}^\infty f(z-y)g(y)\,\mathrm dy = f\star g$$ and so $\displaystyle \int_{\mathbb R} f\star g = 1$ as you wish to prove.
Proving the Convolution of PDFs gives a PDF You are looking at a final result rather than where the convolution came from. Starting from an earlier point makes the proof easier. If $X$ and $Y$ are independent random variables with densities $
28,224
When re-parametrizing a likelihood function, is it enough just to plug in the transformed variable instead of a change of variables formula?
You do not need a Jacobian in your transform because it is a probability distribution on $y$, not on $\theta$. It must integrate to one in $y$, whether you use $\theta$ or $\phi$: $$ \int p(y|\theta)\text{d}y = \int p(y|\phi)\text{d}y = 1 $$ It is only when you include a (Bayesian) measure on $\theta$ that the Jacobian appears. That is, if $p(\theta)$ is the prior on $\theta$, then the posterior density of $\theta$ is $$p(\theta|y)\propto p(\theta) p(y|\theta)$$ and the posterior density of $\phi$ is $$p(\phi|y)\propto p(y|\phi)p(\phi)=p(y|\theta(\phi))p(\theta(\phi))\left|\frac{\partial \theta}{\partial \phi}\right|\propto p(\theta(\phi)|y)\left|\frac{\partial \theta}{\partial \phi}\right|$$which does involve the Jacobian $\left|\frac{\partial \theta}{\partial \phi}\right|$.
When re-parametrizing a likelihood function, is it enough just to plug in the transformed variable i
You do not need a Jacobian in your transform because it is a probability distribution on $y$, not on $\theta$. It must integrate to one in $y$, whether you use $\theta$ or $\phi$: $$ \int p(y|\theta)\
When re-parametrizing a likelihood function, is it enough just to plug in the transformed variable instead of a change of variables formula? You do not need a Jacobian in your transform because it is a probability distribution on $y$, not on $\theta$. It must integrate to one in $y$, whether you use $\theta$ or $\phi$: $$ \int p(y|\theta)\text{d}y = \int p(y|\phi)\text{d}y = 1 $$ It is only when you include a (Bayesian) measure on $\theta$ that the Jacobian appears. That is, if $p(\theta)$ is the prior on $\theta$, then the posterior density of $\theta$ is $$p(\theta|y)\propto p(\theta) p(y|\theta)$$ and the posterior density of $\phi$ is $$p(\phi|y)\propto p(y|\phi)p(\phi)=p(y|\theta(\phi))p(\theta(\phi))\left|\frac{\partial \theta}{\partial \phi}\right|\propto p(\theta(\phi)|y)\left|\frac{\partial \theta}{\partial \phi}\right|$$which does involve the Jacobian $\left|\frac{\partial \theta}{\partial \phi}\right|$.
When re-parametrizing a likelihood function, is it enough just to plug in the transformed variable i You do not need a Jacobian in your transform because it is a probability distribution on $y$, not on $\theta$. It must integrate to one in $y$, whether you use $\theta$ or $\phi$: $$ \int p(y|\theta)\
28,225
Variance of an average of random variables
If the $X_i$ are random variables with a variance $\sigma_i^2$, then the variance of $X=\sum_i X_i$ their sum is $\sigma_X^2$ is given by: $\sigma_X^2=\sum_i \sigma_i^2 + 2 \sum_i \sum_{j<i} cov(X_i, X_j)$. So if draw a random sample $x_i$ from these distributions, then $x=\sum_i x_i$ will be random (when we draw another sample we will have another value for the sum). The variance of these random outcomes (the sums) will be given by the formula supra. If I divide a random variable $X$ with variance $\sigma_X^2$ by $n$ then the variance of this variable will be $\frac{\sigma_X^2}{n^2}$. Consequently, if you draw a random sample $x_i$ from the distributions of $X_i$, then $\bar{x}=\frac{\sum_i x_i}{n}$ is random (with another sample I will have another average), if we draw many samples and each time compute the average, then we find the distribution of this random variable (the average $\bar{X}=\frac{\sum_i X_i}{n}$) and it has a variance equal to: $\sigma_{\bar{X}}^2=\frac{\sum_i \sigma_i^2 + 2 \sum_i \sum_{j<i} cov(X_i, X_j)}{n^2}$ If the $X_i$ are independent then the covariances are zero and the formula simplifies to. $\sigma_{\bar{X}}^2=\frac{\sum_i \sigma_i^2 }{n^2}$ If the $X_i$ are all independent and have the same variance $\sigma$ then this becomes: $\sigma_{\bar{X}}^2=\frac{\sum_i \sigma ^2}{n^2}=\frac{n \sigma^2}{n^2}=\frac{\sigma^2}{n}$ Note: the capital letters represent random variables, the small letters are draws from a random variable and so one particular outcome. Below some sample code to simulate this in the case of two independent variables #draw hughe sample from x1 and from x2 set.seed(1) #random variable with variance 25 x1<-rnorm(n=1000000, mean=2, sd=5) #random variable with variance 81 x2<-rnorm(n=1000000, mean=0, sd=9) # compute the sum x<-x1+x2 # compute the variance of the sum , should be close to 25+81 sd(x)^2 # compute the average x.bar<-x/2 # compute the variance of the average , should be close to (25+81)/(2^2) sd(x.bar)^2
Variance of an average of random variables
If the $X_i$ are random variables with a variance $\sigma_i^2$, then the variance of $X=\sum_i X_i$ their sum is $\sigma_X^2$ is given by: $\sigma_X^2=\sum_i \sigma_i^2 + 2 \sum_i \sum_{j<i} cov(X_i,
Variance of an average of random variables If the $X_i$ are random variables with a variance $\sigma_i^2$, then the variance of $X=\sum_i X_i$ their sum is $\sigma_X^2$ is given by: $\sigma_X^2=\sum_i \sigma_i^2 + 2 \sum_i \sum_{j<i} cov(X_i, X_j)$. So if draw a random sample $x_i$ from these distributions, then $x=\sum_i x_i$ will be random (when we draw another sample we will have another value for the sum). The variance of these random outcomes (the sums) will be given by the formula supra. If I divide a random variable $X$ with variance $\sigma_X^2$ by $n$ then the variance of this variable will be $\frac{\sigma_X^2}{n^2}$. Consequently, if you draw a random sample $x_i$ from the distributions of $X_i$, then $\bar{x}=\frac{\sum_i x_i}{n}$ is random (with another sample I will have another average), if we draw many samples and each time compute the average, then we find the distribution of this random variable (the average $\bar{X}=\frac{\sum_i X_i}{n}$) and it has a variance equal to: $\sigma_{\bar{X}}^2=\frac{\sum_i \sigma_i^2 + 2 \sum_i \sum_{j<i} cov(X_i, X_j)}{n^2}$ If the $X_i$ are independent then the covariances are zero and the formula simplifies to. $\sigma_{\bar{X}}^2=\frac{\sum_i \sigma_i^2 }{n^2}$ If the $X_i$ are all independent and have the same variance $\sigma$ then this becomes: $\sigma_{\bar{X}}^2=\frac{\sum_i \sigma ^2}{n^2}=\frac{n \sigma^2}{n^2}=\frac{\sigma^2}{n}$ Note: the capital letters represent random variables, the small letters are draws from a random variable and so one particular outcome. Below some sample code to simulate this in the case of two independent variables #draw hughe sample from x1 and from x2 set.seed(1) #random variable with variance 25 x1<-rnorm(n=1000000, mean=2, sd=5) #random variable with variance 81 x2<-rnorm(n=1000000, mean=0, sd=9) # compute the sum x<-x1+x2 # compute the variance of the sum , should be close to 25+81 sd(x)^2 # compute the average x.bar<-x/2 # compute the variance of the average , should be close to (25+81)/(2^2) sd(x.bar)^2
Variance of an average of random variables If the $X_i$ are random variables with a variance $\sigma_i^2$, then the variance of $X=\sum_i X_i$ their sum is $\sigma_X^2$ is given by: $\sigma_X^2=\sum_i \sigma_i^2 + 2 \sum_i \sum_{j<i} cov(X_i,
28,226
Variance of an average of random variables
If your estimates are independent and the likelihood on which each parameter estimate is based is reasonably close to a normal likelihood, then this seems like a meta-analysis with estimates $\hat{\theta}_i$ with standard errors $\sigma_i$, $i=1,\ldots,I$ and one reasonable overall estimate (the inverse variance fixed effects estimate) is $$\hat{\theta} = \frac{ \sum_{i=1}^I \frac{\hat{\theta}_i}{\sigma_i^2}}{\sum_{i=1}^I \sigma_i^{-2}} $$ and $$\text{SE}(\hat{\theta}) = \sqrt{ \frac{ 1 }{\sum_{i=1}^I \sigma_i^{-2}}}.$$ This "fixed effects" estimate assumes that the underlying parameter $\theta$ that you are trying to estimate is one fixed value and does not vary across the different estimates you have. Alternatives include random effects estimates that assume that the true underlying value $\theta_i$ for each experiment you have varies a bit in a way that you cannot explain by observed covariates (if you have observed covariates that explain these differences, you should ideally use those and model the differences rather than "dumping" them into extra variability). That might be what you are looking for. Additionally, note that if your estimates are not independent, then you need to take the covariance into account, as pointed out in another response.
Variance of an average of random variables
If your estimates are independent and the likelihood on which each parameter estimate is based is reasonably close to a normal likelihood, then this seems like a meta-analysis with estimates $\hat{\th
Variance of an average of random variables If your estimates are independent and the likelihood on which each parameter estimate is based is reasonably close to a normal likelihood, then this seems like a meta-analysis with estimates $\hat{\theta}_i$ with standard errors $\sigma_i$, $i=1,\ldots,I$ and one reasonable overall estimate (the inverse variance fixed effects estimate) is $$\hat{\theta} = \frac{ \sum_{i=1}^I \frac{\hat{\theta}_i}{\sigma_i^2}}{\sum_{i=1}^I \sigma_i^{-2}} $$ and $$\text{SE}(\hat{\theta}) = \sqrt{ \frac{ 1 }{\sum_{i=1}^I \sigma_i^{-2}}}.$$ This "fixed effects" estimate assumes that the underlying parameter $\theta$ that you are trying to estimate is one fixed value and does not vary across the different estimates you have. Alternatives include random effects estimates that assume that the true underlying value $\theta_i$ for each experiment you have varies a bit in a way that you cannot explain by observed covariates (if you have observed covariates that explain these differences, you should ideally use those and model the differences rather than "dumping" them into extra variability). That might be what you are looking for. Additionally, note that if your estimates are not independent, then you need to take the covariance into account, as pointed out in another response.
Variance of an average of random variables If your estimates are independent and the likelihood on which each parameter estimate is based is reasonably close to a normal likelihood, then this seems like a meta-analysis with estimates $\hat{\th
28,227
Variance of an average of random variables
I'd like to add these details to the answer by f coppens. Basically, my take-home message is that the amount by which the original numbers vary does not affect confidence in the mean of the original numbers. #Here are the four estimates that I would like to average: m1=4.8; sd1=0.438178045 m2=3.6; sd2=0.328633533 m3=2.4; sd3=0.219089022 m4=1.2; sd4=0.109544511 n=4 In 10,000 fake simulations of four flights, I get 10,000 estimates of 'average number of boats' fake.values1 = array (0); fake.means1= array (0) for (ix in 1:10000) { fake.values1[1:4] = c(rnorm(n=1, m1, sd1), rnorm(n=1, m2, sd2), rnorm(n=1, m3, sd3), rnorm(n=1, m4, sd4)) fake.means1[ix] = mean(fake.values1) } # The variance of my 10,000 boat estimates is sd(fake.means1)^2 # which is darn near the Var2 value from my original data, 0.0225 Next, I've add 1 to m1 and subtracted 1 from m4, thus increasing the overall range (and variance) in the values, but keeping the mean constant. new.m1 = m1+1 new.m4 = m4-1 fake.values2 = array (0); fake.means2= array (0) for (ix in 1:10000) { fake.values2[1:4] = c(rnorm(n=1, new.m1, sd1), rnorm(n=1, m2, sd2), rnorm(n=1, m3, sd3), rnorm(n=1, new.m4, sd4)) fake.means2[ix] = mean(fake.values2) } # The variance of this set of 10,000 boat estimates is sd(fake.means2)^2 # which, again is near the Var2 value, 0.0225 So what appears to be the answer to my question is 'Use your Var2 equation'. The Var1 equation captures variability in the estimates. Var2 captures variability in the mean of the estimates, and is not dependent on the spread of the original values being averaged.
Variance of an average of random variables
I'd like to add these details to the answer by f coppens. Basically, my take-home message is that the amount by which the original numbers vary does not affect confidence in the mean of the original
Variance of an average of random variables I'd like to add these details to the answer by f coppens. Basically, my take-home message is that the amount by which the original numbers vary does not affect confidence in the mean of the original numbers. #Here are the four estimates that I would like to average: m1=4.8; sd1=0.438178045 m2=3.6; sd2=0.328633533 m3=2.4; sd3=0.219089022 m4=1.2; sd4=0.109544511 n=4 In 10,000 fake simulations of four flights, I get 10,000 estimates of 'average number of boats' fake.values1 = array (0); fake.means1= array (0) for (ix in 1:10000) { fake.values1[1:4] = c(rnorm(n=1, m1, sd1), rnorm(n=1, m2, sd2), rnorm(n=1, m3, sd3), rnorm(n=1, m4, sd4)) fake.means1[ix] = mean(fake.values1) } # The variance of my 10,000 boat estimates is sd(fake.means1)^2 # which is darn near the Var2 value from my original data, 0.0225 Next, I've add 1 to m1 and subtracted 1 from m4, thus increasing the overall range (and variance) in the values, but keeping the mean constant. new.m1 = m1+1 new.m4 = m4-1 fake.values2 = array (0); fake.means2= array (0) for (ix in 1:10000) { fake.values2[1:4] = c(rnorm(n=1, new.m1, sd1), rnorm(n=1, m2, sd2), rnorm(n=1, m3, sd3), rnorm(n=1, new.m4, sd4)) fake.means2[ix] = mean(fake.values2) } # The variance of this set of 10,000 boat estimates is sd(fake.means2)^2 # which, again is near the Var2 value, 0.0225 So what appears to be the answer to my question is 'Use your Var2 equation'. The Var1 equation captures variability in the estimates. Var2 captures variability in the mean of the estimates, and is not dependent on the spread of the original values being averaged.
Variance of an average of random variables I'd like to add these details to the answer by f coppens. Basically, my take-home message is that the amount by which the original numbers vary does not affect confidence in the mean of the original
28,228
How is softmax unit derived and what is the implication?
The categorical distribution is the minimum assumptive distribution over the support of "a finite set of mutually exclusive outcomes" given the sufficient statistic of "which outcome happened". In other words, using any other distribution would be an additional assumption. Without any prior knowledge, you must assume a categorical distribution for this support and sufficient statistic. It is an exponential family. (All minimum assumptive distributions for a given support and sufficient statistic are exponential families.) The correct way to combine two beliefs based on independent information is the pointwise product of densities making sure not to double-count prior information that's in both beliefs. For an exponential family, this combination is addition of natural parameters. The expectation parameters are the expected values of $x_k$ where $x_k$ are the number of times you observed outcome $k$. This is the right parametrization for converting a set of observations to a maximum likelihood distribution. You simply average in this space. This is what you want when you are modeling observations. The multinomial logistic function is the conversion from natural parameters to expectation parameters of the categorical distribution. You can derive this conversion as the gradient of the log-normalizer with respect to natural parameters. In summary, the multinomial logistic function falls out of three assumptions: a support, a sufficient statistic, and a model whose belief is a combination of independent pieces of information.
How is softmax unit derived and what is the implication?
The categorical distribution is the minimum assumptive distribution over the support of "a finite set of mutually exclusive outcomes" given the sufficient statistic of "which outcome happened". In ot
How is softmax unit derived and what is the implication? The categorical distribution is the minimum assumptive distribution over the support of "a finite set of mutually exclusive outcomes" given the sufficient statistic of "which outcome happened". In other words, using any other distribution would be an additional assumption. Without any prior knowledge, you must assume a categorical distribution for this support and sufficient statistic. It is an exponential family. (All minimum assumptive distributions for a given support and sufficient statistic are exponential families.) The correct way to combine two beliefs based on independent information is the pointwise product of densities making sure not to double-count prior information that's in both beliefs. For an exponential family, this combination is addition of natural parameters. The expectation parameters are the expected values of $x_k$ where $x_k$ are the number of times you observed outcome $k$. This is the right parametrization for converting a set of observations to a maximum likelihood distribution. You simply average in this space. This is what you want when you are modeling observations. The multinomial logistic function is the conversion from natural parameters to expectation parameters of the categorical distribution. You can derive this conversion as the gradient of the log-normalizer with respect to natural parameters. In summary, the multinomial logistic function falls out of three assumptions: a support, a sufficient statistic, and a model whose belief is a combination of independent pieces of information.
How is softmax unit derived and what is the implication? The categorical distribution is the minimum assumptive distribution over the support of "a finite set of mutually exclusive outcomes" given the sufficient statistic of "which outcome happened". In ot
28,229
How is softmax unit derived and what is the implication?
I know this is a late post, but I do feel like there would still be some value in providing some justification for those who happen to land here. You're not entirely wrong. It is arbitrary to a certain extent, but perhaps arbitrary is the wrong word. It is more like a design choice. Let me explain. It turns out that the Softmax is actually the generalization of the Sigmoid function, which is a Bernoulli (output 0 or 1) output unit: $ \begin{equation} [1+\text{exp}(-z)]^{-1} \end{equation} $ But where does the Sigmoid function come from, you might ask. Well, it turns out that many different probability distributions including the Bernoulli, Poisson distribution, Gaussian, etc follow something called a Generalized Linear Model (GLM). That is, they may be expressed in terms of: $ \begin{equation} P(y;\eta) = b(y)\text{exp}[\eta^TT(y) - a(\eta)] \end{equation} $ I will not cover what all of these parameters are, but you can certainly research this. Observe the following example of how a Bernoulli distribution is in the GLM family: $ P(y=1) = \phi\\ P(y=0) = 1 - \phi\\ P(y) = \phi^y(1-\phi)^{1-y} = \text{exp}(y\text{log}(\phi) + (1-y)\text{log}(1-\phi))\\ = \text{exp}(y\text{log}(\phi) + \text{log}(1-\phi)-y\text{log}(1-\phi))\\ = \text{exp}(y\text{log}(\frac{\phi}{1-\phi}) + \text{log}(1-\phi)) $ You can see that in this case, $ b(y) = 1\\ T(y) = y\\ \eta = \text{log}(\frac{\phi}{1-\phi})\\ a(\eta) = -\text{log}(1-\phi) $ Notice what happens when we solve for $\phi$ in terms of $\eta$: $ \eta = \text{log}(\frac{\phi}{1-\phi})\\ e^\eta =\frac{\phi}{1-\phi}\\ e^{-\eta} = \frac{1-\phi}{\phi} = \frac{1}{\phi}-1\\ e^{-\eta}+1 = \frac{1}{\phi}\\ \phi = [\text{exp}(-{\eta})+1]^{-1} $ So to get $\phi=P(y=1)$, we take the sigmoid of $\eta$. The design choice comes in to play when we assume that $\eta = w^Tx$, where $w$ are your weights and $x$ is your data, both of which we assume to be $\in\mathbb{R}^n$. By making this assumption, we can fit $w$ to approximate $\phi$. If you were to go through this same process for a Multinoulli distribution, you would end up deriving the softmax function.
How is softmax unit derived and what is the implication?
I know this is a late post, but I do feel like there would still be some value in providing some justification for those who happen to land here. You're not entirely wrong. It is arbitrary to a certai
How is softmax unit derived and what is the implication? I know this is a late post, but I do feel like there would still be some value in providing some justification for those who happen to land here. You're not entirely wrong. It is arbitrary to a certain extent, but perhaps arbitrary is the wrong word. It is more like a design choice. Let me explain. It turns out that the Softmax is actually the generalization of the Sigmoid function, which is a Bernoulli (output 0 or 1) output unit: $ \begin{equation} [1+\text{exp}(-z)]^{-1} \end{equation} $ But where does the Sigmoid function come from, you might ask. Well, it turns out that many different probability distributions including the Bernoulli, Poisson distribution, Gaussian, etc follow something called a Generalized Linear Model (GLM). That is, they may be expressed in terms of: $ \begin{equation} P(y;\eta) = b(y)\text{exp}[\eta^TT(y) - a(\eta)] \end{equation} $ I will not cover what all of these parameters are, but you can certainly research this. Observe the following example of how a Bernoulli distribution is in the GLM family: $ P(y=1) = \phi\\ P(y=0) = 1 - \phi\\ P(y) = \phi^y(1-\phi)^{1-y} = \text{exp}(y\text{log}(\phi) + (1-y)\text{log}(1-\phi))\\ = \text{exp}(y\text{log}(\phi) + \text{log}(1-\phi)-y\text{log}(1-\phi))\\ = \text{exp}(y\text{log}(\frac{\phi}{1-\phi}) + \text{log}(1-\phi)) $ You can see that in this case, $ b(y) = 1\\ T(y) = y\\ \eta = \text{log}(\frac{\phi}{1-\phi})\\ a(\eta) = -\text{log}(1-\phi) $ Notice what happens when we solve for $\phi$ in terms of $\eta$: $ \eta = \text{log}(\frac{\phi}{1-\phi})\\ e^\eta =\frac{\phi}{1-\phi}\\ e^{-\eta} = \frac{1-\phi}{\phi} = \frac{1}{\phi}-1\\ e^{-\eta}+1 = \frac{1}{\phi}\\ \phi = [\text{exp}(-{\eta})+1]^{-1} $ So to get $\phi=P(y=1)$, we take the sigmoid of $\eta$. The design choice comes in to play when we assume that $\eta = w^Tx$, where $w$ are your weights and $x$ is your data, both of which we assume to be $\in\mathbb{R}^n$. By making this assumption, we can fit $w$ to approximate $\phi$. If you were to go through this same process for a Multinoulli distribution, you would end up deriving the softmax function.
How is softmax unit derived and what is the implication? I know this is a late post, but I do feel like there would still be some value in providing some justification for those who happen to land here. You're not entirely wrong. It is arbitrary to a certai
28,230
Why is there a E in the name EM algorithm?
Expectations are central to the EM algorithm. To start with, the likelihood associated with the data $(x_1,\ldots,x_n)$ is represented as an expectation \begin{align*} p(x_1,\ldots,x_n;\theta) &= \int_\mathfrak{{Z}^n} p(x_1,\ldots,x_n,\mathfrak{z}_1,\ldots,\mathfrak{z}_n;\theta)\,\text{d}\mathbf{\mathfrak{z}}\\ &=\int_\mathfrak{{Z}^n} p(x_1,\ldots,x_n|\mathfrak{z}_1,\ldots,\mathfrak{z}_n,\theta)p(\mathfrak{z}_1,\ldots,\mathfrak{z}_n;\theta)\,\text{d}\mathbf{\mathfrak{z}}\\ &=\mathbb{E}_\theta\left[ p(x_1,\ldots,x_n|\mathfrak{z}_1,\ldots,\mathfrak{z}_n,\theta)\right] \end{align*} where the expectation is in terms of the marginal distribution of the latent vector $(\mathfrak{z}_1,\ldots,\mathfrak{z}_n)$, which depends on $\theta$. The intuition behind EM is also based on an expectation. Since $\log p(x_1,\ldots,x_n;\theta)$ cannot be directly optimised, while $\log p(x_1,\ldots,x_n,\mathfrak{z}_1,\ldots,\mathfrak{z}_n;\theta)$ can but depends on the unobserved $\mathfrak{z}_i$'s, the idea is to maximise instead the expected complete log-likelihood $$\mathbb{E}_\vartheta\left[ \log p(x_1,\ldots,x_n,\mathfrak{z}_1,\ldots,\mathfrak{z}_n;\theta) \big| x_1,\ldots,x_n \right]$$ except that this expectation also depends on a value of $\vartheta$, chosen as $\theta_0$, say, hence the function to maximise (in $\theta$) in the M step: $$Q(\theta_0,\theta)=\mathbb{E}_{\theta_0}\left[ \log p(x_1,\ldots,x_n,\mathfrak{z}_1,\ldots,\mathfrak{z}_n;\theta) \big| x_1,\ldots,x_n \right]$$ Jensen's inequality only comes as a justification for the increase in the observed likelihood at each M step.
Why is there a E in the name EM algorithm?
Expectations are central to the EM algorithm. To start with, the likelihood associated with the data $(x_1,\ldots,x_n)$ is represented as an expectation \begin{align*} p(x_1,\ldots,x_n;\theta) &= \int
Why is there a E in the name EM algorithm? Expectations are central to the EM algorithm. To start with, the likelihood associated with the data $(x_1,\ldots,x_n)$ is represented as an expectation \begin{align*} p(x_1,\ldots,x_n;\theta) &= \int_\mathfrak{{Z}^n} p(x_1,\ldots,x_n,\mathfrak{z}_1,\ldots,\mathfrak{z}_n;\theta)\,\text{d}\mathbf{\mathfrak{z}}\\ &=\int_\mathfrak{{Z}^n} p(x_1,\ldots,x_n|\mathfrak{z}_1,\ldots,\mathfrak{z}_n,\theta)p(\mathfrak{z}_1,\ldots,\mathfrak{z}_n;\theta)\,\text{d}\mathbf{\mathfrak{z}}\\ &=\mathbb{E}_\theta\left[ p(x_1,\ldots,x_n|\mathfrak{z}_1,\ldots,\mathfrak{z}_n,\theta)\right] \end{align*} where the expectation is in terms of the marginal distribution of the latent vector $(\mathfrak{z}_1,\ldots,\mathfrak{z}_n)$, which depends on $\theta$. The intuition behind EM is also based on an expectation. Since $\log p(x_1,\ldots,x_n;\theta)$ cannot be directly optimised, while $\log p(x_1,\ldots,x_n,\mathfrak{z}_1,\ldots,\mathfrak{z}_n;\theta)$ can but depends on the unobserved $\mathfrak{z}_i$'s, the idea is to maximise instead the expected complete log-likelihood $$\mathbb{E}_\vartheta\left[ \log p(x_1,\ldots,x_n,\mathfrak{z}_1,\ldots,\mathfrak{z}_n;\theta) \big| x_1,\ldots,x_n \right]$$ except that this expectation also depends on a value of $\vartheta$, chosen as $\theta_0$, say, hence the function to maximise (in $\theta$) in the M step: $$Q(\theta_0,\theta)=\mathbb{E}_{\theta_0}\left[ \log p(x_1,\ldots,x_n,\mathfrak{z}_1,\ldots,\mathfrak{z}_n;\theta) \big| x_1,\ldots,x_n \right]$$ Jensen's inequality only comes as a justification for the increase in the observed likelihood at each M step.
Why is there a E in the name EM algorithm? Expectations are central to the EM algorithm. To start with, the likelihood associated with the data $(x_1,\ldots,x_n)$ is represented as an expectation \begin{align*} p(x_1,\ldots,x_n;\theta) &= \int
28,231
Why is there a E in the name EM algorithm?
Just some extension regarding the edited part. The name 'E-step' comes from the fact that one does not usually need to form the probability distribution over completions explicitly, but rather need only compute 'expected' sufficient statistics over these completions. Since the value of $z$ is not observed, we estimate a distribution $q_x(z)$ for each data point $x$ as completions of the unobserved data. The Q function is the sum of expected log likelihoods over $q_x(z)$ $$Q(\theta)=\sum_x E_{q_x}[\log p(x,z|\theta)]$$ The mentioned probability distribution over completions should refer to $p(x,z|\theta)$. For some distributions (especially the exponential family, since the likelihood is in its log form), we only have to know the expected sufficient statistics (instead of the expected likelihood) in order to compute and maximize $Q(\theta)$. There's a very good introduction in Chapter 19.2 of Probabilistic Graphical Models.
Why is there a E in the name EM algorithm?
Just some extension regarding the edited part. The name 'E-step' comes from the fact that one does not usually need to form the probability distribution over completions explicitly, but rather need o
Why is there a E in the name EM algorithm? Just some extension regarding the edited part. The name 'E-step' comes from the fact that one does not usually need to form the probability distribution over completions explicitly, but rather need only compute 'expected' sufficient statistics over these completions. Since the value of $z$ is not observed, we estimate a distribution $q_x(z)$ for each data point $x$ as completions of the unobserved data. The Q function is the sum of expected log likelihoods over $q_x(z)$ $$Q(\theta)=\sum_x E_{q_x}[\log p(x,z|\theta)]$$ The mentioned probability distribution over completions should refer to $p(x,z|\theta)$. For some distributions (especially the exponential family, since the likelihood is in its log form), we only have to know the expected sufficient statistics (instead of the expected likelihood) in order to compute and maximize $Q(\theta)$. There's a very good introduction in Chapter 19.2 of Probabilistic Graphical Models.
Why is there a E in the name EM algorithm? Just some extension regarding the edited part. The name 'E-step' comes from the fact that one does not usually need to form the probability distribution over completions explicitly, but rather need o
28,232
Choosing a k-value for Local Outlier Factor (LOF) detection analysis
Posting this here for anyone who comes across my question in the future -- the original paper describing the local outlier factor algorithm, "LOF: Identifying Density-Based Local Outliers" (Breunig et al), recommends a method of choosing a k-value. As a reminder, the LOF algorithm compares the density of each point to the density of its $k$-closest neighbors. The authors of the paper recommend choosing a minimum $k$ and a maximum $k$, and for each point, taking the maximum LOF value over each $k$ in that range. They offer several guidelines for choosing the bounds. For the minimum value, the LOF values fluctuate wildy the points in a uniform distribution for $k<10$, with points in a uniform distribution sometimes showing up as outliers, so they recommend at least $min(k)=10$. Secondly, the minimum $k$-value serves as a minimum size for something to be considered a "cluster", so that points can be outliers relative to that cluster. If $k=15$, and you have a group of $12$ points and a point $p$, each point in the group will include $p$ in its nearest neighbors, and $p$ will include those points, leading them to have very similar LOFs. So if you want to consider a point near a group of $N$ points as an outlier, rather than part of that group, your k value should be at least $N$. For the maximum value, a similar criteria applies, in that it should be the maximum number of objects that you want to be considered outliers if clustered together. A group of $N$ objects isolated from the main set can either be a cluster, or $N$ outliers; for $k<N$, they will be the first; for $k>N$, they will be the second. Hopefully this helps anyone with a similar problem. The full paper is here, and the discussion of max/min k-values begins on page 7 and goes through page 9. (They refer to the $k$-value as MinPts.)
Choosing a k-value for Local Outlier Factor (LOF) detection analysis
Posting this here for anyone who comes across my question in the future -- the original paper describing the local outlier factor algorithm, "LOF: Identifying Density-Based Local Outliers" (Breunig et
Choosing a k-value for Local Outlier Factor (LOF) detection analysis Posting this here for anyone who comes across my question in the future -- the original paper describing the local outlier factor algorithm, "LOF: Identifying Density-Based Local Outliers" (Breunig et al), recommends a method of choosing a k-value. As a reminder, the LOF algorithm compares the density of each point to the density of its $k$-closest neighbors. The authors of the paper recommend choosing a minimum $k$ and a maximum $k$, and for each point, taking the maximum LOF value over each $k$ in that range. They offer several guidelines for choosing the bounds. For the minimum value, the LOF values fluctuate wildy the points in a uniform distribution for $k<10$, with points in a uniform distribution sometimes showing up as outliers, so they recommend at least $min(k)=10$. Secondly, the minimum $k$-value serves as a minimum size for something to be considered a "cluster", so that points can be outliers relative to that cluster. If $k=15$, and you have a group of $12$ points and a point $p$, each point in the group will include $p$ in its nearest neighbors, and $p$ will include those points, leading them to have very similar LOFs. So if you want to consider a point near a group of $N$ points as an outlier, rather than part of that group, your k value should be at least $N$. For the maximum value, a similar criteria applies, in that it should be the maximum number of objects that you want to be considered outliers if clustered together. A group of $N$ objects isolated from the main set can either be a cluster, or $N$ outliers; for $k<N$, they will be the first; for $k>N$, they will be the second. Hopefully this helps anyone with a similar problem. The full paper is here, and the discussion of max/min k-values begins on page 7 and goes through page 9. (They refer to the $k$-value as MinPts.)
Choosing a k-value for Local Outlier Factor (LOF) detection analysis Posting this here for anyone who comes across my question in the future -- the original paper describing the local outlier factor algorithm, "LOF: Identifying Density-Based Local Outliers" (Breunig et
28,233
Why not always use a binomial exact test to compare two proportions instead of chi square?
You state that you have read the chi-squared test should be used when "the total number of observations is too high". I have never heard this. I don't believe it is true, although it is hard to say, since "too high" is quite vague. There is a standard recommendation not to use the chi-squared test when there are any cells with expected counts less than 5. This traditional warning is now known to be too conservative. Having an expected count less than 5 in a cell is not really a problem. Nonetheless, maybe what you heard is somehow related to that warning. As @whuber notes, the two different tests you ask about make different assumptions about your data. The exact test assumes that the probability (31/52) is known a-priori and without error. The chi-squared test estimates the proportions for both before and after. Notably, both of those proportions are treated as having uncertainty due to sampling error. Thus, the chi-squared test will have less power, but is probably more honest. It may well be that the true proportion of flawed observations was considerably lower than 31/52, but it looked that bad by chance alone. You certainly may test if the after proportion is less than 31/52, just as you may test the after proportion against any value. But a significant result would not necessarily imply that the process improved following the QA program; you should only conclude that the proportion is less than an arbitrary number.
Why not always use a binomial exact test to compare two proportions instead of chi square?
You state that you have read the chi-squared test should be used when "the total number of observations is too high". I have never heard this. I don't believe it is true, although it is hard to say,
Why not always use a binomial exact test to compare two proportions instead of chi square? You state that you have read the chi-squared test should be used when "the total number of observations is too high". I have never heard this. I don't believe it is true, although it is hard to say, since "too high" is quite vague. There is a standard recommendation not to use the chi-squared test when there are any cells with expected counts less than 5. This traditional warning is now known to be too conservative. Having an expected count less than 5 in a cell is not really a problem. Nonetheless, maybe what you heard is somehow related to that warning. As @whuber notes, the two different tests you ask about make different assumptions about your data. The exact test assumes that the probability (31/52) is known a-priori and without error. The chi-squared test estimates the proportions for both before and after. Notably, both of those proportions are treated as having uncertainty due to sampling error. Thus, the chi-squared test will have less power, but is probably more honest. It may well be that the true proportion of flawed observations was considerably lower than 31/52, but it looked that bad by chance alone. You certainly may test if the after proportion is less than 31/52, just as you may test the after proportion against any value. But a significant result would not necessarily imply that the process improved following the QA program; you should only conclude that the proportion is less than an arbitrary number.
Why not always use a binomial exact test to compare two proportions instead of chi square? You state that you have read the chi-squared test should be used when "the total number of observations is too high". I have never heard this. I don't believe it is true, although it is hard to say,
28,234
Why not always use a binomial exact test to compare two proportions instead of chi square?
I think what the OP is observing is that using the Clopper-Pearson method for calculating exact binomial probabilities can be done for very large in this age of fast computing, whereas in the past when the sample size got large, it was easier to use a normal approximation which would be pretty accurate with or without a continuity correction. A chi-squared approximation could be another way. It is my experience that for very large sample sizes (1000 or more) the binomial test can be computed accurately and relatively fast. The only drawback to using exact methods for discrete distributions is that for any given sample size $n$, there are certain values for significant levels that cannot be obtained exactly. So if you try to do sample size calculations searching to achieve a certain level of power and you search for the minimum sample size to achieve that power, you might be surprised to see that going from $n$ to $n+1$ can result in a decrease in power. This problem I referred to as a saw-toothed power function. You can see examples of this in my paper with Christine Liu titled: The Saw-Toothed behavior of Power versus Sample Size and Software solutions: Single Binomial Proportion using Exact Methods. The American Statistician May 2002. You can find it quickly by googling the saw-toothed power function. The same issue applies to confidence intervals. An earlier paper by Agresti and Coulli was published in the American Statistician in 1998 which is a popular method for generating Binomial Confidence Intervals. This and other methods for obtaining binomial Confidence intervals can be found in the Wikipedia article titled binomial proportion confidence intervals.
Why not always use a binomial exact test to compare two proportions instead of chi square?
I think what the OP is observing is that using the Clopper-Pearson method for calculating exact binomial probabilities can be done for very large in this age of fast computing, whereas in the past wh
Why not always use a binomial exact test to compare two proportions instead of chi square? I think what the OP is observing is that using the Clopper-Pearson method for calculating exact binomial probabilities can be done for very large in this age of fast computing, whereas in the past when the sample size got large, it was easier to use a normal approximation which would be pretty accurate with or without a continuity correction. A chi-squared approximation could be another way. It is my experience that for very large sample sizes (1000 or more) the binomial test can be computed accurately and relatively fast. The only drawback to using exact methods for discrete distributions is that for any given sample size $n$, there are certain values for significant levels that cannot be obtained exactly. So if you try to do sample size calculations searching to achieve a certain level of power and you search for the minimum sample size to achieve that power, you might be surprised to see that going from $n$ to $n+1$ can result in a decrease in power. This problem I referred to as a saw-toothed power function. You can see examples of this in my paper with Christine Liu titled: The Saw-Toothed behavior of Power versus Sample Size and Software solutions: Single Binomial Proportion using Exact Methods. The American Statistician May 2002. You can find it quickly by googling the saw-toothed power function. The same issue applies to confidence intervals. An earlier paper by Agresti and Coulli was published in the American Statistician in 1998 which is a popular method for generating Binomial Confidence Intervals. This and other methods for obtaining binomial Confidence intervals can be found in the Wikipedia article titled binomial proportion confidence intervals.
Why not always use a binomial exact test to compare two proportions instead of chi square? I think what the OP is observing is that using the Clopper-Pearson method for calculating exact binomial probabilities can be done for very large in this age of fast computing, whereas in the past wh
28,235
Parameter estimation with generalized linear models
You are correct that in general, IWLS, like other numerical optimization methods, can only guarantee convergence to a local maximum, if they even converge. Here's a nice example where the starting value was outside the convergence domain for the algorithm used by glm() in R. However, it is worth noting that for GLMs with the canonical link, the likelihood is concave, see here. Thus, if the algorithm converges, it will have converged to the global mode! The last issue pointed out in the slide is a problem where the MLE for a paramter is at infinity. This can occur in logistic regression where there exists complete separation. In such a case, you will get a warning message that the fitted probabilities are numerically 0 or 1. It's important to note that when this occurs, the algorithm has not converged to the mode, thus this does not have to do with the algorithm being stuck in a local maximum.
Parameter estimation with generalized linear models
You are correct that in general, IWLS, like other numerical optimization methods, can only guarantee convergence to a local maximum, if they even converge. Here's a nice example where the starting va
Parameter estimation with generalized linear models You are correct that in general, IWLS, like other numerical optimization methods, can only guarantee convergence to a local maximum, if they even converge. Here's a nice example where the starting value was outside the convergence domain for the algorithm used by glm() in R. However, it is worth noting that for GLMs with the canonical link, the likelihood is concave, see here. Thus, if the algorithm converges, it will have converged to the global mode! The last issue pointed out in the slide is a problem where the MLE for a paramter is at infinity. This can occur in logistic regression where there exists complete separation. In such a case, you will get a warning message that the fitted probabilities are numerically 0 or 1. It's important to note that when this occurs, the algorithm has not converged to the mode, thus this does not have to do with the algorithm being stuck in a local maximum.
Parameter estimation with generalized linear models You are correct that in general, IWLS, like other numerical optimization methods, can only guarantee convergence to a local maximum, if they even converge. Here's a nice example where the starting va
28,236
Parameter estimation with generalized linear models
When you are trying to estimate parameters, you always want there to be a closed form solution. However, one does not always exist (I suppose it is possible that in some cases there may be one but it is unknown at present). When a closed form solution does not exist, some heuristic strategy must be employed to search over the parameter space for the best possible parameter estimates to use. There are many such search strategies (e.g. in R, ?optim lists 6 general purpose methods). The IRWLS is a simplified version of the Newton-Raphson algorithm. Unfortunately, the answer to your [1] is that no heuristic search strategy is guaranteed to find the global minimum (maximum). There are three reasons why that is the case: As noted on slide 9 of your linked presentation, no unique solution may exist. Examples of this might be perfect multicollinearity, or when there are more parameters to be estimated than there are data. As noted on slide 10 (that presentation is quite good, I think), the solution may be infinite. This can happen in logistic regression, for instance, when you have perfect separation. It can also be the case that there is a finite global minimum (maximum), but that the algorithm does not find it. These algorithms (especially IRWLS and N-R) tend to start from a specified location and 'look around' to see if moving in some direction constitutes 'going downhill' (i.e., improving the fit). If so, then it will re-fit at some distance in that direction and repeat until the guessed / predicted improvement is less than some threshold. Thus, there can be two ways to not reach the global minimum: The rate of descent from the current location towards the global minimum (maximum) is too shallow to cross the threshold and the algorithm stops short of the solution. There is a local minimum (maximum) between the current location and the global minimum (maximum), so that it appears to the algorithm that further movement would lead to a worse fit. Regarding your [2], be aware that different search strategies have different tendencies to be caught in local minima. Even the same strategy can sometimes be adapted, or commenced from a different starting point to address the latter two problems.
Parameter estimation with generalized linear models
When you are trying to estimate parameters, you always want there to be a closed form solution. However, one does not always exist (I suppose it is possible that in some cases there may be one but it
Parameter estimation with generalized linear models When you are trying to estimate parameters, you always want there to be a closed form solution. However, one does not always exist (I suppose it is possible that in some cases there may be one but it is unknown at present). When a closed form solution does not exist, some heuristic strategy must be employed to search over the parameter space for the best possible parameter estimates to use. There are many such search strategies (e.g. in R, ?optim lists 6 general purpose methods). The IRWLS is a simplified version of the Newton-Raphson algorithm. Unfortunately, the answer to your [1] is that no heuristic search strategy is guaranteed to find the global minimum (maximum). There are three reasons why that is the case: As noted on slide 9 of your linked presentation, no unique solution may exist. Examples of this might be perfect multicollinearity, or when there are more parameters to be estimated than there are data. As noted on slide 10 (that presentation is quite good, I think), the solution may be infinite. This can happen in logistic regression, for instance, when you have perfect separation. It can also be the case that there is a finite global minimum (maximum), but that the algorithm does not find it. These algorithms (especially IRWLS and N-R) tend to start from a specified location and 'look around' to see if moving in some direction constitutes 'going downhill' (i.e., improving the fit). If so, then it will re-fit at some distance in that direction and repeat until the guessed / predicted improvement is less than some threshold. Thus, there can be two ways to not reach the global minimum: The rate of descent from the current location towards the global minimum (maximum) is too shallow to cross the threshold and the algorithm stops short of the solution. There is a local minimum (maximum) between the current location and the global minimum (maximum), so that it appears to the algorithm that further movement would lead to a worse fit. Regarding your [2], be aware that different search strategies have different tendencies to be caught in local minima. Even the same strategy can sometimes be adapted, or commenced from a different starting point to address the latter two problems.
Parameter estimation with generalized linear models When you are trying to estimate parameters, you always want there to be a closed form solution. However, one does not always exist (I suppose it is possible that in some cases there may be one but it
28,237
Normalization of dummy variables
Normalization would be required if you are doing some form a similarity measurement. Dummy variables by its nature acts as a binary switch. Coding it as (0,1) or (-.5,.5) should have no impact on the relationships it exhibits to a dependent variable, if what you are trying to do is some form or regression or classification. It would matter if you are performing clustering because it would be scale dependent.
Normalization of dummy variables
Normalization would be required if you are doing some form a similarity measurement. Dummy variables by its nature acts as a binary switch. Coding it as (0,1) or (-.5,.5) should have no impact on the
Normalization of dummy variables Normalization would be required if you are doing some form a similarity measurement. Dummy variables by its nature acts as a binary switch. Coding it as (0,1) or (-.5,.5) should have no impact on the relationships it exhibits to a dependent variable, if what you are trying to do is some form or regression or classification. It would matter if you are performing clustering because it would be scale dependent.
Normalization of dummy variables Normalization would be required if you are doing some form a similarity measurement. Dummy variables by its nature acts as a binary switch. Coding it as (0,1) or (-.5,.5) should have no impact on the
28,238
Normalization of dummy variables
Normalizing dummy variables makes no sense. Usually, normalization is used when the variables are measured on different scales such that a proper comparison is not possible. With dummy variables, however, one puts just a binary information in the model and if it is normalized the information of the impact of e. g. one year is lost.
Normalization of dummy variables
Normalizing dummy variables makes no sense. Usually, normalization is used when the variables are measured on different scales such that a proper comparison is not possible. With dummy variables, howe
Normalization of dummy variables Normalizing dummy variables makes no sense. Usually, normalization is used when the variables are measured on different scales such that a proper comparison is not possible. With dummy variables, however, one puts just a binary information in the model and if it is normalized the information of the impact of e. g. one year is lost.
Normalization of dummy variables Normalizing dummy variables makes no sense. Usually, normalization is used when the variables are measured on different scales such that a proper comparison is not possible. With dummy variables, howe
28,239
In a meta-analysis, how should one handle non-significant studies containing no raw data?
As you point out, there are merits with all three approaches. There clearly isn't one option that is 'best'. Why not do all 3 and present the results as a sensitivity analysis? A meta-analysis conducted with ample and appropriate sensitivity analyses just shows that the author is well aware of the limits of the data at hand, makes explicit the influence of the choices we make when conducting a meta-analysis, and is able to critically evaluate the consequences. To me, that is the mark of well-conducted meta-analysis. Anybody who has ever conducted a meta-analysis knows very well that there are many choices and decisions to be made along the way and those choices and decisions can have a considerable influence on the results obtained. The advantage of a meta-analysis (or more generally, a systematic review) is that the methods (and hence the choices and decisions) are made explicit. And one can evaluate their influence in a systematic way. That is exactly how a meta-analysis should be conducted.
In a meta-analysis, how should one handle non-significant studies containing no raw data?
As you point out, there are merits with all three approaches. There clearly isn't one option that is 'best'. Why not do all 3 and present the results as a sensitivity analysis? A meta-analysis conduct
In a meta-analysis, how should one handle non-significant studies containing no raw data? As you point out, there are merits with all three approaches. There clearly isn't one option that is 'best'. Why not do all 3 and present the results as a sensitivity analysis? A meta-analysis conducted with ample and appropriate sensitivity analyses just shows that the author is well aware of the limits of the data at hand, makes explicit the influence of the choices we make when conducting a meta-analysis, and is able to critically evaluate the consequences. To me, that is the mark of well-conducted meta-analysis. Anybody who has ever conducted a meta-analysis knows very well that there are many choices and decisions to be made along the way and those choices and decisions can have a considerable influence on the results obtained. The advantage of a meta-analysis (or more generally, a systematic review) is that the methods (and hence the choices and decisions) are made explicit. And one can evaluate their influence in a systematic way. That is exactly how a meta-analysis should be conducted.
In a meta-analysis, how should one handle non-significant studies containing no raw data? As you point out, there are merits with all three approaches. There clearly isn't one option that is 'best'. Why not do all 3 and present the results as a sensitivity analysis? A meta-analysis conduct
28,240
In a meta-analysis, how should one handle non-significant studies containing no raw data?
Here are the steps that I would take (and that I teach to my students): 1) Contact the authors of the original research. Be polite and request exact effect estimates to use in your meta-analysis. Worst thing that can happen is that they don't reply or refuse to give you the information. Best case scenario is you get the exact information you were looking for. 2) If you have exact p-values, you can often back calculate SD's with some degree of certainty. 3) You make some sort of imputation. This could be using 'borrowing' the effect estimate from similar sized trials, largest SD in the meta-analysis, SD from similar studies in the same meta-analysis, expert opinion, etc. There are many ways to impute the missing data, some more scientifically correct than others, but the most important thing is that you are crystal clear about what you did and to conduct a sensitivity analysis to determine the effect of the imputation(s) on the pooled effect estimate. 3) You put them the studies into the meta-analysis with the missing data. The program (e.g. RevMan) will not give these studies any weight in the analysis because it won't be able to calculate the effect estimate and variance for that study, but you will be able to visually show that there were additional studies with partial data that were not part of the pooled calculation. 4) You don't include data from these studies. Pick you poison...
In a meta-analysis, how should one handle non-significant studies containing no raw data?
Here are the steps that I would take (and that I teach to my students): 1) Contact the authors of the original research. Be polite and request exact effect estimates to use in your meta-analysis. Wors
In a meta-analysis, how should one handle non-significant studies containing no raw data? Here are the steps that I would take (and that I teach to my students): 1) Contact the authors of the original research. Be polite and request exact effect estimates to use in your meta-analysis. Worst thing that can happen is that they don't reply or refuse to give you the information. Best case scenario is you get the exact information you were looking for. 2) If you have exact p-values, you can often back calculate SD's with some degree of certainty. 3) You make some sort of imputation. This could be using 'borrowing' the effect estimate from similar sized trials, largest SD in the meta-analysis, SD from similar studies in the same meta-analysis, expert opinion, etc. There are many ways to impute the missing data, some more scientifically correct than others, but the most important thing is that you are crystal clear about what you did and to conduct a sensitivity analysis to determine the effect of the imputation(s) on the pooled effect estimate. 3) You put them the studies into the meta-analysis with the missing data. The program (e.g. RevMan) will not give these studies any weight in the analysis because it won't be able to calculate the effect estimate and variance for that study, but you will be able to visually show that there were additional studies with partial data that were not part of the pooled calculation. 4) You don't include data from these studies. Pick you poison...
In a meta-analysis, how should one handle non-significant studies containing no raw data? Here are the steps that I would take (and that I teach to my students): 1) Contact the authors of the original research. Be polite and request exact effect estimates to use in your meta-analysis. Wors
28,241
Required number of permutations for a permutation-based p-value
I admit, the paragraph might be confusing. When performing a permutation test you do estimate a p-value. The issue is, that the estimation of the p-value has an error itself which is calculated as $\sqrt{\frac{p(1-p)}{k}}$. If the error is too large, the p-value is unreliable. So how many permutations k does one need to get a reliable estimate ? First define your maximum allowed error aka the precision. Let this be $P$. Then an estimated p-value shall be in the interval $[p-3*P,p+3*P]$ (since p is approximately normal distributed) Using the upper bound The cited paragraph of the paper suggests to use $\frac{1}{2\sqrt{k}}$ as an upper bound estimate of the error instead of $\sqrt{\frac{p(1-p)}{k}}$. This corresponds to a unknown p-value of p=0.5 (where the error is maximum among all ps for a fixed k). So: You want to know k where $\frac{1}{2\sqrt{k}}\le P$. <=> $\frac{1}{4P^2}\le k$ But since the cited formula represents an upper bound, this approach is very rough. Using the error at the significance level Another approach uses the desired significance level $\alpha$ as p to calculate the required precision. This is correct, because the error of the estimated p is more important if we are near the decision threshold (which is the significance level). In this case one wants to know k where $\sqrt{\frac{\alpha(1-\alpha)}{k}}\le P$. <=> $\frac{(\alpha(1-\alpha))}{P^2}\le k$ Note that if the true unkown p-value is clearly bigger than $\alpha$, then the error is actually bigger, so p in $[p-3*P,p+3*P]$ does not hold anymore. Extending the confidence interval This approach corresponds with the center of the confidence interval being right at the decision threshold. In order to force the upper bound of the confidence interval of the estimated p being below the decision threshold (which is more correct), one needs ... $l\sqrt{\frac{\alpha(1-\alpha)}{k}}\le P$ <=> $(l)^2\frac{(\alpha(1-\alpha))}{P^2}\le k$ where l corresponds to (see again the graphic) | l | confidence interval | | 1 | ~68 % | | 2 | ~95 % | | 3 | ~99 % | Examples: Let the desired precison P be 0.005. Then using the rough upper bound one gets $k>=10000$. Using P at $\alpha=0.05$ and requesting a 95%-confidence interval one gets $k>=7600$. For P=0.01 at $\alpha=0.01$ and a 95 % confidence interval one gets k>=396. Finally: I strongly suggest to dive deeper into Monte-Carlo simulations. The wikipedia provides a start.
Required number of permutations for a permutation-based p-value
I admit, the paragraph might be confusing. When performing a permutation test you do estimate a p-value. The issue is, that the estimation of the p-value has an error itself which is calculated as $\s
Required number of permutations for a permutation-based p-value I admit, the paragraph might be confusing. When performing a permutation test you do estimate a p-value. The issue is, that the estimation of the p-value has an error itself which is calculated as $\sqrt{\frac{p(1-p)}{k}}$. If the error is too large, the p-value is unreliable. So how many permutations k does one need to get a reliable estimate ? First define your maximum allowed error aka the precision. Let this be $P$. Then an estimated p-value shall be in the interval $[p-3*P,p+3*P]$ (since p is approximately normal distributed) Using the upper bound The cited paragraph of the paper suggests to use $\frac{1}{2\sqrt{k}}$ as an upper bound estimate of the error instead of $\sqrt{\frac{p(1-p)}{k}}$. This corresponds to a unknown p-value of p=0.5 (where the error is maximum among all ps for a fixed k). So: You want to know k where $\frac{1}{2\sqrt{k}}\le P$. <=> $\frac{1}{4P^2}\le k$ But since the cited formula represents an upper bound, this approach is very rough. Using the error at the significance level Another approach uses the desired significance level $\alpha$ as p to calculate the required precision. This is correct, because the error of the estimated p is more important if we are near the decision threshold (which is the significance level). In this case one wants to know k where $\sqrt{\frac{\alpha(1-\alpha)}{k}}\le P$. <=> $\frac{(\alpha(1-\alpha))}{P^2}\le k$ Note that if the true unkown p-value is clearly bigger than $\alpha$, then the error is actually bigger, so p in $[p-3*P,p+3*P]$ does not hold anymore. Extending the confidence interval This approach corresponds with the center of the confidence interval being right at the decision threshold. In order to force the upper bound of the confidence interval of the estimated p being below the decision threshold (which is more correct), one needs ... $l\sqrt{\frac{\alpha(1-\alpha)}{k}}\le P$ <=> $(l)^2\frac{(\alpha(1-\alpha))}{P^2}\le k$ where l corresponds to (see again the graphic) | l | confidence interval | | 1 | ~68 % | | 2 | ~95 % | | 3 | ~99 % | Examples: Let the desired precison P be 0.005. Then using the rough upper bound one gets $k>=10000$. Using P at $\alpha=0.05$ and requesting a 95%-confidence interval one gets $k>=7600$. For P=0.01 at $\alpha=0.01$ and a 95 % confidence interval one gets k>=396. Finally: I strongly suggest to dive deeper into Monte-Carlo simulations. The wikipedia provides a start.
Required number of permutations for a permutation-based p-value I admit, the paragraph might be confusing. When performing a permutation test you do estimate a p-value. The issue is, that the estimation of the p-value has an error itself which is calculated as $\s
28,242
Integrate with eCDF quickly in R
Defining the empirical distribution function $$ \hat{F}_n(t)=\frac{1}{n}\sum_{i=1}^n I_{[x_i,\infty)}(t) \, , $$ it follows that $$ \int_{-\infty}^\infty g(t)\,d\hat{F}_n(t) = \frac{1}{n} \sum_{i=1}^n g(x_i) \, . $$ Hence, you don't need to use integrate() to solve this problem. This kind of R code x <- rnorm(10^6) g <- function(t) exp(t) # say mean(g(x)) should be super fast because it is vectorized.
Integrate with eCDF quickly in R
Defining the empirical distribution function $$ \hat{F}_n(t)=\frac{1}{n}\sum_{i=1}^n I_{[x_i,\infty)}(t) \, , $$ it follows that $$ \int_{-\infty}^\infty g(t)\,d\hat{F}_n(t) = \frac{1}{n} \sum_{i
Integrate with eCDF quickly in R Defining the empirical distribution function $$ \hat{F}_n(t)=\frac{1}{n}\sum_{i=1}^n I_{[x_i,\infty)}(t) \, , $$ it follows that $$ \int_{-\infty}^\infty g(t)\,d\hat{F}_n(t) = \frac{1}{n} \sum_{i=1}^n g(x_i) \, . $$ Hence, you don't need to use integrate() to solve this problem. This kind of R code x <- rnorm(10^6) g <- function(t) exp(t) # say mean(g(x)) should be super fast because it is vectorized.
Integrate with eCDF quickly in R Defining the empirical distribution function $$ \hat{F}_n(t)=\frac{1}{n}\sum_{i=1}^n I_{[x_i,\infty)}(t) \, , $$ it follows that $$ \int_{-\infty}^\infty g(t)\,d\hat{F}_n(t) = \frac{1}{n} \sum_{i
28,243
Exercise 2.2 of The Elements of Statistical Learning
I don't think you're supposed to find an analytic expression for the Bayes decision boundary, for a given realisation of the $m_k$'s. Similarly I doubt you're supposed to get the boundary over the distribution of the $m_k$, since that's just $x=y$ by symmetry as you noted. I think what you need is to show is a program that can compute the decision boundary for a given realisation of the $m_k$'s. This can be done by setting down a grid of $x$ and $y$ values, computing the class-conditional densities, and finding the points where they're equal. This code is a stab at it. IIRC there's actually code to compute the decision boundary in Modern Applied Statistics with S, but I haven't got that handy right now. # for dmvnorm/rmvnorm: multivariate normal distribution library(mvtnorm) # class-conditional density given mixture centers f <- function(x, m) { out <- numeric(nrow(x)) for(i in seq_len(nrow(m))) out <- out + dmvnorm(x, m[i, ], diag(0.2, 2)) out } # generate the class mixture centers m1 <- rmvnorm(10, c(1,0), diag(2)) m2 <- rmvnorm(10, c(0,1), diag(2)) # and plot them plot(m1, xlim=c(-2, 3), ylim=c(-2, 3), col="blue") points(m2, col="red") # display contours of the class-conditional densities dens <- local({ x <- y <- seq(-3, 4, len=701) f1 <- outer(x, y, function(x, y) f(cbind(x, y), m1)) f2 <- outer(x, y, function(x, y) f(cbind(x, y), m2)) list(x=x, y=y, f1=f1, f2=f2) }) contour(dens$x, dens$y, dens$f1, col="lightblue", lty=2, levels=seq(.3, 3, len=10), labels="", add=TRUE) contour(dens$x, dens$y, dens$f2, col="pink", lty=2, levels=seq(.3, 3, len=10), labels="", add=TRUE) # find which points are on the Bayes decision boundary eq <- local({ f1 <- dens$f1 f2 <- dens$f2 pts <- seq(-3, 4, len=701) eq <- which(abs((dens$f1 - dens$f2)/(dens$f1 + dens$f2)) < 5e-3, arr.ind=TRUE) eq[,1] <- pts[eq[,1]] eq[,2] <- pts[eq[,2]] eq }) points(eq, pch=16, cex=0.5, col="grey") Result:
Exercise 2.2 of The Elements of Statistical Learning
I don't think you're supposed to find an analytic expression for the Bayes decision boundary, for a given realisation of the $m_k$'s. Similarly I doubt you're supposed to get the boundary over the dis
Exercise 2.2 of The Elements of Statistical Learning I don't think you're supposed to find an analytic expression for the Bayes decision boundary, for a given realisation of the $m_k$'s. Similarly I doubt you're supposed to get the boundary over the distribution of the $m_k$, since that's just $x=y$ by symmetry as you noted. I think what you need is to show is a program that can compute the decision boundary for a given realisation of the $m_k$'s. This can be done by setting down a grid of $x$ and $y$ values, computing the class-conditional densities, and finding the points where they're equal. This code is a stab at it. IIRC there's actually code to compute the decision boundary in Modern Applied Statistics with S, but I haven't got that handy right now. # for dmvnorm/rmvnorm: multivariate normal distribution library(mvtnorm) # class-conditional density given mixture centers f <- function(x, m) { out <- numeric(nrow(x)) for(i in seq_len(nrow(m))) out <- out + dmvnorm(x, m[i, ], diag(0.2, 2)) out } # generate the class mixture centers m1 <- rmvnorm(10, c(1,0), diag(2)) m2 <- rmvnorm(10, c(0,1), diag(2)) # and plot them plot(m1, xlim=c(-2, 3), ylim=c(-2, 3), col="blue") points(m2, col="red") # display contours of the class-conditional densities dens <- local({ x <- y <- seq(-3, 4, len=701) f1 <- outer(x, y, function(x, y) f(cbind(x, y), m1)) f2 <- outer(x, y, function(x, y) f(cbind(x, y), m2)) list(x=x, y=y, f1=f1, f2=f2) }) contour(dens$x, dens$y, dens$f1, col="lightblue", lty=2, levels=seq(.3, 3, len=10), labels="", add=TRUE) contour(dens$x, dens$y, dens$f2, col="pink", lty=2, levels=seq(.3, 3, len=10), labels="", add=TRUE) # find which points are on the Bayes decision boundary eq <- local({ f1 <- dens$f1 f2 <- dens$f2 pts <- seq(-3, 4, len=701) eq <- which(abs((dens$f1 - dens$f2)/(dens$f1 + dens$f2)) < 5e-3, arr.ind=TRUE) eq[,1] <- pts[eq[,1]] eq[,2] <- pts[eq[,2]] eq }) points(eq, pch=16, cex=0.5, col="grey") Result:
Exercise 2.2 of The Elements of Statistical Learning I don't think you're supposed to find an analytic expression for the Bayes decision boundary, for a given realisation of the $m_k$'s. Similarly I doubt you're supposed to get the boundary over the dis
28,244
Exercise 2.2 of The Elements of Statistical Learning
Actually, the book does ask to provide an analytical solution to this problem. And yes, you have to condition the boundary, but not on the 40 means: you never get to know them precisely. Instead you have to condition on the 200 data points that you do get to see. So you will need 200 parameters, but due to the use of summation, the answer doesn't look too complicated. I would never be able to derive this formula, so I only take the credit for realizing that the analytical solution doesn't have to be ugly and then searching for it on google. Luckily, it's provided by the authors some nice people, pages 6-7.
Exercise 2.2 of The Elements of Statistical Learning
Actually, the book does ask to provide an analytical solution to this problem. And yes, you have to condition the boundary, but not on the 40 means: you never get to know them precisely. Instead you h
Exercise 2.2 of The Elements of Statistical Learning Actually, the book does ask to provide an analytical solution to this problem. And yes, you have to condition the boundary, but not on the 40 means: you never get to know them precisely. Instead you have to condition on the 200 data points that you do get to see. So you will need 200 parameters, but due to the use of summation, the answer doesn't look too complicated. I would never be able to derive this formula, so I only take the credit for realizing that the analytical solution doesn't have to be ugly and then searching for it on google. Luckily, it's provided by the authors some nice people, pages 6-7.
Exercise 2.2 of The Elements of Statistical Learning Actually, the book does ask to provide an analytical solution to this problem. And yes, you have to condition the boundary, but not on the 40 means: you never get to know them precisely. Instead you h
28,245
Exercise 2.2 of The Elements of Statistical Learning
Wish i stumbled upon code per above earlier ; just finsihed creating some alternative code per below... for what it is worth set.seed(1) library(MASS) #create original 10 center points/means for each class I.mat=diag(2) mu1=c(1,0);mu2=c(0,1) mv.dist1=mvrnorm(n = 10, mu1, I.mat) mv.dist2=mvrnorm(n = 10, mu2, I.mat) values1=NULL;values2=NULL #create 100 observations for each class, after random sampling of a center point, based on an assumed bivariate probability distribution around each center point for(i in 1:10){ mv.values1=mv.dist1[sample(nrow(mv.dist1),size=1,replace=TRUE),] sub.mv.dist1=mvrnorm(n = 10, mv.values1, I.mat/5) values1=rbind(sub.mv.dist1,values1) } values1 #similar as per above, for second class for(i in 1:10){ mv.values2=mv.dist2[sample(nrow(mv.dist2),size=1,replace=TRUE),] sub.mv.dist2=mvrnorm(n = 10, mv.values2, I.mat/5) values2=rbind(sub.mv.dist2,values2) } values2 #did not find probability function in MASS, so used mnormt library(mnormt) #create grid of points grid.vector1=seq(-2,2,0.1) grid.vector2=seq(-2,2,0.1) length(grid.vector1)*length(grid.vector2) grid=expand.grid(grid.vector1,grid.vector2) #calculate density for each point on grid for each of the 100 multivariates distributions prob.1=matrix(0:0,nrow=1681,ncol=10) #initialize grid for (i in 1:1681){ for (j in 1:10){ prob.1[i,j]=dmnorm(grid[i,], mv.dist1[j,], I.mat/5) } } prob.1 prob1.max=apply(prob.1,1,max) #second class - as per above prob.2=matrix(0:0,nrow=1681,ncol=10) #initialize grid for (i in 1:1681){ for (j in 1:10){ prob.2[i,j]=dmnorm(grid[i,], mv.dist2[j,], I.mat/5) } } prob.2 prob2.max=apply(prob.2,1,max) #bind prob.total=cbind(prob1.max,prob2.max) class=rep(1,1681) class[prob1.max<prob2.max]=2 cbind(prob.total,class) #plot points plot(grid[,1], grid[,2],pch=".", cex=3,col=ifelse(class==1, "coral", "cornflowerblue")) points(values1,col="coral") points(values2,col="cornflowerblue") #check - original centers # points(mv.dist1,col="coral") # points(mv.dist2,col="cornflowerblue")
Exercise 2.2 of The Elements of Statistical Learning
Wish i stumbled upon code per above earlier ; just finsihed creating some alternative code per below... for what it is worth set.seed(1) library(MASS) #create original 10 center points/means for eac
Exercise 2.2 of The Elements of Statistical Learning Wish i stumbled upon code per above earlier ; just finsihed creating some alternative code per below... for what it is worth set.seed(1) library(MASS) #create original 10 center points/means for each class I.mat=diag(2) mu1=c(1,0);mu2=c(0,1) mv.dist1=mvrnorm(n = 10, mu1, I.mat) mv.dist2=mvrnorm(n = 10, mu2, I.mat) values1=NULL;values2=NULL #create 100 observations for each class, after random sampling of a center point, based on an assumed bivariate probability distribution around each center point for(i in 1:10){ mv.values1=mv.dist1[sample(nrow(mv.dist1),size=1,replace=TRUE),] sub.mv.dist1=mvrnorm(n = 10, mv.values1, I.mat/5) values1=rbind(sub.mv.dist1,values1) } values1 #similar as per above, for second class for(i in 1:10){ mv.values2=mv.dist2[sample(nrow(mv.dist2),size=1,replace=TRUE),] sub.mv.dist2=mvrnorm(n = 10, mv.values2, I.mat/5) values2=rbind(sub.mv.dist2,values2) } values2 #did not find probability function in MASS, so used mnormt library(mnormt) #create grid of points grid.vector1=seq(-2,2,0.1) grid.vector2=seq(-2,2,0.1) length(grid.vector1)*length(grid.vector2) grid=expand.grid(grid.vector1,grid.vector2) #calculate density for each point on grid for each of the 100 multivariates distributions prob.1=matrix(0:0,nrow=1681,ncol=10) #initialize grid for (i in 1:1681){ for (j in 1:10){ prob.1[i,j]=dmnorm(grid[i,], mv.dist1[j,], I.mat/5) } } prob.1 prob1.max=apply(prob.1,1,max) #second class - as per above prob.2=matrix(0:0,nrow=1681,ncol=10) #initialize grid for (i in 1:1681){ for (j in 1:10){ prob.2[i,j]=dmnorm(grid[i,], mv.dist2[j,], I.mat/5) } } prob.2 prob2.max=apply(prob.2,1,max) #bind prob.total=cbind(prob1.max,prob2.max) class=rep(1,1681) class[prob1.max<prob2.max]=2 cbind(prob.total,class) #plot points plot(grid[,1], grid[,2],pch=".", cex=3,col=ifelse(class==1, "coral", "cornflowerblue")) points(values1,col="coral") points(values2,col="cornflowerblue") #check - original centers # points(mv.dist1,col="coral") # points(mv.dist2,col="cornflowerblue")
Exercise 2.2 of The Elements of Statistical Learning Wish i stumbled upon code per above earlier ; just finsihed creating some alternative code per below... for what it is worth set.seed(1) library(MASS) #create original 10 center points/means for eac
28,246
Standard error of slopes in piecewise linear regression with known breakpoints
How to easily calculate the intercept and slope of each segment? The slope of each segment is calculated by simply adding all the coefficients up to the current position. So the slope estimate at $x=15$ is $-1.1003 + 1.3760 = 0.2757\,$. The intercept is a little harder, but it's a linear combination of coefficients (involving the knots). In your example, the second line meets the first at $x=9.6$, so the red point is on the first line at $21.7057 -1.1003 \times 9.6 = 11.1428$. Since the second line passes through the point $(9.6, 11.428)$ with slope $0.2757$, its intercept is $11.1428 - 0.2757 \times 9.6 = 8.496$. Of course, you can put those steps together and it simplifies right down to the intercept for the second segment = $\beta_0 - \beta_2 k_1 = 21.7057 - 1.3760 \times 9.6$. Can the model be reparameterized to do this in one calculation? Well, yes, but it's probably easier in general to just compute it from the model. 2. How to calculate the standard error of each slope of each segment? Since the estimate is a linear combination of regression coefficients $a^\top\hat\beta$, where $a$ consists of 1's and 0s, the variance is $a^\top\text{Var}(\hat\beta)a$. The standard error is the square root of that sum of variance and covariance terms. e.g. in your example, the standard error of the slope of the second segment is: Sb <- vcov(mod)[2:3,2:3] sqrt(sum(Sb)) alternatively in matrix form: Sb <- vcov(mod) a <- matrix(c(0,1,1),nr=3) sqrt(t(a) %*% Sb %*% a) 3. How to test whether two adjacent slopes have the same slopes (i.e. whether the breakpoint can be omitted)? This is tested by looking at the coefficient in the table of that segment. See this line: I(pmax(x - 9.6, 0)) 1.3760 0.2688 5.120 8.54e-05 *** That's the change in slope at 9.6. If that change is different from 0, the two slopes aren't the same. So the p-value for a test that the second segment has the same slope as the first is right at the end of that line.
Standard error of slopes in piecewise linear regression with known breakpoints
How to easily calculate the intercept and slope of each segment? The slope of each segment is calculated by simply adding all the coefficients up to the current position. So the slope estimate at $
Standard error of slopes in piecewise linear regression with known breakpoints How to easily calculate the intercept and slope of each segment? The slope of each segment is calculated by simply adding all the coefficients up to the current position. So the slope estimate at $x=15$ is $-1.1003 + 1.3760 = 0.2757\,$. The intercept is a little harder, but it's a linear combination of coefficients (involving the knots). In your example, the second line meets the first at $x=9.6$, so the red point is on the first line at $21.7057 -1.1003 \times 9.6 = 11.1428$. Since the second line passes through the point $(9.6, 11.428)$ with slope $0.2757$, its intercept is $11.1428 - 0.2757 \times 9.6 = 8.496$. Of course, you can put those steps together and it simplifies right down to the intercept for the second segment = $\beta_0 - \beta_2 k_1 = 21.7057 - 1.3760 \times 9.6$. Can the model be reparameterized to do this in one calculation? Well, yes, but it's probably easier in general to just compute it from the model. 2. How to calculate the standard error of each slope of each segment? Since the estimate is a linear combination of regression coefficients $a^\top\hat\beta$, where $a$ consists of 1's and 0s, the variance is $a^\top\text{Var}(\hat\beta)a$. The standard error is the square root of that sum of variance and covariance terms. e.g. in your example, the standard error of the slope of the second segment is: Sb <- vcov(mod)[2:3,2:3] sqrt(sum(Sb)) alternatively in matrix form: Sb <- vcov(mod) a <- matrix(c(0,1,1),nr=3) sqrt(t(a) %*% Sb %*% a) 3. How to test whether two adjacent slopes have the same slopes (i.e. whether the breakpoint can be omitted)? This is tested by looking at the coefficient in the table of that segment. See this line: I(pmax(x - 9.6, 0)) 1.3760 0.2688 5.120 8.54e-05 *** That's the change in slope at 9.6. If that change is different from 0, the two slopes aren't the same. So the p-value for a test that the second segment has the same slope as the first is right at the end of that line.
Standard error of slopes in piecewise linear regression with known breakpoints How to easily calculate the intercept and slope of each segment? The slope of each segment is calculated by simply adding all the coefficients up to the current position. So the slope estimate at $
28,247
Standard error of slopes in piecewise linear regression with known breakpoints
My naive approach, which answers question 1: mod2 <- lm(y~I((x<9.6)*x)+as.numeric((x<9.6))+ I((x>=9.6)*x)+as.numeric((x>=9.6))-1) summary(mod2) # Estimate Std. Error t value Pr(>|t|) # I((x < 9.6) * x) -1.1040 0.2328 -4.743 0.000221 *** # as.numeric((x < 9.6)) 21.7188 1.3099 16.580 1.69e-11 *** # I((x >= 9.6) * x) 0.2731 0.1560 1.751 0.099144 . # as.numeric((x >= 9.6)) 8.5442 2.6790 3.189 0.005704 ** But I'm not sure if the statistics (in particular degrees of freedom) are done correctly, if you do it this way.
Standard error of slopes in piecewise linear regression with known breakpoints
My naive approach, which answers question 1: mod2 <- lm(y~I((x<9.6)*x)+as.numeric((x<9.6))+ I((x>=9.6)*x)+as.numeric((x>=9.6))-1) summary(mod2) # Estimate Std. Err
Standard error of slopes in piecewise linear regression with known breakpoints My naive approach, which answers question 1: mod2 <- lm(y~I((x<9.6)*x)+as.numeric((x<9.6))+ I((x>=9.6)*x)+as.numeric((x>=9.6))-1) summary(mod2) # Estimate Std. Error t value Pr(>|t|) # I((x < 9.6) * x) -1.1040 0.2328 -4.743 0.000221 *** # as.numeric((x < 9.6)) 21.7188 1.3099 16.580 1.69e-11 *** # I((x >= 9.6) * x) 0.2731 0.1560 1.751 0.099144 . # as.numeric((x >= 9.6)) 8.5442 2.6790 3.189 0.005704 ** But I'm not sure if the statistics (in particular degrees of freedom) are done correctly, if you do it this way.
Standard error of slopes in piecewise linear regression with known breakpoints My naive approach, which answers question 1: mod2 <- lm(y~I((x<9.6)*x)+as.numeric((x<9.6))+ I((x>=9.6)*x)+as.numeric((x>=9.6))-1) summary(mod2) # Estimate Std. Err
28,248
By using SMOTE the classification of the validation set is bad
If you oversample the training data to change the relative class frequencies in the training set, you are implicitly telling the classifier to expect the validation set to have those same class frequencies. As the class frequencies influence the decision boundary, if the validation set class frequencies are different, then the classification boundary will be wrong as a result and performance will be sub-optimal. Now it is true that for some classifiers, having imbalanced classes can cause it to perform badly, and re-sampling the data can help to correct this. However if you oversample the minority class too much, you will over-correct and performance will be suboptimal because the the difference in class frequencies between the training and validation sets is more than is needed to correct the imbalance problem. My recipe then would be to use cross-validation to choose the degree of oversampling that is required to just compensate for the "class imbalance problem" experienced by your classifier, but no more. Note however this leads to an additional parameter that needs to be tuned, which leads to greater computational expense, and a higher likelihood of over-fitting in model selection (if the total number of tunable parameters is non-negligible).
By using SMOTE the classification of the validation set is bad
If you oversample the training data to change the relative class frequencies in the training set, you are implicitly telling the classifier to expect the validation set to have those same class freque
By using SMOTE the classification of the validation set is bad If you oversample the training data to change the relative class frequencies in the training set, you are implicitly telling the classifier to expect the validation set to have those same class frequencies. As the class frequencies influence the decision boundary, if the validation set class frequencies are different, then the classification boundary will be wrong as a result and performance will be sub-optimal. Now it is true that for some classifiers, having imbalanced classes can cause it to perform badly, and re-sampling the data can help to correct this. However if you oversample the minority class too much, you will over-correct and performance will be suboptimal because the the difference in class frequencies between the training and validation sets is more than is needed to correct the imbalance problem. My recipe then would be to use cross-validation to choose the degree of oversampling that is required to just compensate for the "class imbalance problem" experienced by your classifier, but no more. Note however this leads to an additional parameter that needs to be tuned, which leads to greater computational expense, and a higher likelihood of over-fitting in model selection (if the total number of tunable parameters is non-negligible).
By using SMOTE the classification of the validation set is bad If you oversample the training data to change the relative class frequencies in the training set, you are implicitly telling the classifier to expect the validation set to have those same class freque
28,249
By using SMOTE the classification of the validation set is bad
Have you considered using the R implementation of random forest via Rpy? It has an option that allows you to choose both the sample size that each tree is trained on and the fraction falling into each class. I've found it to be the most effective way to deal with imbalance when using random forest.
By using SMOTE the classification of the validation set is bad
Have you considered using the R implementation of random forest via Rpy? It has an option that allows you to choose both the sample size that each tree is trained on and the fraction falling into each
By using SMOTE the classification of the validation set is bad Have you considered using the R implementation of random forest via Rpy? It has an option that allows you to choose both the sample size that each tree is trained on and the fraction falling into each class. I've found it to be the most effective way to deal with imbalance when using random forest.
By using SMOTE the classification of the validation set is bad Have you considered using the R implementation of random forest via Rpy? It has an option that allows you to choose both the sample size that each tree is trained on and the fraction falling into each
28,250
Goodness of fit to Poisson Distribution
1) There are two issues with the Kolmogorov-Smirnov* - a) it assumes the distribution is completely specified, with no estimated parameters. If you estimate parameters a KS becomes a form of Lilliefors test (in this case for Poisson-ness), and you need different critical values b) it assumes the distribution is continuous both impact the calculation of p-values, and both make it less likely to reject. *(and the Cramer-von Mises and the Anderson Darling, and any other test that assumes a continuous, completely specified null) Unless you don't mind a potentially highly-conservative test (of unknown size), you have to adjust the calculation of the significance for both of these; simulation would be called for. 2) on the other hand, a vanilla chi-square goodness of fit is a terrible idea when testing something that's ordered, as a Poisson is. By ignoring ordering, it's really not very sensitive to the more interesting alternatives - it throws away power against directly interesting alternatives like overdispersion, instead spending its power against things like 'an excess of even numbers over odd numbers'. As a result its power against interesting alternatives is generally even lower than the vanilla KS but without the compensation of the much lower type I error rate. I think this is even worse. 3) on the gripping hand, you can partition the chi-squared into components that do respect the ordering via the use of orthogonal polynomials, and drop off the less interesting highest-order components. In this particular case you'd use polynomials orthogonal to the Poisson p.f. This is an approach taken in Rayner and Best's little 1989 book on Smooth Tests of Goodness of Fit (they have a newer one on smooth tests in R that might make your life easier) Alternatively, see papers like this one: http://www.jstor.org/discover/10.2307/1403470 4) However, depending on why you're doing it, it may be better to reconsider the whole enterprise... The discussion in questions like these carry over to most goodness of fit tests ... and indeed often to most tests of assumptions in general: Is normality testing 'essentially useless'? What tests do I use to confirm that residuals are normally distributed?
Goodness of fit to Poisson Distribution
1) There are two issues with the Kolmogorov-Smirnov* - a) it assumes the distribution is completely specified, with no estimated parameters. If you estimate parameters a KS becomes a form of Lilliefor
Goodness of fit to Poisson Distribution 1) There are two issues with the Kolmogorov-Smirnov* - a) it assumes the distribution is completely specified, with no estimated parameters. If you estimate parameters a KS becomes a form of Lilliefors test (in this case for Poisson-ness), and you need different critical values b) it assumes the distribution is continuous both impact the calculation of p-values, and both make it less likely to reject. *(and the Cramer-von Mises and the Anderson Darling, and any other test that assumes a continuous, completely specified null) Unless you don't mind a potentially highly-conservative test (of unknown size), you have to adjust the calculation of the significance for both of these; simulation would be called for. 2) on the other hand, a vanilla chi-square goodness of fit is a terrible idea when testing something that's ordered, as a Poisson is. By ignoring ordering, it's really not very sensitive to the more interesting alternatives - it throws away power against directly interesting alternatives like overdispersion, instead spending its power against things like 'an excess of even numbers over odd numbers'. As a result its power against interesting alternatives is generally even lower than the vanilla KS but without the compensation of the much lower type I error rate. I think this is even worse. 3) on the gripping hand, you can partition the chi-squared into components that do respect the ordering via the use of orthogonal polynomials, and drop off the less interesting highest-order components. In this particular case you'd use polynomials orthogonal to the Poisson p.f. This is an approach taken in Rayner and Best's little 1989 book on Smooth Tests of Goodness of Fit (they have a newer one on smooth tests in R that might make your life easier) Alternatively, see papers like this one: http://www.jstor.org/discover/10.2307/1403470 4) However, depending on why you're doing it, it may be better to reconsider the whole enterprise... The discussion in questions like these carry over to most goodness of fit tests ... and indeed often to most tests of assumptions in general: Is normality testing 'essentially useless'? What tests do I use to confirm that residuals are normally distributed?
Goodness of fit to Poisson Distribution 1) There are two issues with the Kolmogorov-Smirnov* - a) it assumes the distribution is completely specified, with no estimated parameters. If you estimate parameters a KS becomes a form of Lilliefor
28,251
Goodness of fit to Poisson Distribution
The KS-Test and other tests such as Anderson Darling are used for continuous distributions. For discrete distributions, you can use the Chi-Square goodness of fit test, which is based on comparing the #observed events vs. the number of expected based on the expected number for your distribution. If the parameter is known for the Poisson distribution you would obviously use that, more likely you will estimate the parameter using MLE, which reduces the degrees of freedom in your Chi-sq test. An example is here; you would just adapt it to your specific distribution: http://www.stat.yale.edu/Courses/1997-98/101/chigf.htm
Goodness of fit to Poisson Distribution
The KS-Test and other tests such as Anderson Darling are used for continuous distributions. For discrete distributions, you can use the Chi-Square goodness of fit test, which is based on comparing th
Goodness of fit to Poisson Distribution The KS-Test and other tests such as Anderson Darling are used for continuous distributions. For discrete distributions, you can use the Chi-Square goodness of fit test, which is based on comparing the #observed events vs. the number of expected based on the expected number for your distribution. If the parameter is known for the Poisson distribution you would obviously use that, more likely you will estimate the parameter using MLE, which reduces the degrees of freedom in your Chi-sq test. An example is here; you would just adapt it to your specific distribution: http://www.stat.yale.edu/Courses/1997-98/101/chigf.htm
Goodness of fit to Poisson Distribution The KS-Test and other tests such as Anderson Darling are used for continuous distributions. For discrete distributions, you can use the Chi-Square goodness of fit test, which is based on comparing th
28,252
Given a coin with unknown bias, generate variates from a fair coin efficiently
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. This is a well-known problem with several nice solutions which have been discussed here and in stackoverflow (it seems like I cannot post more than one link but a quick google search gives you some interesting entries). Have a look at the wikipedia entry http://en.wikipedia.org/wiki/Fair_coin#Fair_results_from_a_biased_coin
Given a coin with unknown bias, generate variates from a fair coin efficiently
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Given a coin with unknown bias, generate variates from a fair coin efficiently Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. This is a well-known problem with several nice solutions which have been discussed here and in stackoverflow (it seems like I cannot post more than one link but a quick google search gives you some interesting entries). Have a look at the wikipedia entry http://en.wikipedia.org/wiki/Fair_coin#Fair_results_from_a_biased_coin
Given a coin with unknown bias, generate variates from a fair coin efficiently Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
28,253
Given a coin with unknown bias, generate variates from a fair coin efficiently
This is a classic problem, I believe attributed originally to von Neumann. One solution is to keep tossing the coin in pairs until the pairs are different, and then defer to the outcome of the first coin in the pair. Explicitely let $(X_i,Y_i)$ be the outcome of toss $i$, with $X_i$ being the first coin, and $Y_i$ being the second coin. Each coin has probability $p$ of heads. Then $P(X_i=H|X_i\neq Y_i)=P(X_i=T|X_i\neq Y_i)$ due to symmetry, which implies $P(X_i=H|X_i\neq Y_i)=1/2$. To explitely see this symmetry note that $X_i\neq Y_i$ implies the outcomes are $(H,T)$ or $(T,H)$, both of which are equally likely due to independence. Empirically, the waiting time until such an unequal pair is $$1/P(X\neq Y)=\frac{1}{1-p^2-(1-p)^2}=\frac{1}{2p(1-p)},$$ which blows up as $p$ gets closer to 0 or 1 (which makes sense).
Given a coin with unknown bias, generate variates from a fair coin efficiently
This is a classic problem, I believe attributed originally to von Neumann. One solution is to keep tossing the coin in pairs until the pairs are different, and then defer to the outcome of the first c
Given a coin with unknown bias, generate variates from a fair coin efficiently This is a classic problem, I believe attributed originally to von Neumann. One solution is to keep tossing the coin in pairs until the pairs are different, and then defer to the outcome of the first coin in the pair. Explicitely let $(X_i,Y_i)$ be the outcome of toss $i$, with $X_i$ being the first coin, and $Y_i$ being the second coin. Each coin has probability $p$ of heads. Then $P(X_i=H|X_i\neq Y_i)=P(X_i=T|X_i\neq Y_i)$ due to symmetry, which implies $P(X_i=H|X_i\neq Y_i)=1/2$. To explitely see this symmetry note that $X_i\neq Y_i$ implies the outcomes are $(H,T)$ or $(T,H)$, both of which are equally likely due to independence. Empirically, the waiting time until such an unequal pair is $$1/P(X\neq Y)=\frac{1}{1-p^2-(1-p)^2}=\frac{1}{2p(1-p)},$$ which blows up as $p$ gets closer to 0 or 1 (which makes sense).
Given a coin with unknown bias, generate variates from a fair coin efficiently This is a classic problem, I believe attributed originally to von Neumann. One solution is to keep tossing the coin in pairs until the pairs are different, and then defer to the outcome of the first c
28,254
Given a coin with unknown bias, generate variates from a fair coin efficiently
I'm not sure how to sum up the terms efficiently, but we can stop whenever the total number of rolls $n$ and the total number of successes $t$ are such that $\binom{n}{t}$ is even since we can partition the different orderings that we could have achieved $n$ and $t$ into two groups of equal probability each corresponding to a different outputted label. We need to be careful that we haven't already stopped for these elements, i.e., that no element has a prefix of length $n'$ with $t'$ successes such that $\binom{n'}{t'}$ is even. I'm not sure how to turn this into an expected number of flips. To illustrate: We can stop at TH or HT since these have equal probability. Moving down Pascal's triangle, the next even terms are in the fourth row: 4, 6, 4. Meaning that we can stop after rolls if one heads has come up since we can create a bipartite matching: HHHT with HHTH, and technically HTHH with THHH although we would already have stopped for those. Similarly, $\binom42$ yields the matching HHTT with TTHH (the rest, we would already have stopped before reaching them). For $\binom52$, all of the sequences have stopped prefixes. It gets a bit more interesting at $\binom83$ where we match FFFFTTFT with FFFFTTTF. For $p=\frac12$ after 8 rolls, the chance of not having stopped is $\frac1{128}$ with an expected number of rolls if we have stopped of $\frac{53}{16}$. For the solution where we keep rolling pairs until they differ, the chance of not having stopped is $\frac{1}{16}$ with an expected number of rolls if we have stopped of 4. By recursion, an upper bound on the expected flips for the algorithm presented is $\frac{128}{127} \cdot \frac{53}{16} = \frac{424}{127} < 4$. I wrote a Python program to print out the stopping points: import scipy.misc from collections import defaultdict bins = defaultdict(list) def go(depth, seq=[], k=0): n = len(seq) if scipy.misc.comb(n, k, True) % 2 == 0: bins[(n,k)].append("".join("T" if x else "F" for x in seq)) return if n < depth: for i in range(2): seq.append(i) go(depth, seq, k+i) seq.pop() go(8) for key, value in sorted(bins.items()): for i, v in enumerate(value): print(v, "->", "F" if i < len(value) // 2 else "T") print() prints: FT -> F TF -> T FFFT -> F FFTF -> T FFTT -> F TTFF -> T TTFT -> F TTTF -> T FFFFFT -> F FFFFTF -> T TTTTFT -> F TTTTTF -> T FFFFFFFT -> F FFFFFFTF -> T FFFFFFTT -> F FFFFTTFF -> T FFFFTTFT -> F FFFFTTTF -> T FFFFTTTT -> F TTTTFFFF -> T TTTTFFFT -> F TTTTFFTF -> T TTTTFFTT -> F TTTTTTFF -> T TTTTTTFT -> F TTTTTTTF -> T
Given a coin with unknown bias, generate variates from a fair coin efficiently
I'm not sure how to sum up the terms efficiently, but we can stop whenever the total number of rolls $n$ and the total number of successes $t$ are such that $\binom{n}{t}$ is even since we can partiti
Given a coin with unknown bias, generate variates from a fair coin efficiently I'm not sure how to sum up the terms efficiently, but we can stop whenever the total number of rolls $n$ and the total number of successes $t$ are such that $\binom{n}{t}$ is even since we can partition the different orderings that we could have achieved $n$ and $t$ into two groups of equal probability each corresponding to a different outputted label. We need to be careful that we haven't already stopped for these elements, i.e., that no element has a prefix of length $n'$ with $t'$ successes such that $\binom{n'}{t'}$ is even. I'm not sure how to turn this into an expected number of flips. To illustrate: We can stop at TH or HT since these have equal probability. Moving down Pascal's triangle, the next even terms are in the fourth row: 4, 6, 4. Meaning that we can stop after rolls if one heads has come up since we can create a bipartite matching: HHHT with HHTH, and technically HTHH with THHH although we would already have stopped for those. Similarly, $\binom42$ yields the matching HHTT with TTHH (the rest, we would already have stopped before reaching them). For $\binom52$, all of the sequences have stopped prefixes. It gets a bit more interesting at $\binom83$ where we match FFFFTTFT with FFFFTTTF. For $p=\frac12$ after 8 rolls, the chance of not having stopped is $\frac1{128}$ with an expected number of rolls if we have stopped of $\frac{53}{16}$. For the solution where we keep rolling pairs until they differ, the chance of not having stopped is $\frac{1}{16}$ with an expected number of rolls if we have stopped of 4. By recursion, an upper bound on the expected flips for the algorithm presented is $\frac{128}{127} \cdot \frac{53}{16} = \frac{424}{127} < 4$. I wrote a Python program to print out the stopping points: import scipy.misc from collections import defaultdict bins = defaultdict(list) def go(depth, seq=[], k=0): n = len(seq) if scipy.misc.comb(n, k, True) % 2 == 0: bins[(n,k)].append("".join("T" if x else "F" for x in seq)) return if n < depth: for i in range(2): seq.append(i) go(depth, seq, k+i) seq.pop() go(8) for key, value in sorted(bins.items()): for i, v in enumerate(value): print(v, "->", "F" if i < len(value) // 2 else "T") print() prints: FT -> F TF -> T FFFT -> F FFTF -> T FFTT -> F TTFF -> T TTFT -> F TTTF -> T FFFFFT -> F FFFFTF -> T TTTTFT -> F TTTTTF -> T FFFFFFFT -> F FFFFFFTF -> T FFFFFFTT -> F FFFFTTFF -> T FFFFTTFT -> F FFFFTTTF -> T FFFFTTTT -> F TTTTFFFF -> T TTTTFFFT -> F TTTTFFTF -> T TTTTFFTT -> F TTTTTTFF -> T TTTTTTFT -> F TTTTTTTF -> T
Given a coin with unknown bias, generate variates from a fair coin efficiently I'm not sure how to sum up the terms efficiently, but we can stop whenever the total number of rolls $n$ and the total number of successes $t$ are such that $\binom{n}{t}$ is even since we can partiti
28,255
Imputation with Random Forests
The basic idea is to do a quick replacement of missing data and then iteratively improve the missing imputation using proximity. To work with unlabeled data, just replicate the data with all labels, and then treat it as labeled data. The fraction of trees for which a pair of observations share a terminal node gives the proximity matrix, and so explicitly uses the class label. Training set: Replace missing values by the average value. Repeat until satisfied: a. Using imputed values calculated so far, train a random forest. b. Compute the proximity matrix. c. Using the proximity as the weight, impute missing values as the weighted average of non-missing values. Test set: If labels exist, use the imputation derived from test data. If data is unlabeled, replicate the test set with a copy for each class label and proceed as with labeled data. Here, (weighted) average refers to (weighted) median for numerical variables and (weighted) mode for categorical variables. 4-6 iterations are recommended in the references. R documentation (pdf), Breiman's manual v4.0 (pdf), Breiman's RF page
Imputation with Random Forests
The basic idea is to do a quick replacement of missing data and then iteratively improve the missing imputation using proximity. To work with unlabeled data, just replicate the data with all labels,
Imputation with Random Forests The basic idea is to do a quick replacement of missing data and then iteratively improve the missing imputation using proximity. To work with unlabeled data, just replicate the data with all labels, and then treat it as labeled data. The fraction of trees for which a pair of observations share a terminal node gives the proximity matrix, and so explicitly uses the class label. Training set: Replace missing values by the average value. Repeat until satisfied: a. Using imputed values calculated so far, train a random forest. b. Compute the proximity matrix. c. Using the proximity as the weight, impute missing values as the weighted average of non-missing values. Test set: If labels exist, use the imputation derived from test data. If data is unlabeled, replicate the test set with a copy for each class label and proceed as with labeled data. Here, (weighted) average refers to (weighted) median for numerical variables and (weighted) mode for categorical variables. 4-6 iterations are recommended in the references. R documentation (pdf), Breiman's manual v4.0 (pdf), Breiman's RF page
Imputation with Random Forests The basic idea is to do a quick replacement of missing data and then iteratively improve the missing imputation using proximity. To work with unlabeled data, just replicate the data with all labels,
28,256
Imputation with Random Forests
I have tried using Random Forest for multiple imputation in MICE to handle missing data in survival analysis. I used bootstrapping to account for sampling variability in the imputation models. I found that Random Forest MICE performed better than parametric MICE when there were interactions between predictor variables that were not included in the imputation model. The CALIBERrfimpute package provides a function for Random Forest imputation in MICE: http://cran.r-project.org/web/packages/CALIBERrfimpute/index.html This is an article describing tests of the method on simulated data and a real epidemiological dataset: http://dx.doi.org/10.1093/aje/kwt312
Imputation with Random Forests
I have tried using Random Forest for multiple imputation in MICE to handle missing data in survival analysis. I used bootstrapping to account for sampling variability in the imputation models. I found
Imputation with Random Forests I have tried using Random Forest for multiple imputation in MICE to handle missing data in survival analysis. I used bootstrapping to account for sampling variability in the imputation models. I found that Random Forest MICE performed better than parametric MICE when there were interactions between predictor variables that were not included in the imputation model. The CALIBERrfimpute package provides a function for Random Forest imputation in MICE: http://cran.r-project.org/web/packages/CALIBERrfimpute/index.html This is an article describing tests of the method on simulated data and a real epidemiological dataset: http://dx.doi.org/10.1093/aje/kwt312
Imputation with Random Forests I have tried using Random Forest for multiple imputation in MICE to handle missing data in survival analysis. I used bootstrapping to account for sampling variability in the imputation models. I found
28,257
Imputation with Random Forests
The algorithm implemented in mice.impute.rf is described in Appendix A.1 of Doove, L.L., van Buuren, S., Dusseldorp, E. (2014), Recursive partitioning for missing data imputation in the presence of interaction Effects. Computational Statistics & Data Analysis, 72, 92-104. Available here: https://stefvanbuuren.name/publications/2014%20Recursive%20partitioning%20-%20CSDA.pdf In short, for each tree in the ensemble, the algorithm determines the leave from which a missing observation would be predicted, then the elements of all these resulting leaves are pooled together and the imputed value is randomly selected from them (the pooled elements make up a predictive distribution). There is no averaging across trees in order to preserve uncertainty of the imputed value.
Imputation with Random Forests
The algorithm implemented in mice.impute.rf is described in Appendix A.1 of Doove, L.L., van Buuren, S., Dusseldorp, E. (2014), Recursive partitioning for missing data imputation in the presence of in
Imputation with Random Forests The algorithm implemented in mice.impute.rf is described in Appendix A.1 of Doove, L.L., van Buuren, S., Dusseldorp, E. (2014), Recursive partitioning for missing data imputation in the presence of interaction Effects. Computational Statistics & Data Analysis, 72, 92-104. Available here: https://stefvanbuuren.name/publications/2014%20Recursive%20partitioning%20-%20CSDA.pdf In short, for each tree in the ensemble, the algorithm determines the leave from which a missing observation would be predicted, then the elements of all these resulting leaves are pooled together and the imputed value is randomly selected from them (the pooled elements make up a predictive distribution). There is no averaging across trees in order to preserve uncertainty of the imputed value.
Imputation with Random Forests The algorithm implemented in mice.impute.rf is described in Appendix A.1 of Doove, L.L., van Buuren, S., Dusseldorp, E. (2014), Recursive partitioning for missing data imputation in the presence of in
28,258
What is the correlation coefficient between two zero random variables?
The correlation is undefined. It should be an exception because the variance is zero. To see why limits won't work, let $X$ be any random variable with a nonzero variance and (without any loss of generality) suppose it has a mean of zero. Then the sequences of bivariate random variables $(X/n, X/n)$ and $(X/n, -X/n)$ both converge in probability to $(0,0)$ as $n\to\infty$, but the correlations in the first sequence are all $1$ and those in the second sequence are all $-1$. Thus you cannot sneak up on a correlation for $(0,0)$ by taking limits--the limit of the correlations can be $1$, $-1$ (or indeed any value in between).
What is the correlation coefficient between two zero random variables?
The correlation is undefined. It should be an exception because the variance is zero. To see why limits won't work, let $X$ be any random variable with a nonzero variance and (without any loss of gen
What is the correlation coefficient between two zero random variables? The correlation is undefined. It should be an exception because the variance is zero. To see why limits won't work, let $X$ be any random variable with a nonzero variance and (without any loss of generality) suppose it has a mean of zero. Then the sequences of bivariate random variables $(X/n, X/n)$ and $(X/n, -X/n)$ both converge in probability to $(0,0)$ as $n\to\infty$, but the correlations in the first sequence are all $1$ and those in the second sequence are all $-1$. Thus you cannot sneak up on a correlation for $(0,0)$ by taking limits--the limit of the correlations can be $1$, $-1$ (or indeed any value in between).
What is the correlation coefficient between two zero random variables? The correlation is undefined. It should be an exception because the variance is zero. To see why limits won't work, let $X$ be any random variable with a nonzero variance and (without any loss of gen
28,259
What is the correlation coefficient between two zero random variables?
$\frac{0}{0}$ seems correct to me. That is, it's meaningless. The correlation measures the linear relationship between two variables. But if either variable is a constant this is a meaningless idea. It isn't 0, it isn't 1, it's just ... not. So, $\frac{0}{0}$ seems right.
What is the correlation coefficient between two zero random variables?
$\frac{0}{0}$ seems correct to me. That is, it's meaningless. The correlation measures the linear relationship between two variables. But if either variable is a constant this is a meaningless idea. I
What is the correlation coefficient between two zero random variables? $\frac{0}{0}$ seems correct to me. That is, it's meaningless. The correlation measures the linear relationship between two variables. But if either variable is a constant this is a meaningless idea. It isn't 0, it isn't 1, it's just ... not. So, $\frac{0}{0}$ seems right.
What is the correlation coefficient between two zero random variables? $\frac{0}{0}$ seems correct to me. That is, it's meaningless. The correlation measures the linear relationship between two variables. But if either variable is a constant this is a meaningless idea. I
28,260
Bayes factors with improper priors
No. While improper priors can be okay for parameter estimation under certain circumstances (due to the Bernstein–von Mises theorem), they are a big no-no for model comparison, due to what is known as the marginalization paradox. The problem, as the name would suggest, is that the marginal distribution of an improper distribution is not well-defined. Given a likelihood $p_1(x \mid \theta)$ and a prior $p_1(\theta)$: the Bayes factor requires computing the marginal likelihood: $$p_1(x) = \int_\Theta p_1(x \mid \theta) p_1(\theta) d \theta .$$ If you think of an improper prior as being only known up to proportionality (e.g. $p_1(\theta) \propto 1$), then the problem is that $p_1(x)$ will be multiplied by an unknown constant. In a Bayes factor, you'll be computing the ratio of something with an unknown constant. Some authors, notably E.T. Jaynes, try to get around this by defining improper priors as the limit of a sequence of proper priors: then the problem is that there may be two different limiting sequences that then give different answers.
Bayes factors with improper priors
No. While improper priors can be okay for parameter estimation under certain circumstances (due to the Bernstein–von Mises theorem), they are a big no-no for model comparison, due to what is known as
Bayes factors with improper priors No. While improper priors can be okay for parameter estimation under certain circumstances (due to the Bernstein–von Mises theorem), they are a big no-no for model comparison, due to what is known as the marginalization paradox. The problem, as the name would suggest, is that the marginal distribution of an improper distribution is not well-defined. Given a likelihood $p_1(x \mid \theta)$ and a prior $p_1(\theta)$: the Bayes factor requires computing the marginal likelihood: $$p_1(x) = \int_\Theta p_1(x \mid \theta) p_1(\theta) d \theta .$$ If you think of an improper prior as being only known up to proportionality (e.g. $p_1(\theta) \propto 1$), then the problem is that $p_1(x)$ will be multiplied by an unknown constant. In a Bayes factor, you'll be computing the ratio of something with an unknown constant. Some authors, notably E.T. Jaynes, try to get around this by defining improper priors as the limit of a sequence of proper priors: then the problem is that there may be two different limiting sequences that then give different answers.
Bayes factors with improper priors No. While improper priors can be okay for parameter estimation under certain circumstances (due to the Bernstein–von Mises theorem), they are a big no-no for model comparison, due to what is known as
28,261
Understanding the intercept value in a multiple linear regression with categorical values
Contrary to intuition, this is not the mean value of breaks when wool=="A" and tension=="L". data(warpbreaks) aggregate(breaks ~ wool + tension, warpbreaks, mean) # wool tension breaks # 1 A L 44.55556 # 2 B L 28.22222 # 3 A M 24.00000 # 4 B M 28.77778 # 5 A H 24.55556 # 6 B H 18.77778 As @Macro explains in his comments, this depends very much on the model you fit. If you fit the full model (with interaction terms) you get the following: lm(breaks ~ wool * tension, data=warpbreaks) # # Call: # lm(formula = breaks ~ wool * tension, data = warpbreaks) # # Coefficients: # (Intercept) woolB tensionM tensionH woolB:tensionM # 44.56 -16.33 -20.56 -20.00 21.11 # woolB:tensionH # 10.56 where now the intercept is the mean values of breaks when wool=="A" and tension=="L". This is so because in the full model, there is one parameter per case (6 parameters in total as you can check), while in the additive model there are less parameters than cases (4 parameters in total). Even though the intercept is not the mean value, notice that the difference between the mean values of breaks when wool=="B" and when wool=="A" is equal to the parameter woolB aggregate(breaks ~ wool, data=warpbreaks, mean) # wool breaks # 1 A 31.03704 # 2 B 25.25926 25.25926 - 31.03704 # [1] -5.77778 Likewise, you can check that the same holds true for tension. aggregate(breaks ~ tension, data=warpbreaks, mean) # tension breaks # 1 L 36.38889 # 2 M 26.38889 # 3 H 21.66667 26.38889 - 36.38889 # [1] -10 21.66667 - 36.38889 # [1] -14.72222 In conclusion, when you fit an additive model (no interaction term), the parameters are the difference of the mean per category (of only one factor) and the intercept is the estimated value of the response variable for the first modalities of each factor under the assumption of additivity. This estimate may not be reasonable, if additivity does not hold. You can get an idea whether this assumption is reasonable by testing the nullity of interaction terms. anova(lm(breaks ~ wool*tension, data=warpbreaks)) # Analysis of Variance Table # # Response: breaks # Df Sum Sq Mean Sq F value Pr(>F) # wool 1 450.7 450.67 3.7653 0.0582130 . # tension 2 2034.3 1017.13 8.4980 0.0006926 *** # wool:tension 2 1002.8 501.39 4.1891 0.0210442 * # Residuals 48 5745.1 119.69 # --- # Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 As you can see, the p-value of the test is 0.021, which means that interaction terms can probably not be neglected and that the intercept estimate of the additive model is perhaps not meaningful.
Understanding the intercept value in a multiple linear regression with categorical values
Contrary to intuition, this is not the mean value of breaks when wool=="A" and tension=="L". data(warpbreaks) aggregate(breaks ~ wool + tension, warpbreaks, mean) # wool tension breaks # 1 A
Understanding the intercept value in a multiple linear regression with categorical values Contrary to intuition, this is not the mean value of breaks when wool=="A" and tension=="L". data(warpbreaks) aggregate(breaks ~ wool + tension, warpbreaks, mean) # wool tension breaks # 1 A L 44.55556 # 2 B L 28.22222 # 3 A M 24.00000 # 4 B M 28.77778 # 5 A H 24.55556 # 6 B H 18.77778 As @Macro explains in his comments, this depends very much on the model you fit. If you fit the full model (with interaction terms) you get the following: lm(breaks ~ wool * tension, data=warpbreaks) # # Call: # lm(formula = breaks ~ wool * tension, data = warpbreaks) # # Coefficients: # (Intercept) woolB tensionM tensionH woolB:tensionM # 44.56 -16.33 -20.56 -20.00 21.11 # woolB:tensionH # 10.56 where now the intercept is the mean values of breaks when wool=="A" and tension=="L". This is so because in the full model, there is one parameter per case (6 parameters in total as you can check), while in the additive model there are less parameters than cases (4 parameters in total). Even though the intercept is not the mean value, notice that the difference between the mean values of breaks when wool=="B" and when wool=="A" is equal to the parameter woolB aggregate(breaks ~ wool, data=warpbreaks, mean) # wool breaks # 1 A 31.03704 # 2 B 25.25926 25.25926 - 31.03704 # [1] -5.77778 Likewise, you can check that the same holds true for tension. aggregate(breaks ~ tension, data=warpbreaks, mean) # tension breaks # 1 L 36.38889 # 2 M 26.38889 # 3 H 21.66667 26.38889 - 36.38889 # [1] -10 21.66667 - 36.38889 # [1] -14.72222 In conclusion, when you fit an additive model (no interaction term), the parameters are the difference of the mean per category (of only one factor) and the intercept is the estimated value of the response variable for the first modalities of each factor under the assumption of additivity. This estimate may not be reasonable, if additivity does not hold. You can get an idea whether this assumption is reasonable by testing the nullity of interaction terms. anova(lm(breaks ~ wool*tension, data=warpbreaks)) # Analysis of Variance Table # # Response: breaks # Df Sum Sq Mean Sq F value Pr(>F) # wool 1 450.7 450.67 3.7653 0.0582130 . # tension 2 2034.3 1017.13 8.4980 0.0006926 *** # wool:tension 2 1002.8 501.39 4.1891 0.0210442 * # Residuals 48 5745.1 119.69 # --- # Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 As you can see, the p-value of the test is 0.021, which means that interaction terms can probably not be neglected and that the intercept estimate of the additive model is perhaps not meaningful.
Understanding the intercept value in a multiple linear regression with categorical values Contrary to intuition, this is not the mean value of breaks when wool=="A" and tension=="L". data(warpbreaks) aggregate(breaks ~ wool + tension, warpbreaks, mean) # wool tension breaks # 1 A
28,262
How do you calculate the expected value of $e^{-X}$?
As pointed out in the comments, your specific question can be solved by evaluating the moment generating function and $t=-1$, but it appears you may be asking the more general question of how to calculate the expected value of a function of a random variable. In general, if $X$ has density function $p$, then $$ E \left( f(X) \right) = \int_{D} f(x) p(x) dx $$ where $D$ denotes the support of the random variable. For discrete random variables, the corresponding expectation is $$ E \left( f(X) \right) = \sum_{x \in D} f(x) P(X=x) $$ These identities follow from the definition of expected value. In your example $f(X) = \exp(-X)$, so you would just plug that into the definition above. Continuous example: Suppose $X \sim N(0,1)$, then \begin{align*} E \left (\exp(-X) \right) &= \int_{-\infty}^{\infty} e^{-x} \frac{1}{\sqrt{2 \pi}} e^{-x^2/2} dx \\ &= \int_{-\infty}^{\infty} \frac{1}{\sqrt{2 \pi}} e^{-(x^2 + 2x)/2} dx \\ &= \int_{-\infty}^{\infty} \frac{1}{\sqrt{2 \pi}} e^{-(x^2 + 2x + 1)/2} e^{1/2} dx \\ &= e^{1/2} \int_{-\infty}^{\infty} \underbrace{\frac{1}{\sqrt{2 \pi}} e^{-(x+1)^2/2}}_{{\rm density \ of \ a \ N(-1,1)}} dx \\ &= e^{1/2} \end{align*} Discrete example: $X \sim {\rm Bernoulli}(p)$. Then \begin{align*} E \left( \exp(-X) \right) &= \sum_{i=0}^{1} e^{-i} P(X=i) \\ &= (1-p)e^0 + pe^{-1} \\ &= (1-p) + p/e \end{align*}
How do you calculate the expected value of $e^{-X}$?
As pointed out in the comments, your specific question can be solved by evaluating the moment generating function and $t=-1$, but it appears you may be asking the more general question of how to calcu
How do you calculate the expected value of $e^{-X}$? As pointed out in the comments, your specific question can be solved by evaluating the moment generating function and $t=-1$, but it appears you may be asking the more general question of how to calculate the expected value of a function of a random variable. In general, if $X$ has density function $p$, then $$ E \left( f(X) \right) = \int_{D} f(x) p(x) dx $$ where $D$ denotes the support of the random variable. For discrete random variables, the corresponding expectation is $$ E \left( f(X) \right) = \sum_{x \in D} f(x) P(X=x) $$ These identities follow from the definition of expected value. In your example $f(X) = \exp(-X)$, so you would just plug that into the definition above. Continuous example: Suppose $X \sim N(0,1)$, then \begin{align*} E \left (\exp(-X) \right) &= \int_{-\infty}^{\infty} e^{-x} \frac{1}{\sqrt{2 \pi}} e^{-x^2/2} dx \\ &= \int_{-\infty}^{\infty} \frac{1}{\sqrt{2 \pi}} e^{-(x^2 + 2x)/2} dx \\ &= \int_{-\infty}^{\infty} \frac{1}{\sqrt{2 \pi}} e^{-(x^2 + 2x + 1)/2} e^{1/2} dx \\ &= e^{1/2} \int_{-\infty}^{\infty} \underbrace{\frac{1}{\sqrt{2 \pi}} e^{-(x+1)^2/2}}_{{\rm density \ of \ a \ N(-1,1)}} dx \\ &= e^{1/2} \end{align*} Discrete example: $X \sim {\rm Bernoulli}(p)$. Then \begin{align*} E \left( \exp(-X) \right) &= \sum_{i=0}^{1} e^{-i} P(X=i) \\ &= (1-p)e^0 + pe^{-1} \\ &= (1-p) + p/e \end{align*}
How do you calculate the expected value of $e^{-X}$? As pointed out in the comments, your specific question can be solved by evaluating the moment generating function and $t=-1$, but it appears you may be asking the more general question of how to calcu
28,263
R linear regression categorical variable "hidden" value
Q: " ... how do I interpret the x2 value "High"? For example, what effect does "High" x2s have on the response variable in the example given here?? A: You have no doubt noticed that there is no mention of x2="High" in the output. At the moment x2High is chosen as the "base case". That's because you offered a factor variable with the default coding for levels despite an ordering that would have been L/M/H more naturally to the human mind. But "H" being lexically before both "L" and "M" in the alphabet, was chosen by R as the base case. Since 'x2' was not ordered, each of the reported contrasts were relative to x2="High" and so x2=="Low" was estimated at -0.78 relative to x2="High". At the moment the Intercept is the estimated value of "Y" when x2="High" and x1= 0. You probably want to re-run your regression after changing the levels ordering (but not making the factor ordered). x2a = factor(x2, levels=c("Low", "Medium", "High")) Then your 'Medium' and 'High' estimate will be more in line with what you expect. Edit: There are alternative coding arrangements (or more accurately arrangements of the model matrix.) The default choice for contrasts in R is "treatment contrasts" which specifies one factor level (or one particular combination of factor levels) as the reference level and reports estimated mean differences for other levels or combinations. You can, however have the reference level be the overall mean by forcing the Intercept to be 0 (not recommended) or using one of the other contrast choices: ?contrasts ?C # which also means you should _not_ use either "c" or "C" as variable names. You can choose different contrasts for different factors, although doing so would seem to impose an additional interpretive burden. S-Plus uses Helmert contrasts by default, and SAS uses treatment contrasts but chooses the last factor level rather than the first as the reference level.
R linear regression categorical variable "hidden" value
Q: " ... how do I interpret the x2 value "High"? For example, what effect does "High" x2s have on the response variable in the example given here?? A: You have no doubt noticed that there is no mentio
R linear regression categorical variable "hidden" value Q: " ... how do I interpret the x2 value "High"? For example, what effect does "High" x2s have on the response variable in the example given here?? A: You have no doubt noticed that there is no mention of x2="High" in the output. At the moment x2High is chosen as the "base case". That's because you offered a factor variable with the default coding for levels despite an ordering that would have been L/M/H more naturally to the human mind. But "H" being lexically before both "L" and "M" in the alphabet, was chosen by R as the base case. Since 'x2' was not ordered, each of the reported contrasts were relative to x2="High" and so x2=="Low" was estimated at -0.78 relative to x2="High". At the moment the Intercept is the estimated value of "Y" when x2="High" and x1= 0. You probably want to re-run your regression after changing the levels ordering (but not making the factor ordered). x2a = factor(x2, levels=c("Low", "Medium", "High")) Then your 'Medium' and 'High' estimate will be more in line with what you expect. Edit: There are alternative coding arrangements (or more accurately arrangements of the model matrix.) The default choice for contrasts in R is "treatment contrasts" which specifies one factor level (or one particular combination of factor levels) as the reference level and reports estimated mean differences for other levels or combinations. You can, however have the reference level be the overall mean by forcing the Intercept to be 0 (not recommended) or using one of the other contrast choices: ?contrasts ?C # which also means you should _not_ use either "c" or "C" as variable names. You can choose different contrasts for different factors, although doing so would seem to impose an additional interpretive burden. S-Plus uses Helmert contrasts by default, and SAS uses treatment contrasts but chooses the last factor level rather than the first as the reference level.
R linear regression categorical variable "hidden" value Q: " ... how do I interpret the x2 value "High"? For example, what effect does "High" x2s have on the response variable in the example given here?? A: You have no doubt noticed that there is no mentio
28,264
How to perform a Wilcoxon signed rank test for survival data in R?
(You should probably cite the source for your naming conventions and explain in more detail why this question is being posed. If this a case of trying to match the documentation for SAS or SPSS we might have cross-cultural difficulties.) The quick answer to your specific question about how to get a "Peto test" is to use rho=1, but it will be an approximation. Referring to the one-sample and two-sample sections of chapter 7 in Klein and Moeschberger's "Survival Analysis", we read that the Peto-Peto version and the Gehan versions were both two-sample (censored) versions of the Mann-Whitney Wilcoxon two-sample test but used different versions of the survival function estimator. There is no single 'Fleming-Harrington test' since that term refers to a family of tests which reduce to the log-rank and the Wilcoxon-type tests at specified values of rho. (The R/S surv.diff function has the q-parameter of the Fleming-Harrington family fixed at 0 and only varies the p-parameter which it names rho.) A meta-question is whether you should be focusing on the names and not on the mathematical substance? Choosing p=rho=0 (with q fixed at 0) in the Fleming-Harrington family weights the (O-E) or cross-group differences equally across the range of times, whereas both the Gehan-Wilcoxon and Peto-Peto tests weight the early deaths more strongly. My opinion (as a physician) is that it's sensible to have a weighting the considers early differences more probative for the typical case, but can imagine specific instances where the other choice could be defended.
How to perform a Wilcoxon signed rank test for survival data in R?
(You should probably cite the source for your naming conventions and explain in more detail why this question is being posed. If this a case of trying to match the documentation for SAS or SPSS we mig
How to perform a Wilcoxon signed rank test for survival data in R? (You should probably cite the source for your naming conventions and explain in more detail why this question is being posed. If this a case of trying to match the documentation for SAS or SPSS we might have cross-cultural difficulties.) The quick answer to your specific question about how to get a "Peto test" is to use rho=1, but it will be an approximation. Referring to the one-sample and two-sample sections of chapter 7 in Klein and Moeschberger's "Survival Analysis", we read that the Peto-Peto version and the Gehan versions were both two-sample (censored) versions of the Mann-Whitney Wilcoxon two-sample test but used different versions of the survival function estimator. There is no single 'Fleming-Harrington test' since that term refers to a family of tests which reduce to the log-rank and the Wilcoxon-type tests at specified values of rho. (The R/S surv.diff function has the q-parameter of the Fleming-Harrington family fixed at 0 and only varies the p-parameter which it names rho.) A meta-question is whether you should be focusing on the names and not on the mathematical substance? Choosing p=rho=0 (with q fixed at 0) in the Fleming-Harrington family weights the (O-E) or cross-group differences equally across the range of times, whereas both the Gehan-Wilcoxon and Peto-Peto tests weight the early deaths more strongly. My opinion (as a physician) is that it's sensible to have a weighting the considers early differences more probative for the typical case, but can imagine specific instances where the other choice could be defended.
How to perform a Wilcoxon signed rank test for survival data in R? (You should probably cite the source for your naming conventions and explain in more detail why this question is being posed. If this a case of trying to match the documentation for SAS or SPSS we mig
28,265
How to perform a Wilcoxon signed rank test for survival data in R?
To answer your question on how to calculate this in R, you can use the comp() function from the survMisc package. Example: > library(survMisc) > fit = survfit(Surv(time, status) ~ x, data = aml) > comp(fit)$tests$lrTests ChiSq df p Log-rank 3.40 1 0.0653 Gehan-Breslow (mod~ Wilcoxon) 2.72 1 0.0989 Tarone-Ware 2.98 1 0.0842 Peto-Peto 2.71 1 0.0998 Mod~ Peto-Peto (Andersen) 2.64 1 0.1042 Flem~-Harr~ with p=1, q=1 1.45 1 0.2281 To choose the parameters for the Fleming-Harrington test (shown in the last line), you use the FHp and FHq arguments. For example, > comp(fit, FHp=0, FHq=0)$tests$lrTests […] Flem~-Harr~ with p=0, q=0 3.40 1 0.0653 gives you the normal log-rank test (also shown in the first line in the first example).
How to perform a Wilcoxon signed rank test for survival data in R?
To answer your question on how to calculate this in R, you can use the comp() function from the survMisc package. Example: > library(survMisc) > fit = survfit(Surv(time, status) ~ x, data = aml) > com
How to perform a Wilcoxon signed rank test for survival data in R? To answer your question on how to calculate this in R, you can use the comp() function from the survMisc package. Example: > library(survMisc) > fit = survfit(Surv(time, status) ~ x, data = aml) > comp(fit)$tests$lrTests ChiSq df p Log-rank 3.40 1 0.0653 Gehan-Breslow (mod~ Wilcoxon) 2.72 1 0.0989 Tarone-Ware 2.98 1 0.0842 Peto-Peto 2.71 1 0.0998 Mod~ Peto-Peto (Andersen) 2.64 1 0.1042 Flem~-Harr~ with p=1, q=1 1.45 1 0.2281 To choose the parameters for the Fleming-Harrington test (shown in the last line), you use the FHp and FHq arguments. For example, > comp(fit, FHp=0, FHq=0)$tests$lrTests […] Flem~-Harr~ with p=0, q=0 3.40 1 0.0653 gives you the normal log-rank test (also shown in the first line in the first example).
How to perform a Wilcoxon signed rank test for survival data in R? To answer your question on how to calculate this in R, you can use the comp() function from the survMisc package. Example: > library(survMisc) > fit = survfit(Surv(time, status) ~ x, data = aml) > com
28,266
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted value?
As Ben Bolker says, the answer to this question can be found in the code for summary.lm(). Here's the header: function (object, correlation = FALSE, symbolic.cor = FALSE, ...) { So, let x <- 1:1000; y <- rep(1,1000); z <- lm(y ~ x) and then take a look at this slightly modified extract: p <- z$rank rdf <- z$df.residual Qr <- stats:::qr.lm(z) n <- NROW(Qr$qr) r <- z$residuals f <- z$fitted.values w <- z$weights if (is.null(w)) { mss <- sum((f - mean(f))^2) rss <- sum(r^2) } ans <- z[c("call", "terms")] if (p != attr(z$terms, "intercept")) { df.int <- 1L ans$r.squared <- mss/(mss + rss) ans$adj.r.squared <- 1 - (1 - ans$r.squared) * ((n - df.int)/rdf) } Notice that ans\$r.squared is $0.4998923$... To answer a question with a question: what do we draw from this? :) I believe the answer lies in how R handles floating point numbers. I think that mss and rss are the sums of very small (squared) rounding errors, hence the reason $R^2$ is about 0.5. As for the progression, I suspect this has to do with the number of values that it takes for the +/- approximations to cancel out to 0 (for both mss and rss, as 0/0 is likely the source of these NaN values). I don't know why the values differ from a 2^(1:k) progression, though. Update 1: Here is a nice thread from R-help addressing some of the reasons that underflow warnings are not addressed in R. In addition, this SO Q&A has a number of interesting posts and useful links regarding underflow, higher precision arithmetic, etc.
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted valu
As Ben Bolker says, the answer to this question can be found in the code for summary.lm(). Here's the header: function (object, correlation = FALSE, symbolic.cor = FALSE, ...) { So, let x <- 1:
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted value? As Ben Bolker says, the answer to this question can be found in the code for summary.lm(). Here's the header: function (object, correlation = FALSE, symbolic.cor = FALSE, ...) { So, let x <- 1:1000; y <- rep(1,1000); z <- lm(y ~ x) and then take a look at this slightly modified extract: p <- z$rank rdf <- z$df.residual Qr <- stats:::qr.lm(z) n <- NROW(Qr$qr) r <- z$residuals f <- z$fitted.values w <- z$weights if (is.null(w)) { mss <- sum((f - mean(f))^2) rss <- sum(r^2) } ans <- z[c("call", "terms")] if (p != attr(z$terms, "intercept")) { df.int <- 1L ans$r.squared <- mss/(mss + rss) ans$adj.r.squared <- 1 - (1 - ans$r.squared) * ((n - df.int)/rdf) } Notice that ans\$r.squared is $0.4998923$... To answer a question with a question: what do we draw from this? :) I believe the answer lies in how R handles floating point numbers. I think that mss and rss are the sums of very small (squared) rounding errors, hence the reason $R^2$ is about 0.5. As for the progression, I suspect this has to do with the number of values that it takes for the +/- approximations to cancel out to 0 (for both mss and rss, as 0/0 is likely the source of these NaN values). I don't know why the values differ from a 2^(1:k) progression, though. Update 1: Here is a nice thread from R-help addressing some of the reasons that underflow warnings are not addressed in R. In addition, this SO Q&A has a number of interesting posts and useful links regarding underflow, higher precision arithmetic, etc.
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted valu As Ben Bolker says, the answer to this question can be found in the code for summary.lm(). Here's the header: function (object, correlation = FALSE, symbolic.cor = FALSE, ...) { So, let x <- 1:
28,267
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted value?
I'm curious about your motivation for asking the question. I can't think of a practical reason this behavior should matter; intellectual curiosity is an alternative (and IMO much more sensible) reason. I think you don't need to understand FORTRAN to answer this question, but I think you do need to know about QR decomposition and its use in linear regression. If you treat dqrls as a black box that computes a QR decomposition and returns various information about it, then you may be able to trace the steps ... or just go straight to summary.lm and trace through to see how the R^2 is calculated. In particular: mss <- if (attr(z$terms, "intercept")) sum((f - mean(f))^2) else sum(f^2) rss <- sum(r^2) ## ... stuff ... ans$r.squared <- mss/(mss + rss) Then you have to go back into lm.fit and see that the fitted values are computed as r1 <- y - z$residuals (i.e. as the response minus the residuals). Now you can go figure out what determines the value of the residuals and whether the value minus its mean is exactly zero or not, and from there figure out the computational outcomes ...
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted valu
I'm curious about your motivation for asking the question. I can't think of a practical reason this behavior should matter; intellectual curiosity is an alternative (and IMO much more sensible) reason
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted value? I'm curious about your motivation for asking the question. I can't think of a practical reason this behavior should matter; intellectual curiosity is an alternative (and IMO much more sensible) reason. I think you don't need to understand FORTRAN to answer this question, but I think you do need to know about QR decomposition and its use in linear regression. If you treat dqrls as a black box that computes a QR decomposition and returns various information about it, then you may be able to trace the steps ... or just go straight to summary.lm and trace through to see how the R^2 is calculated. In particular: mss <- if (attr(z$terms, "intercept")) sum((f - mean(f))^2) else sum(f^2) rss <- sum(r^2) ## ... stuff ... ans$r.squared <- mss/(mss + rss) Then you have to go back into lm.fit and see that the fitted values are computed as r1 <- y - z$residuals (i.e. as the response minus the residuals). Now you can go figure out what determines the value of the residuals and whether the value minus its mean is exactly zero or not, and from there figure out the computational outcomes ...
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted valu I'm curious about your motivation for asking the question. I can't think of a practical reason this behavior should matter; intellectual curiosity is an alternative (and IMO much more sensible) reason
28,268
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted value?
$R^2$ is defined as $R^2 = 1-\frac{\textrm{SS}_{err}}{\textrm{SS}_{tot}}$ ( http://en.wikipedia.org/wiki/R_squared ), so if the sum-of-squares-total is 0 then it is undefined. In my opinion R should show an error-message.
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted valu
$R^2$ is defined as $R^2 = 1-\frac{\textrm{SS}_{err}}{\textrm{SS}_{tot}}$ ( http://en.wikipedia.org/wiki/R_squared ), so if the sum-of-squares-total is 0 then it is undefined. In my opinion R shou
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted value? $R^2$ is defined as $R^2 = 1-\frac{\textrm{SS}_{err}}{\textrm{SS}_{tot}}$ ( http://en.wikipedia.org/wiki/R_squared ), so if the sum-of-squares-total is 0 then it is undefined. In my opinion R should show an error-message.
Why is there an R^2 value (and what is determining it) when lm has no variance in the predicted valu $R^2$ is defined as $R^2 = 1-\frac{\textrm{SS}_{err}}{\textrm{SS}_{tot}}$ ( http://en.wikipedia.org/wiki/R_squared ), so if the sum-of-squares-total is 0 then it is undefined. In my opinion R shou
28,269
How to interpret logarithmically transformed coefficients in linear regression?
I think the more important point is suggested in @whuber's comment. Your whole approach is misfounded because by taking logarithms you effectively are throwing out of the dataset any students with zero missing days in either 2010 or 2011. It sounds like there are enough of these people to be a problem, and I am sure your results will be wrong based on the approach you are taking. Instead, you need to fit a generalized linear model with a poisson response. SPSS can't do this unless you have paid for the appropriate module, so I'd suggest upgrading to R. You will still have the problem of interpreting coefficients, but this is secondary to the importance of having a model that is basically appropriate.
How to interpret logarithmically transformed coefficients in linear regression?
I think the more important point is suggested in @whuber's comment. Your whole approach is misfounded because by taking logarithms you effectively are throwing out of the dataset any students with ze
How to interpret logarithmically transformed coefficients in linear regression? I think the more important point is suggested in @whuber's comment. Your whole approach is misfounded because by taking logarithms you effectively are throwing out of the dataset any students with zero missing days in either 2010 or 2011. It sounds like there are enough of these people to be a problem, and I am sure your results will be wrong based on the approach you are taking. Instead, you need to fit a generalized linear model with a poisson response. SPSS can't do this unless you have paid for the appropriate module, so I'd suggest upgrading to R. You will still have the problem of interpreting coefficients, but this is secondary to the importance of having a model that is basically appropriate.
How to interpret logarithmically transformed coefficients in linear regression? I think the more important point is suggested in @whuber's comment. Your whole approach is misfounded because by taking logarithms you effectively are throwing out of the dataset any students with ze
28,270
How to interpret logarithmically transformed coefficients in linear regression?
I agree with other respondents, especially with respect to the form of the model. If I understand the motivation of your question, however, you are addressing general audiences and want to convey the substantive (theoretical) meaning of your analysis. For this purpose I compare predicted values (e.g. estimated days missed) under various "scenarios." Based on the model you choose, you might compare the expected number or value of the dependent variable when the predictors are at some specific fixed values (their medians or zero, for instance) and then show how a "meaningful" change in of the predictors affects the predictions. Of course, you have to transform the data back into the original, understandable scale you start with. I say "meaningful change" because often the standard "one-unit change in X" doesn't convey the real import or lack thereof of an independent variable. With "attendance data," I'm not sure what such a change would be. (If a student missed no days in 2010, and one day in 2011, I'm not sure we would learn anything. But I don't know.)
How to interpret logarithmically transformed coefficients in linear regression?
I agree with other respondents, especially with respect to the form of the model. If I understand the motivation of your question, however, you are addressing general audiences and want to convey the
How to interpret logarithmically transformed coefficients in linear regression? I agree with other respondents, especially with respect to the form of the model. If I understand the motivation of your question, however, you are addressing general audiences and want to convey the substantive (theoretical) meaning of your analysis. For this purpose I compare predicted values (e.g. estimated days missed) under various "scenarios." Based on the model you choose, you might compare the expected number or value of the dependent variable when the predictors are at some specific fixed values (their medians or zero, for instance) and then show how a "meaningful" change in of the predictors affects the predictions. Of course, you have to transform the data back into the original, understandable scale you start with. I say "meaningful change" because often the standard "one-unit change in X" doesn't convey the real import or lack thereof of an independent variable. With "attendance data," I'm not sure what such a change would be. (If a student missed no days in 2010, and one day in 2011, I'm not sure we would learn anything. But I don't know.)
How to interpret logarithmically transformed coefficients in linear regression? I agree with other respondents, especially with respect to the form of the model. If I understand the motivation of your question, however, you are addressing general audiences and want to convey the
28,271
How to interpret logarithmically transformed coefficients in linear regression?
If we have the model $Y = bX$, then we might expect that a 1 unit increase of $X$ yields a b unit increase in Y. Instead, if we have $Y = b \log(X)$, then we expect a 1 percent increase in $X$ to yield $b\log(1.01)$ unit increase in Y. Edit: whoops, didn't realize that your dependent variable was also log transformed. Here's a link with a good example describing all three situations: 1) only Y is transformed 2) only the predictors are transformed 3) both Y and the predictors are transformed http://www.ats.ucla.edu/stat/mult_pkg/faq/general/log_transformed_regression.htm
How to interpret logarithmically transformed coefficients in linear regression?
If we have the model $Y = bX$, then we might expect that a 1 unit increase of $X$ yields a b unit increase in Y. Instead, if we have $Y = b \log(X)$, then we expect a 1 percent increase in $X$ to yie
How to interpret logarithmically transformed coefficients in linear regression? If we have the model $Y = bX$, then we might expect that a 1 unit increase of $X$ yields a b unit increase in Y. Instead, if we have $Y = b \log(X)$, then we expect a 1 percent increase in $X$ to yield $b\log(1.01)$ unit increase in Y. Edit: whoops, didn't realize that your dependent variable was also log transformed. Here's a link with a good example describing all three situations: 1) only Y is transformed 2) only the predictors are transformed 3) both Y and the predictors are transformed http://www.ats.ucla.edu/stat/mult_pkg/faq/general/log_transformed_regression.htm
How to interpret logarithmically transformed coefficients in linear regression? If we have the model $Y = bX$, then we might expect that a 1 unit increase of $X$ yields a b unit increase in Y. Instead, if we have $Y = b \log(X)$, then we expect a 1 percent increase in $X$ to yie
28,272
How to interpret logarithmically transformed coefficients in linear regression?
I often use the log-transform, but I tend to use binary covariates because it leads to a natural interpretation in terms of multipliers. Assume you want to predict $Y$ given, say 3 binary covariates $X_1$, $X_2$ and $X_3$ taking values in $\{0,1\}$. Now, instead of presenting: $log(Y) \approxeq log(C) + X_1W_1 + X_2W_2$, you can simply show: $Y \approxeq C \ M_1^{X_1}\ M_2^{X_2}\ M_3^{X_3}$, where: $M_1=e^{W_1}$, $M_2=e^{W_2}$ and $M_3=e^{W_3}$ are multipliers. That is to say, each time the covariate $X_i$ equals 1, the prediction is multiplied by $M_i$. For example, if $X_1=0$, $X_2=1$ and $X_3=1$, your prediction is: $Y \approxeq C \ M_2\ M_3$. I'm using $\approxeq$ because this is not exactly the prediction of the mean of $Y$: the mean parameter of a log-normal distribution is not in general the mean of the random variable (as it is the case for classical linear regression without the log-transform). I do not have precise reference here, but I think this is straightforward reasoning.
How to interpret logarithmically transformed coefficients in linear regression?
I often use the log-transform, but I tend to use binary covariates because it leads to a natural interpretation in terms of multipliers. Assume you want to predict $Y$ given, say 3 binary covariates $
How to interpret logarithmically transformed coefficients in linear regression? I often use the log-transform, but I tend to use binary covariates because it leads to a natural interpretation in terms of multipliers. Assume you want to predict $Y$ given, say 3 binary covariates $X_1$, $X_2$ and $X_3$ taking values in $\{0,1\}$. Now, instead of presenting: $log(Y) \approxeq log(C) + X_1W_1 + X_2W_2$, you can simply show: $Y \approxeq C \ M_1^{X_1}\ M_2^{X_2}\ M_3^{X_3}$, where: $M_1=e^{W_1}$, $M_2=e^{W_2}$ and $M_3=e^{W_3}$ are multipliers. That is to say, each time the covariate $X_i$ equals 1, the prediction is multiplied by $M_i$. For example, if $X_1=0$, $X_2=1$ and $X_3=1$, your prediction is: $Y \approxeq C \ M_2\ M_3$. I'm using $\approxeq$ because this is not exactly the prediction of the mean of $Y$: the mean parameter of a log-normal distribution is not in general the mean of the random variable (as it is the case for classical linear regression without the log-transform). I do not have precise reference here, but I think this is straightforward reasoning.
How to interpret logarithmically transformed coefficients in linear regression? I often use the log-transform, but I tend to use binary covariates because it leads to a natural interpretation in terms of multipliers. Assume you want to predict $Y$ given, say 3 binary covariates $
28,273
What is the difference between spatial dependence and spatial heterogeneity?
These terms probably do not have a universally accepted technical definition, but their meanings are reasonably clear: they refer to second order and first order variation of a spatial process, respectively. Let's take them by order after first introducing some standard concepts. A spatial process or spatial stochastic process can be thought of as a collection of random variables indexed by points in a space. (The variables have to satisfy some natural technical consistency conditions in order to qualify as a process: see the Kolmogorov Extension Theorem.) Note that a spatial process is a model. It is valid to use multiple different (conflicting) models to analyze and describe the same data. For instance, models of naturally occurring concentrations of metals in soils may be purely stochastic for small regions (such as a hectare or less) whereas over large regions (extending many kilometers) it's usually important to describe underlying regional trends deterministically--that is, as a form of spatial heterogeneity. Spatial heterogeneity is a property of a spatial process whose mean (or "intensity") varies from point to point. The mean is a first order property of a random variable (that is, related to its first moment), whence spatial heterogeneity can be considered a first order property of a process. Spatial dependence is a property of a spatial stochastic process in which the outcomes at different locations may be dependent. Often we can measure dependence in terms of the covariance (second moment) or correlation of the random variables: in this sense, dependence can be thought of as a second-order property. (Sticklers will be quick to point out that correlation and independence are not the same, so equating dependence with second order properties, although intuitively helpful, is not generally valid.) When you see patterns in spatial data, you can usually describe them either as heterogeneity or dependence (or both), depending on the purpose of the analysis, prior information, and the amount of data. Some simple, well-studied examples illustrate these ideas. A Poisson process with varying intensity is spatially heterogeneous but has no spatial dependence. In this figure, the square demarcates an area of higher spatial intensity. All point locations, however, are independent: the clustering and gaps in points are typical of independent randomly chosen locations. A neighborhood mean, or convolution, of a "white noise" process is spatially homogeneous but has spatial dependence. The spatial dependence in this Gaussian process is apparent through the patterns of ridges and valleys. They are homogeneous, though: there is no trend overall. Note, however, that if we were to focus on a small part of this area, we might elect to treat it as an inhomogeneous process (that is, with a trend) instead. This illustrates how scale can influence the model we choose. The previous process added to a deterministic function produces a process that is spatially dependent and heterogeneous. This image shows a different realization of the random component of this process than used for the previous illustration, so the patterns of small undulations will not be exactly the same as before--but they will have the same statistical properties.
What is the difference between spatial dependence and spatial heterogeneity?
These terms probably do not have a universally accepted technical definition, but their meanings are reasonably clear: they refer to second order and first order variation of a spatial process, respec
What is the difference between spatial dependence and spatial heterogeneity? These terms probably do not have a universally accepted technical definition, but their meanings are reasonably clear: they refer to second order and first order variation of a spatial process, respectively. Let's take them by order after first introducing some standard concepts. A spatial process or spatial stochastic process can be thought of as a collection of random variables indexed by points in a space. (The variables have to satisfy some natural technical consistency conditions in order to qualify as a process: see the Kolmogorov Extension Theorem.) Note that a spatial process is a model. It is valid to use multiple different (conflicting) models to analyze and describe the same data. For instance, models of naturally occurring concentrations of metals in soils may be purely stochastic for small regions (such as a hectare or less) whereas over large regions (extending many kilometers) it's usually important to describe underlying regional trends deterministically--that is, as a form of spatial heterogeneity. Spatial heterogeneity is a property of a spatial process whose mean (or "intensity") varies from point to point. The mean is a first order property of a random variable (that is, related to its first moment), whence spatial heterogeneity can be considered a first order property of a process. Spatial dependence is a property of a spatial stochastic process in which the outcomes at different locations may be dependent. Often we can measure dependence in terms of the covariance (second moment) or correlation of the random variables: in this sense, dependence can be thought of as a second-order property. (Sticklers will be quick to point out that correlation and independence are not the same, so equating dependence with second order properties, although intuitively helpful, is not generally valid.) When you see patterns in spatial data, you can usually describe them either as heterogeneity or dependence (or both), depending on the purpose of the analysis, prior information, and the amount of data. Some simple, well-studied examples illustrate these ideas. A Poisson process with varying intensity is spatially heterogeneous but has no spatial dependence. In this figure, the square demarcates an area of higher spatial intensity. All point locations, however, are independent: the clustering and gaps in points are typical of independent randomly chosen locations. A neighborhood mean, or convolution, of a "white noise" process is spatially homogeneous but has spatial dependence. The spatial dependence in this Gaussian process is apparent through the patterns of ridges and valleys. They are homogeneous, though: there is no trend overall. Note, however, that if we were to focus on a small part of this area, we might elect to treat it as an inhomogeneous process (that is, with a trend) instead. This illustrates how scale can influence the model we choose. The previous process added to a deterministic function produces a process that is spatially dependent and heterogeneous. This image shows a different realization of the random component of this process than used for the previous illustration, so the patterns of small undulations will not be exactly the same as before--but they will have the same statistical properties.
What is the difference between spatial dependence and spatial heterogeneity? These terms probably do not have a universally accepted technical definition, but their meanings are reasonably clear: they refer to second order and first order variation of a spatial process, respec
28,274
What is the difference between spatial dependence and spatial heterogeneity?
The notion of spatial heterogeneity in current spatial statistics is only used to characterize local variance of spatial dependence or regression. I suggested a broad perspective on spatial heterogeneity, which refers to the scaling pattern of far more small things than large ones. Importantly the scaling pattern recurs multiple times, measured by ht-index. https://www.researchgate.net/publication/236627484_Ht-Index_for_Quantifying_the_Fractal_or_Scaling_Structure_of_Geographic_Features Under the new definition, spatial heterogeneity should be formulated as a scaling law. Thus the heterogeneity is power law like rather than Gaussian distribution like. With this broad perspective, both spatial dependence and heterogeneity depict the true picture of the Earth's surface. There are far more small things than large ones across all scales or globally, but things are more or less similar at one scale or locally; see this paper for more details. https://www.researchgate.net/publication/282310447_A_Fractal_Perspective_on_Scale_in_Geography
What is the difference between spatial dependence and spatial heterogeneity?
The notion of spatial heterogeneity in current spatial statistics is only used to characterize local variance of spatial dependence or regression. I suggested a broad perspective on spatial heterogene
What is the difference between spatial dependence and spatial heterogeneity? The notion of spatial heterogeneity in current spatial statistics is only used to characterize local variance of spatial dependence or regression. I suggested a broad perspective on spatial heterogeneity, which refers to the scaling pattern of far more small things than large ones. Importantly the scaling pattern recurs multiple times, measured by ht-index. https://www.researchgate.net/publication/236627484_Ht-Index_for_Quantifying_the_Fractal_or_Scaling_Structure_of_Geographic_Features Under the new definition, spatial heterogeneity should be formulated as a scaling law. Thus the heterogeneity is power law like rather than Gaussian distribution like. With this broad perspective, both spatial dependence and heterogeneity depict the true picture of the Earth's surface. There are far more small things than large ones across all scales or globally, but things are more or less similar at one scale or locally; see this paper for more details. https://www.researchgate.net/publication/282310447_A_Fractal_Perspective_on_Scale_in_Geography
What is the difference between spatial dependence and spatial heterogeneity? The notion of spatial heterogeneity in current spatial statistics is only used to characterize local variance of spatial dependence or regression. I suggested a broad perspective on spatial heterogene
28,275
What is the difference between spatial dependence and spatial heterogeneity?
The question is dependent upon the mathematical definition of the two concepts. There are already several definitions of spatial autocorrelation like Moran's I, but few of spatial heterogeneity, probably because the latter is scale dependent and would be different in distinct scales. I defined the spatial stratified heterogeneity (the full paper is expected online on 12 March 2016 in journal Ecological Indicators): A measure of spatial stratified heterogeneity Jin-Feng Wang1*, Tong-Lin Zhang2, Bo-Jie Fu3 ABSTRACT Spatial stratified heterogeneity, referring to the within-strata variance less than the between strata-variance, is ubiquitous in ecological phenomena, such as ecological zones and many ecological variables. Spatial stratified heterogeneity reflects the essence of nature, implies potential distinct mechanisms by strata, suggests possible determinants of the observed process, allows the representativeness of observations of the earth, and enforces the applicability of statistical inferences. In this paper, we propose a q-statistic method to measure the degree of spatial stratified heterogeneity and to test its significance. The q value is within [0, 1] (0 if a spatial stratification of heterogeneity is not significant, and 1 if there is a perfect spatial stratification of heterogeneity). The exact probability density function is derived. The q-statistic is illustrated by two examples, wherein we assess the spatial stratified heterogeneities of a hand map and the distribution of the annual NDVI in China. --Jinfeng Wang 2016-3-8
What is the difference between spatial dependence and spatial heterogeneity?
The question is dependent upon the mathematical definition of the two concepts. There are already several definitions of spatial autocorrelation like Moran's I, but few of spatial heterogeneity, proba
What is the difference between spatial dependence and spatial heterogeneity? The question is dependent upon the mathematical definition of the two concepts. There are already several definitions of spatial autocorrelation like Moran's I, but few of spatial heterogeneity, probably because the latter is scale dependent and would be different in distinct scales. I defined the spatial stratified heterogeneity (the full paper is expected online on 12 March 2016 in journal Ecological Indicators): A measure of spatial stratified heterogeneity Jin-Feng Wang1*, Tong-Lin Zhang2, Bo-Jie Fu3 ABSTRACT Spatial stratified heterogeneity, referring to the within-strata variance less than the between strata-variance, is ubiquitous in ecological phenomena, such as ecological zones and many ecological variables. Spatial stratified heterogeneity reflects the essence of nature, implies potential distinct mechanisms by strata, suggests possible determinants of the observed process, allows the representativeness of observations of the earth, and enforces the applicability of statistical inferences. In this paper, we propose a q-statistic method to measure the degree of spatial stratified heterogeneity and to test its significance. The q value is within [0, 1] (0 if a spatial stratification of heterogeneity is not significant, and 1 if there is a perfect spatial stratification of heterogeneity). The exact probability density function is derived. The q-statistic is illustrated by two examples, wherein we assess the spatial stratified heterogeneities of a hand map and the distribution of the annual NDVI in China. --Jinfeng Wang 2016-3-8
What is the difference between spatial dependence and spatial heterogeneity? The question is dependent upon the mathematical definition of the two concepts. There are already several definitions of spatial autocorrelation like Moran's I, but few of spatial heterogeneity, proba
28,276
How can I account for spatial covariance in a linear model?
1) You can model spatial correlation with the nlme library; there are several possible models you might choose. See pages 260-266 of Pinheiro/Bates. A good first step is to make a variogram to see how the correlation depends on distance. library(nlme) m0 <- gls(response ~ level, data = layout) plot(Variogram(m0, form=~x+y)) Here the sample semivariogram increases with distance indicating that the observations are indeed spatially correlated. One option for the correlation structure is a spherical structure; that could be modeled in the following way. m1 <- update(m0, corr=corSpher(c(15, 0.25), form=~x+y, nugget=TRUE)) This model does seem to fit better than the model with no correlation structure, though it's entirely possible it too could be improved on with one of the other possible correlation structures. > anova(m0, m1) Model df AIC BIC logLik Test L.Ratio p-value m0 1 3 46.5297 49.80283 -20.26485 m1 2 5 43.3244 48.77961 -16.66220 1 vs 2 7.205301 0.0273 2) You could also try including x and y directly in the model; this could be appropriate if the pattern of correlation depends on more than just distance. In your case (looking at sesqu's pictures) it seems that for this block anyway, you may have a diagonal pattern. Here I'm updating the original model instead of m0 because I'm only changing the fixed effects, so the models should both be fit using maximum likelihood. > model2 <- update(model, .~.+x*y) > anova(model, model2) Analysis of Variance Table Model 1: response ~ level Model 2: response ~ level + x + y + x:y Res.Df RSS Df Sum of Sq F Pr(>F) 1 22 5.3809 2 19 2.7268 3 2.6541 6.1646 0.004168 ** To compare all three models, you'd need to fit them all with gls and the maximum likelihood method instead of the default method of REML. > m0b <- update(m0, method="ML") > m1b <- update(m1, method="ML") > m2b <- update(m0b, .~x*y) > anova(m0b, m1b, m2b, test=FALSE) Model df AIC BIC logLik m0b 1 3 38.22422 41.75838 -16.112112 m1b 2 5 35.88922 41.77949 -12.944610 m2b 3 5 29.09821 34.98847 -9.549103 Remember that especially with your knowledge of the study, you might be able to come up with a model that is better than any of these. That is, model m2b shouldn't necessarily be considered to be the best yet. Note: These calculations were performed after changing the x-value of plot 37 to 0.
How can I account for spatial covariance in a linear model?
1) You can model spatial correlation with the nlme library; there are several possible models you might choose. See pages 260-266 of Pinheiro/Bates. A good first step is to make a variogram to see ho
How can I account for spatial covariance in a linear model? 1) You can model spatial correlation with the nlme library; there are several possible models you might choose. See pages 260-266 of Pinheiro/Bates. A good first step is to make a variogram to see how the correlation depends on distance. library(nlme) m0 <- gls(response ~ level, data = layout) plot(Variogram(m0, form=~x+y)) Here the sample semivariogram increases with distance indicating that the observations are indeed spatially correlated. One option for the correlation structure is a spherical structure; that could be modeled in the following way. m1 <- update(m0, corr=corSpher(c(15, 0.25), form=~x+y, nugget=TRUE)) This model does seem to fit better than the model with no correlation structure, though it's entirely possible it too could be improved on with one of the other possible correlation structures. > anova(m0, m1) Model df AIC BIC logLik Test L.Ratio p-value m0 1 3 46.5297 49.80283 -20.26485 m1 2 5 43.3244 48.77961 -16.66220 1 vs 2 7.205301 0.0273 2) You could also try including x and y directly in the model; this could be appropriate if the pattern of correlation depends on more than just distance. In your case (looking at sesqu's pictures) it seems that for this block anyway, you may have a diagonal pattern. Here I'm updating the original model instead of m0 because I'm only changing the fixed effects, so the models should both be fit using maximum likelihood. > model2 <- update(model, .~.+x*y) > anova(model, model2) Analysis of Variance Table Model 1: response ~ level Model 2: response ~ level + x + y + x:y Res.Df RSS Df Sum of Sq F Pr(>F) 1 22 5.3809 2 19 2.7268 3 2.6541 6.1646 0.004168 ** To compare all three models, you'd need to fit them all with gls and the maximum likelihood method instead of the default method of REML. > m0b <- update(m0, method="ML") > m1b <- update(m1, method="ML") > m2b <- update(m0b, .~x*y) > anova(m0b, m1b, m2b, test=FALSE) Model df AIC BIC logLik m0b 1 3 38.22422 41.75838 -16.112112 m1b 2 5 35.88922 41.77949 -12.944610 m2b 3 5 29.09821 34.98847 -9.549103 Remember that especially with your knowledge of the study, you might be able to come up with a model that is better than any of these. That is, model m2b shouldn't necessarily be considered to be the best yet. Note: These calculations were performed after changing the x-value of plot 37 to 0.
How can I account for spatial covariance in a linear model? 1) You can model spatial correlation with the nlme library; there are several possible models you might choose. See pages 260-266 of Pinheiro/Bates. A good first step is to make a variogram to see ho
28,277
How can I account for spatial covariance in a linear model?
1) What is your spatial explaining variable? Looks like the x*y plane would be a poor model for the spatial effect. i=c(1,3,5,7,8,11,14,15,16,17,18,22,23,25,28,30,31,32,35,36,39,39,41,42) l=rep(NA,42)[i];l[i]=level r=rep(NA,42)[i];r[i]=response image(t(matrix(-l,6)));title("treatment") image(t(matrix(-r,6)));title("response") 2) Seeing as how the blocks are 1 mile apart and you expect to see effects for mere 30 meters, I would say it's entirely appropriate to analyze them separately.
How can I account for spatial covariance in a linear model?
1) What is your spatial explaining variable? Looks like the x*y plane would be a poor model for the spatial effect. i=c(1,3,5,7,8,11,14,15,16,17,18,22,23,25,28,30,31,32,35,36,39,39,41,42) l=rep(NA,4
How can I account for spatial covariance in a linear model? 1) What is your spatial explaining variable? Looks like the x*y plane would be a poor model for the spatial effect. i=c(1,3,5,7,8,11,14,15,16,17,18,22,23,25,28,30,31,32,35,36,39,39,41,42) l=rep(NA,42)[i];l[i]=level r=rep(NA,42)[i];r[i]=response image(t(matrix(-l,6)));title("treatment") image(t(matrix(-r,6)));title("response") 2) Seeing as how the blocks are 1 mile apart and you expect to see effects for mere 30 meters, I would say it's entirely appropriate to analyze them separately.
How can I account for spatial covariance in a linear model? 1) What is your spatial explaining variable? Looks like the x*y plane would be a poor model for the spatial effect. i=c(1,3,5,7,8,11,14,15,16,17,18,22,23,25,28,30,31,32,35,36,39,39,41,42) l=rep(NA,4
28,278
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be violated
Previous answers on this site: Related questions have been asked a few times on this site. Check out whether to treat likert scales as ordinal or interval choosing between pearson and spearman correlation Spearman or Pearson with non-normal data Scales versus items: From my experience, there is a difference between running analyses on a likert item as opposed to a likert scale. A likert scale is the sum of multiple items. After summing multiple items, likert scales obtain more possible values, the resulting scale is less lumpy. Such scales often have a sufficient number of points that many researchers are prepared to treat them as continuous. Of course, some would argue that this is a bit cavalier, and much has been written in psychometrics about how best to measure psychological and related constructs. Standard practice in social sciences: From my casual observations from reading journal articles in psychology, the majority of bivariate relationships between multiple-item likert scales are analysed using Pearson's correlation coefficient. Here, I'm thinking about scales like personality, intelligence, attitudes, well-being, and so forth. If you have scales like this, it is worth considering that your results will be compared to previous results where Pearson may have been the dominant choice. Compare methods: It is an interesting exercise to compare Pearson's with Spearman's (and perhaps even Kendall's tau). However, you are still left with the decision of which statistic to use, and this ultimately depends on what definition you have of bivariate association. Heteroscedasticity A correlation coefficient is an accurate summary of the linear relationship between two variables even in the absence of Homoscedasticity (or perhaps we should say bivariate normality given that neither variable is a dependent variable). Nonlinearity If there is a non-linear relationship between your two variables, this is interesting. However, both variables could still be treated as continuous variables, and thus, you could still use Pearson's. For example, age often has an inverted-U relationship with other variables such as income, yet age is still a continuous variable. I suggest that you produce a scatter plot and fit some smoothed fits (such as a spline or LOESS) to explore any non-linear relationships. If the relationship is truly non-linear then linear correlation is not the best choice for describing such a relationship. You might then want to explore polynomial or nonlinear regression.
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be v
Previous answers on this site: Related questions have been asked a few times on this site. Check out whether to treat likert scales as ordinal or interval choosing between pearson and spearman correl
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be violated Previous answers on this site: Related questions have been asked a few times on this site. Check out whether to treat likert scales as ordinal or interval choosing between pearson and spearman correlation Spearman or Pearson with non-normal data Scales versus items: From my experience, there is a difference between running analyses on a likert item as opposed to a likert scale. A likert scale is the sum of multiple items. After summing multiple items, likert scales obtain more possible values, the resulting scale is less lumpy. Such scales often have a sufficient number of points that many researchers are prepared to treat them as continuous. Of course, some would argue that this is a bit cavalier, and much has been written in psychometrics about how best to measure psychological and related constructs. Standard practice in social sciences: From my casual observations from reading journal articles in psychology, the majority of bivariate relationships between multiple-item likert scales are analysed using Pearson's correlation coefficient. Here, I'm thinking about scales like personality, intelligence, attitudes, well-being, and so forth. If you have scales like this, it is worth considering that your results will be compared to previous results where Pearson may have been the dominant choice. Compare methods: It is an interesting exercise to compare Pearson's with Spearman's (and perhaps even Kendall's tau). However, you are still left with the decision of which statistic to use, and this ultimately depends on what definition you have of bivariate association. Heteroscedasticity A correlation coefficient is an accurate summary of the linear relationship between two variables even in the absence of Homoscedasticity (or perhaps we should say bivariate normality given that neither variable is a dependent variable). Nonlinearity If there is a non-linear relationship between your two variables, this is interesting. However, both variables could still be treated as continuous variables, and thus, you could still use Pearson's. For example, age often has an inverted-U relationship with other variables such as income, yet age is still a continuous variable. I suggest that you produce a scatter plot and fit some smoothed fits (such as a spline or LOESS) to explore any non-linear relationships. If the relationship is truly non-linear then linear correlation is not the best choice for describing such a relationship. You might then want to explore polynomial or nonlinear regression.
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be v Previous answers on this site: Related questions have been asked a few times on this site. Check out whether to treat likert scales as ordinal or interval choosing between pearson and spearman correl
28,279
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be violated
You should almost certainly go for Spearman's rho or Kendall's tau. Often, if the data is non-normal but variances are equal, you can go for Pearson's r as it doesnt make a huge amount of difference. If the variances are significantly different, then you need a non parametric method. You could probably cite almost any introductory statistics textbook to support your use of Spearman's Rho. Update: if the assumption of linearity is violated, then you should not be using the Pearson correlation coefficient on your data, as it assumes a linear relationship. Spearman's Rho is acceptable without linearity and is meant for more general monotonic relationships between the variables. If you want to use Pearson's correlation coefficient, you could look at log transforming your data as this might deal with the non-linearity.
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be v
You should almost certainly go for Spearman's rho or Kendall's tau. Often, if the data is non-normal but variances are equal, you can go for Pearson's r as it doesnt make a huge amount of difference.
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be violated You should almost certainly go for Spearman's rho or Kendall's tau. Often, if the data is non-normal but variances are equal, you can go for Pearson's r as it doesnt make a huge amount of difference. If the variances are significantly different, then you need a non parametric method. You could probably cite almost any introductory statistics textbook to support your use of Spearman's Rho. Update: if the assumption of linearity is violated, then you should not be using the Pearson correlation coefficient on your data, as it assumes a linear relationship. Spearman's Rho is acceptable without linearity and is meant for more general monotonic relationships between the variables. If you want to use Pearson's correlation coefficient, you could look at log transforming your data as this might deal with the non-linearity.
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be v You should almost certainly go for Spearman's rho or Kendall's tau. Often, if the data is non-normal but variances are equal, you can go for Pearson's r as it doesnt make a huge amount of difference.
28,280
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be violated
one thing is pretty sure that correlation requires linearity in relationship in general. now you say your data somewhat curve shaped,so nonlinear regression seems to be the left choice
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be v
one thing is pretty sure that correlation requires linearity in relationship in general. now you say your data somewhat curve shaped,so nonlinear regression seems to be the left choice
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be violated one thing is pretty sure that correlation requires linearity in relationship in general. now you say your data somewhat curve shaped,so nonlinear regression seems to be the left choice
Spearman's or Pearson's correlation with Likert scales where linearity and homoscedasticity may be v one thing is pretty sure that correlation requires linearity in relationship in general. now you say your data somewhat curve shaped,so nonlinear regression seems to be the left choice
28,281
From an email address to a quasi-random number [closed]
Look up hash functions, for example at http://en.wikipedia.org/wiki/Hash_function
From an email address to a quasi-random number [closed]
Look up hash functions, for example at http://en.wikipedia.org/wiki/Hash_function
From an email address to a quasi-random number [closed] Look up hash functions, for example at http://en.wikipedia.org/wiki/Hash_function
From an email address to a quasi-random number [closed] Look up hash functions, for example at http://en.wikipedia.org/wiki/Hash_function
28,282
From an email address to a quasi-random number [closed]
Why not just have a look-up table of numbers for each possible character in an email. Then concatenate the numbers to form a seed. For example, A 1 B 2 C 3 .... @ 27 .... So abc@ccc, would be converted to 12327333. This would give you a unique seed for each person. You would then use this to generate the 1, 2, 3, 4. From your question, it looks like you don't mind a "quick and dirty solution". One problem with my solution is that email addresses aren't random - for example you will probably get very few email addresses that contain the letter "z", but all email addresses contain "@".
From an email address to a quasi-random number [closed]
Why not just have a look-up table of numbers for each possible character in an email. Then concatenate the numbers to form a seed. For example, A 1 B 2 C 3 .... @ 27 .... So abc@ccc, would be conver
From an email address to a quasi-random number [closed] Why not just have a look-up table of numbers for each possible character in an email. Then concatenate the numbers to form a seed. For example, A 1 B 2 C 3 .... @ 27 .... So abc@ccc, would be converted to 12327333. This would give you a unique seed for each person. You would then use this to generate the 1, 2, 3, 4. From your question, it looks like you don't mind a "quick and dirty solution". One problem with my solution is that email addresses aren't random - for example you will probably get very few email addresses that contain the letter "z", but all email addresses contain "@".
From an email address to a quasi-random number [closed] Why not just have a look-up table of numbers for each possible character in an email. Then concatenate the numbers to form a seed. For example, A 1 B 2 C 3 .... @ 27 .... So abc@ccc, would be conver
28,283
From an email address to a quasi-random number [closed]
As an addition to other excellent answers, I just will give a simple example in R language to show a very simple hash function, which should be good enough for this purpose. To get some email addresses as test data, I get a character vector with the emails of the maintainers of the (too many!) R packages installed on my computer: library(stringr) # on CRAN last <- function(x) { return( x[length(x)] ) } INST <- installed.packages(priority="NA", fields=c("Maintainer")) Maintainer <- INST[, "Maintainer"] Mlist <- str_split(Maintainer, "[[:blank:]]") Maddr <- sapply(Mlist, FUN=last) Maddr <- str_replace(Maddr, "[<>]", "") Maddr <- unique(Maddr) Then I define a simple function which gets some number from each character in the email address, adds them, computes the remainder modulo 4 and adds 1, so it returns always one of the results 1,2,3 or 4: apply_to_each_char <- function(w, FUN) { ww <- str_split(w, "")[[1]] res <- sapply(ww, FUN) } # END apply_to_each_char charsum <- function(word) { # length-one char vector sum0 <- sum( apply_to_each_char(word, function(w) as.integer(charToRaw(w)) )) return( 1 + sum0 %% 4) } # end charsum Then applying it: hashes <- sapply(Maddr, charsum) table(hashes) hashes 1 2 3 4 542 511 562 552 and we can observe that the resulting distribution is close to uniform.
From an email address to a quasi-random number [closed]
As an addition to other excellent answers, I just will give a simple example in R language to show a very simple hash function, which should be good enough for this purpose. To get some email addresse
From an email address to a quasi-random number [closed] As an addition to other excellent answers, I just will give a simple example in R language to show a very simple hash function, which should be good enough for this purpose. To get some email addresses as test data, I get a character vector with the emails of the maintainers of the (too many!) R packages installed on my computer: library(stringr) # on CRAN last <- function(x) { return( x[length(x)] ) } INST <- installed.packages(priority="NA", fields=c("Maintainer")) Maintainer <- INST[, "Maintainer"] Mlist <- str_split(Maintainer, "[[:blank:]]") Maddr <- sapply(Mlist, FUN=last) Maddr <- str_replace(Maddr, "[<>]", "") Maddr <- unique(Maddr) Then I define a simple function which gets some number from each character in the email address, adds them, computes the remainder modulo 4 and adds 1, so it returns always one of the results 1,2,3 or 4: apply_to_each_char <- function(w, FUN) { ww <- str_split(w, "")[[1]] res <- sapply(ww, FUN) } # END apply_to_each_char charsum <- function(word) { # length-one char vector sum0 <- sum( apply_to_each_char(word, function(w) as.integer(charToRaw(w)) )) return( 1 + sum0 %% 4) } # end charsum Then applying it: hashes <- sapply(Maddr, charsum) table(hashes) hashes 1 2 3 4 542 511 562 552 and we can observe that the resulting distribution is close to uniform.
From an email address to a quasi-random number [closed] As an addition to other excellent answers, I just will give a simple example in R language to show a very simple hash function, which should be good enough for this purpose. To get some email addresse
28,284
From an email address to a quasi-random number [closed]
You could try converting each character to an ascii number, multiplying them all together to force overflow, and then performing a modulus operation on the least significant digits. If this is not pseudo-random enough, you can perform a bit-shift the numbers a bit... -Ralph Winters
From an email address to a quasi-random number [closed]
You could try converting each character to an ascii number, multiplying them all together to force overflow, and then performing a modulus operation on the least significant digits. If this is not ps
From an email address to a quasi-random number [closed] You could try converting each character to an ascii number, multiplying them all together to force overflow, and then performing a modulus operation on the least significant digits. If this is not pseudo-random enough, you can perform a bit-shift the numbers a bit... -Ralph Winters
From an email address to a quasi-random number [closed] You could try converting each character to an ascii number, multiplying them all together to force overflow, and then performing a modulus operation on the least significant digits. If this is not ps
28,285
Formal statistical test for whether a process is a white noise
In time-series analysis usually Ljung-Box test is used. Note though that it tests the correlations. If the correlations are zero, but variance varies, then the process is not white noise, but Ljung-Box test will fail to reject the null-hypothesis. Here is an example in R: > Box.test(c(rnorm(100,0,1),rnorm(100,0,10)),type="Ljung-Box") Box-Ljung test data: c(rnorm(100, 0, 1), rnorm(100, 0, 10)) X-squared = 0.4771, df = 1, p-value = 0.4898 Here is the plot of the process: Here is more discussion about this test.
Formal statistical test for whether a process is a white noise
In time-series analysis usually Ljung-Box test is used. Note though that it tests the correlations. If the correlations are zero, but variance varies, then the process is not white noise, but Ljung-Bo
Formal statistical test for whether a process is a white noise In time-series analysis usually Ljung-Box test is used. Note though that it tests the correlations. If the correlations are zero, but variance varies, then the process is not white noise, but Ljung-Box test will fail to reject the null-hypothesis. Here is an example in R: > Box.test(c(rnorm(100,0,1),rnorm(100,0,10)),type="Ljung-Box") Box-Ljung test data: c(rnorm(100, 0, 1), rnorm(100, 0, 10)) X-squared = 0.4771, df = 1, p-value = 0.4898 Here is the plot of the process: Here is more discussion about this test.
Formal statistical test for whether a process is a white noise In time-series analysis usually Ljung-Box test is used. Note though that it tests the correlations. If the correlations are zero, but variance varies, then the process is not white noise, but Ljung-Bo
28,286
Formal statistical test for whether a process is a white noise
The R library hwwntest (Haar Wavelet White Noise test) seems to work pretty well. It offers a number of functions. It does require the amount of data to be a power of 2. hywavwn.test() seems to work the best for me. > hywavwn.test(rnorm(128, 0, 1)) Hybrid Wavelet Test of White Noise data: p-value = 0.542 > hywavwn.test(rnorm(128, 0, 10)) Hybrid Wavelet Test of White Noise data: p-value = 1
Formal statistical test for whether a process is a white noise
The R library hwwntest (Haar Wavelet White Noise test) seems to work pretty well. It offers a number of functions. It does require the amount of data to be a power of 2. hywavwn.test() seems to work
Formal statistical test for whether a process is a white noise The R library hwwntest (Haar Wavelet White Noise test) seems to work pretty well. It offers a number of functions. It does require the amount of data to be a power of 2. hywavwn.test() seems to work the best for me. > hywavwn.test(rnorm(128, 0, 1)) Hybrid Wavelet Test of White Noise data: p-value = 0.542 > hywavwn.test(rnorm(128, 0, 10)) Hybrid Wavelet Test of White Noise data: p-value = 1
Formal statistical test for whether a process is a white noise The R library hwwntest (Haar Wavelet White Noise test) seems to work pretty well. It offers a number of functions. It does require the amount of data to be a power of 2. hywavwn.test() seems to work
28,287
Translate R to C++ (eventually with Rcpp) [closed]
Interesting question, but quite possibly too challenging to be discussed briefly: You would need a C++-side implementations of median() The cited code from package robustbase is highly 'R-optimised' which may not be the best starting point. Rcpp is not an 'R compiler' that you toss any such function at to 'make it faster'. It is more about connecting existing C++ code, or writing new C++ code. Of course the above can be translated (Turing-equivalence and all that) but that may not be the best way to learn about using Rcpp. I think we have simpler examples on the mailing list. Lastly, isn't this a programming question for SO? ;-)
Translate R to C++ (eventually with Rcpp) [closed]
Interesting question, but quite possibly too challenging to be discussed briefly: You would need a C++-side implementations of median() The cited code from package robustbase is highly 'R-optimised'
Translate R to C++ (eventually with Rcpp) [closed] Interesting question, but quite possibly too challenging to be discussed briefly: You would need a C++-side implementations of median() The cited code from package robustbase is highly 'R-optimised' which may not be the best starting point. Rcpp is not an 'R compiler' that you toss any such function at to 'make it faster'. It is more about connecting existing C++ code, or writing new C++ code. Of course the above can be translated (Turing-equivalence and all that) but that may not be the best way to learn about using Rcpp. I think we have simpler examples on the mailing list. Lastly, isn't this a programming question for SO? ;-)
Translate R to C++ (eventually with Rcpp) [closed] Interesting question, but quite possibly too challenging to be discussed briefly: You would need a C++-side implementations of median() The cited code from package robustbase is highly 'R-optimised'
28,288
Output of logistic model in R
The help pages for predict.glm state: "Thus for a default binomial model the default predictions are of log-odds (probabilities on logit scale) and ‘type = "response"’ gives the predicted probabilities". So, predict(mdl) returns the log(odds), and using "type = "response" returns the predicted probabilities. You might find this toy example instructive: > y <- c(0,0,0,1,1,1,1,1,1,1) > prop.table(table(y)) y 0 1 0.3 0.7 > glm.y <- glm(y~1, family = "binomial") > ## predicted log(odds) > predict(glm.y) 1 2 3 4 5 6 7 8 0.8472979 0.8472979 0.8472979 0.8472979 0.8472979 0.8472979 0.8472979 0.8472979 9 10 0.8472979 0.8472979 > ## predicted probabilities (p = odds/(1+odds)) > exp(predict(glm.y))/(1+exp(predict(glm.y))) 1 2 3 4 5 6 7 8 9 10 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 > predict(glm.y, type = "response") 1 2 3 4 5 6 7 8 9 10 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 Regarding your second question, you might want to check out the effects-package http://socserv.socsci.mcmaster.ca/jfox/Misc/effects/index.html by John Fox; see also his JSS article "Effect Displays in R for Generalised Linear Models" (pp. 8-10).
Output of logistic model in R
The help pages for predict.glm state: "Thus for a default binomial model the default predictions are of log-odds (probabilities on logit scale) and ‘type = "response"’ gives the predicted pro
Output of logistic model in R The help pages for predict.glm state: "Thus for a default binomial model the default predictions are of log-odds (probabilities on logit scale) and ‘type = "response"’ gives the predicted probabilities". So, predict(mdl) returns the log(odds), and using "type = "response" returns the predicted probabilities. You might find this toy example instructive: > y <- c(0,0,0,1,1,1,1,1,1,1) > prop.table(table(y)) y 0 1 0.3 0.7 > glm.y <- glm(y~1, family = "binomial") > ## predicted log(odds) > predict(glm.y) 1 2 3 4 5 6 7 8 0.8472979 0.8472979 0.8472979 0.8472979 0.8472979 0.8472979 0.8472979 0.8472979 9 10 0.8472979 0.8472979 > ## predicted probabilities (p = odds/(1+odds)) > exp(predict(glm.y))/(1+exp(predict(glm.y))) 1 2 3 4 5 6 7 8 9 10 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 > predict(glm.y, type = "response") 1 2 3 4 5 6 7 8 9 10 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 Regarding your second question, you might want to check out the effects-package http://socserv.socsci.mcmaster.ca/jfox/Misc/effects/index.html by John Fox; see also his JSS article "Effect Displays in R for Generalised Linear Models" (pp. 8-10).
Output of logistic model in R The help pages for predict.glm state: "Thus for a default binomial model the default predictions are of log-odds (probabilities on logit scale) and ‘type = "response"’ gives the predicted pro
28,289
How to show that $\{N(\theta,1):\theta \in \Omega\}$ is not a complete family of distributions when $\Omega$ is finite?
For notational convenience, let $\varphi_{\theta}(x)$ denote the density of a $N(\theta, 1)$ random variable. One way of viewing this problem is that the condition \begin{align*} \int_{-\infty}^\infty g(x)\varphi_\theta(x)dx = 0, \quad \theta \in \{-1, 0, 1\} \tag{1} \end{align*} sets up a system of three equations. If we pick up $g(x) = ax^3 + bx^2 + cx + d$ from the family of cubic polynomials, then $(1)$ becomes a homogeneous system of three linear equations with four unknowns $a, b, c, d$. By linear algebra theory, the dimensionality of the solution space to such a linear system is at least $1$ (because the rank of the associated coefficient matrix is at most $3$), implying that there are countless non-zero $g(x)$ satisfying $(1)$. Indeed, substituting $g(x) = ax^3 + bx^2 + cx + d$ and central moments of $\varphi_\theta(x)$ into $(1)$ yields \begin{align*} b + d &= 0, \\ 4a + 2b + c + d &= 0, \tag{2} \\ -4a + 2b - c + d &= 0. \end{align*} One (of infinitely many) non-zero solution to $(2)$ is $a = -1, b = 0, c = 4, d = 0$, resulting $g(x) = -x^3 + 4x \neq 0$. This shows that the family $\{N(\theta, 1): \theta \in \Omega\}$ is not complete. While the above construction works well for any parameter space with finite cardinality, it does not generalize to the case where the parameter space contains infinite members (e.g., the original linked exercise whose $\Omega = \{1, 2, 3, \ldots\}$). To deal with the latter case, note that, by the translation property of $\varphi_\theta$, the condition $E_\theta[g(X)] = 0$ for all $\theta \in \Omega$ is equivalent to \begin{align} E[g(X + \theta)] = 0 \; \text{for all } \theta \in \Omega, \tag{2} \end{align} where "$E$" is with respect to the standard normal density $\varphi(x)$. This observation implies that, when $\Omega = \{1, 2, \ldots\}$, $(2)$ automatically holds for $g$ such that $g(x + \theta) = g(x)$ for all $\theta = 1, 2, \ldots$ and $E[g(X)] = 0$. Clearly, one candidate of such $g$ is any periodic odd function with periodicity $1$. For example, $g(x) = \sin(\pi x)$ proposed in @jld's answer. As another (non-trigonometric) example, $g(x)$ can be taken to be \begin{align} g(x) = \frac{1}{2} - \left|x - \frac{1}{2}\right|, \; 0 \leq x \leq 1. \end{align} And then copy this to intervals $[n, n + 1]$, $n = 1, 2, \ldots$ to complete $g$'s definition on $[0, +\infty)$. Finally, define $g(x) = -g(-x)$ when $x < 0$.
How to show that $\{N(\theta,1):\theta \in \Omega\}$ is not a complete family of distributions when
For notational convenience, let $\varphi_{\theta}(x)$ denote the density of a $N(\theta, 1)$ random variable. One way of viewing this problem is that the condition \begin{align*} \int_{-\infty}^\infty
How to show that $\{N(\theta,1):\theta \in \Omega\}$ is not a complete family of distributions when $\Omega$ is finite? For notational convenience, let $\varphi_{\theta}(x)$ denote the density of a $N(\theta, 1)$ random variable. One way of viewing this problem is that the condition \begin{align*} \int_{-\infty}^\infty g(x)\varphi_\theta(x)dx = 0, \quad \theta \in \{-1, 0, 1\} \tag{1} \end{align*} sets up a system of three equations. If we pick up $g(x) = ax^3 + bx^2 + cx + d$ from the family of cubic polynomials, then $(1)$ becomes a homogeneous system of three linear equations with four unknowns $a, b, c, d$. By linear algebra theory, the dimensionality of the solution space to such a linear system is at least $1$ (because the rank of the associated coefficient matrix is at most $3$), implying that there are countless non-zero $g(x)$ satisfying $(1)$. Indeed, substituting $g(x) = ax^3 + bx^2 + cx + d$ and central moments of $\varphi_\theta(x)$ into $(1)$ yields \begin{align*} b + d &= 0, \\ 4a + 2b + c + d &= 0, \tag{2} \\ -4a + 2b - c + d &= 0. \end{align*} One (of infinitely many) non-zero solution to $(2)$ is $a = -1, b = 0, c = 4, d = 0$, resulting $g(x) = -x^3 + 4x \neq 0$. This shows that the family $\{N(\theta, 1): \theta \in \Omega\}$ is not complete. While the above construction works well for any parameter space with finite cardinality, it does not generalize to the case where the parameter space contains infinite members (e.g., the original linked exercise whose $\Omega = \{1, 2, 3, \ldots\}$). To deal with the latter case, note that, by the translation property of $\varphi_\theta$, the condition $E_\theta[g(X)] = 0$ for all $\theta \in \Omega$ is equivalent to \begin{align} E[g(X + \theta)] = 0 \; \text{for all } \theta \in \Omega, \tag{2} \end{align} where "$E$" is with respect to the standard normal density $\varphi(x)$. This observation implies that, when $\Omega = \{1, 2, \ldots\}$, $(2)$ automatically holds for $g$ such that $g(x + \theta) = g(x)$ for all $\theta = 1, 2, \ldots$ and $E[g(X)] = 0$. Clearly, one candidate of such $g$ is any periodic odd function with periodicity $1$. For example, $g(x) = \sin(\pi x)$ proposed in @jld's answer. As another (non-trigonometric) example, $g(x)$ can be taken to be \begin{align} g(x) = \frac{1}{2} - \left|x - \frac{1}{2}\right|, \; 0 \leq x \leq 1. \end{align} And then copy this to intervals $[n, n + 1]$, $n = 1, 2, \ldots$ to complete $g$'s definition on $[0, +\infty)$. Finally, define $g(x) = -g(-x)$ when $x < 0$.
How to show that $\{N(\theta,1):\theta \in \Omega\}$ is not a complete family of distributions when For notational convenience, let $\varphi_{\theta}(x)$ denote the density of a $N(\theta, 1)$ random variable. One way of viewing this problem is that the condition \begin{align*} \int_{-\infty}^\infty
28,290
How to show that $\{N(\theta,1):\theta \in \Omega\}$ is not a complete family of distributions when $\Omega$ is finite?
We can use a function $f$ that is odd about each point in $\Omega$ since then $\int_{\mathbb R} f(x) e^{-(x-\theta)^2}\,\text dx = 0$ for each $\theta$. This suggests a periodic function and so we can get an example by picking a sine wave with frequency high enough to be odd about each $\theta$, so e.g. in your case $\sin (\pi x)$ does the trick.
How to show that $\{N(\theta,1):\theta \in \Omega\}$ is not a complete family of distributions when
We can use a function $f$ that is odd about each point in $\Omega$ since then $\int_{\mathbb R} f(x) e^{-(x-\theta)^2}\,\text dx = 0$ for each $\theta$. This suggests a periodic function and so we can
How to show that $\{N(\theta,1):\theta \in \Omega\}$ is not a complete family of distributions when $\Omega$ is finite? We can use a function $f$ that is odd about each point in $\Omega$ since then $\int_{\mathbb R} f(x) e^{-(x-\theta)^2}\,\text dx = 0$ for each $\theta$. This suggests a periodic function and so we can get an example by picking a sine wave with frequency high enough to be odd about each $\theta$, so e.g. in your case $\sin (\pi x)$ does the trick.
How to show that $\{N(\theta,1):\theta \in \Omega\}$ is not a complete family of distributions when We can use a function $f$ that is odd about each point in $\Omega$ since then $\int_{\mathbb R} f(x) e^{-(x-\theta)^2}\,\text dx = 0$ for each $\theta$. This suggests a periodic function and so we can
28,291
Multivariable vs multivariate regression [duplicate]
Multivariable regression is any regression model where there is more than one explanatory variable. For this reason it is often simply known as "multiple regression". In the simple case of just one explanatory variable, this is sometimes called univariable regression. Unfortunately multivariable regression is often mistakenly called multivariate regression, or vice versa. Multivariate regression is any regression model in which there is more than one outcome variable. In the more usual case where there is just one outcome variable, this is also known as univariate regression. Thus we can have: univariate multivariable regression. A model with one outcome and several explanatory variables. This is probably the most common regression model and will be familiar to most analysts, and is often just called multiple regression; sometimes (where the link function is the identity function) it is called the General Linear Model (not Generalized). univariate univariable regression. One outcome, one explanatory variable, often used as the introductory example in a first course on regression models. multivariate multivariable regression. Multiple outcomes, multiple explanatory variable. This is the scenario described in the question. multivariate univariable regression. Multiple outcomes, single explanatory variable. An example of this is Hotelling's T-Squared test, a multivariate counterpart of the T-test (thanks to @Dave for pointing this out). The above is standard terminology in applied fields I have worked in: biostatistics, social sciences and psychology. I would not be surprises if other domains use the terms differemtly.
Multivariable vs multivariate regression [duplicate]
Multivariable regression is any regression model where there is more than one explanatory variable. For this reason it is often simply known as "multiple regression". In the simple case of just one ex
Multivariable vs multivariate regression [duplicate] Multivariable regression is any regression model where there is more than one explanatory variable. For this reason it is often simply known as "multiple regression". In the simple case of just one explanatory variable, this is sometimes called univariable regression. Unfortunately multivariable regression is often mistakenly called multivariate regression, or vice versa. Multivariate regression is any regression model in which there is more than one outcome variable. In the more usual case where there is just one outcome variable, this is also known as univariate regression. Thus we can have: univariate multivariable regression. A model with one outcome and several explanatory variables. This is probably the most common regression model and will be familiar to most analysts, and is often just called multiple regression; sometimes (where the link function is the identity function) it is called the General Linear Model (not Generalized). univariate univariable regression. One outcome, one explanatory variable, often used as the introductory example in a first course on regression models. multivariate multivariable regression. Multiple outcomes, multiple explanatory variable. This is the scenario described in the question. multivariate univariable regression. Multiple outcomes, single explanatory variable. An example of this is Hotelling's T-Squared test, a multivariate counterpart of the T-test (thanks to @Dave for pointing this out). The above is standard terminology in applied fields I have worked in: biostatistics, social sciences and psychology. I would not be surprises if other domains use the terms differemtly.
Multivariable vs multivariate regression [duplicate] Multivariable regression is any regression model where there is more than one explanatory variable. For this reason it is often simply known as "multiple regression". In the simple case of just one ex
28,292
Multivariable vs multivariate regression [duplicate]
Multivariate regression should refer to a situation like you’ve described where the response has multiple related dimensions such as lung capacity and heart rate. Determining how each predictor affects each dimension of the response falls to model building, but it doesn’t change the fact that the regression is multivariate. I don’t know “multivariable regression” as a term, but I could see it referring to a multivariate regression of just a regular regression with multiple predictors of one response variable. As the latter is (much) more common, I would expect that if I saw “multivariable regression” in a job description. (Ditto if I read about “multivariate regression” in a job description, even if that’s not the typical use of the term.) Yes, there’s plenty of abuse of terminology out there. The one that sends me through the roof is “multilinear regression”. “Multilinear” has a specific meaning in mathematics, and the “multiple linear regression” that someone means when she calls it “multilinear” is linear, not multilinear.
Multivariable vs multivariate regression [duplicate]
Multivariate regression should refer to a situation like you’ve described where the response has multiple related dimensions such as lung capacity and heart rate. Determining how each predictor affect
Multivariable vs multivariate regression [duplicate] Multivariate regression should refer to a situation like you’ve described where the response has multiple related dimensions such as lung capacity and heart rate. Determining how each predictor affects each dimension of the response falls to model building, but it doesn’t change the fact that the regression is multivariate. I don’t know “multivariable regression” as a term, but I could see it referring to a multivariate regression of just a regular regression with multiple predictors of one response variable. As the latter is (much) more common, I would expect that if I saw “multivariable regression” in a job description. (Ditto if I read about “multivariate regression” in a job description, even if that’s not the typical use of the term.) Yes, there’s plenty of abuse of terminology out there. The one that sends me through the roof is “multilinear regression”. “Multilinear” has a specific meaning in mathematics, and the “multiple linear regression” that someone means when she calls it “multilinear” is linear, not multilinear.
Multivariable vs multivariate regression [duplicate] Multivariate regression should refer to a situation like you’ve described where the response has multiple related dimensions such as lung capacity and heart rate. Determining how each predictor affect
28,293
Is there a canonical example of when ridge outperforms lasso?
Both models penalise the inclusion of a non-zero coefficient, using a penalty function. LASSO regression penalises in a way that is proportionate to the absolute magnitude of the coefficient, and ridge regression penalises in a way that is proportionate to the square of the coefficient. Neither model penalises inputs in the likelihood function where the coefficient is set to zero. For inputs into the likelihood function where a coefficient is non-zero, LASSO regression penalises values near zero more heavily, whereas ridge regression penalises values far from zero more heavily. (In your question, you seem to be making the error of thinking that the squared value is always more than the absolute value. That is not true. For input values with magnitude less than one, the absolute value is larger than the square.) Intuition tells us that ridge regression will tend to outperform LASSO regression in cases where the true non-zero coefficients are close to zero, relative to the noise in the regression. In this case, ridge regression penalises these values less, so it is more likely to estimate non-zero values for these coefficients. LASSO regression penalises these coefficients more, so it is more likely to incorrectly estimate them to be zero. On the basis of this intuition, I would recommend that you compare these models for some data generated from a regression with coefficients that are small relative to the noise in the regression. If you were to conduct a simulation study with cases like this, you should find that ridge regression tends to outperform LASSO in these cases.
Is there a canonical example of when ridge outperforms lasso?
Both models penalise the inclusion of a non-zero coefficient, using a penalty function. LASSO regression penalises in a way that is proportionate to the absolute magnitude of the coefficient, and rid
Is there a canonical example of when ridge outperforms lasso? Both models penalise the inclusion of a non-zero coefficient, using a penalty function. LASSO regression penalises in a way that is proportionate to the absolute magnitude of the coefficient, and ridge regression penalises in a way that is proportionate to the square of the coefficient. Neither model penalises inputs in the likelihood function where the coefficient is set to zero. For inputs into the likelihood function where a coefficient is non-zero, LASSO regression penalises values near zero more heavily, whereas ridge regression penalises values far from zero more heavily. (In your question, you seem to be making the error of thinking that the squared value is always more than the absolute value. That is not true. For input values with magnitude less than one, the absolute value is larger than the square.) Intuition tells us that ridge regression will tend to outperform LASSO regression in cases where the true non-zero coefficients are close to zero, relative to the noise in the regression. In this case, ridge regression penalises these values less, so it is more likely to estimate non-zero values for these coefficients. LASSO regression penalises these coefficients more, so it is more likely to incorrectly estimate them to be zero. On the basis of this intuition, I would recommend that you compare these models for some data generated from a regression with coefficients that are small relative to the noise in the regression. If you were to conduct a simulation study with cases like this, you should find that ridge regression tends to outperform LASSO in these cases.
Is there a canonical example of when ridge outperforms lasso? Both models penalise the inclusion of a non-zero coefficient, using a penalty function. LASSO regression penalises in a way that is proportionate to the absolute magnitude of the coefficient, and rid
28,294
Is there a canonical example of when ridge outperforms lasso?
Ridge was originally designed for correlated variables, and that's where it's best. Consider examinations to determine a degree. ( Which supposedly is measuring ability) Which do you think is more reliable: taking the average of all the exams or picking a single exam most correlated with ability (if there is one)? Averaging over the different exams removes (independent noise - you didn't sleep well one day etc) Ridge will take the average of these correlated inputs (IE the separate exams), whilst lasso will just select one.
Is there a canonical example of when ridge outperforms lasso?
Ridge was originally designed for correlated variables, and that's where it's best. Consider examinations to determine a degree. ( Which supposedly is measuring ability) Which do you think is more rel
Is there a canonical example of when ridge outperforms lasso? Ridge was originally designed for correlated variables, and that's where it's best. Consider examinations to determine a degree. ( Which supposedly is measuring ability) Which do you think is more reliable: taking the average of all the exams or picking a single exam most correlated with ability (if there is one)? Averaging over the different exams removes (independent noise - you didn't sleep well one day etc) Ridge will take the average of these correlated inputs (IE the separate exams), whilst lasso will just select one.
Is there a canonical example of when ridge outperforms lasso? Ridge was originally designed for correlated variables, and that's where it's best. Consider examinations to determine a degree. ( Which supposedly is measuring ability) Which do you think is more rel
28,295
How to calculate the PDF of the 'difference' between two Beta distributions?
I know this is a bit of an old question but for what it's worth there is an established closed-form solution to this problem, found by Pham-Gia, Turkkan, and Eng in 1993. It's a piecewise solution that relies on the Appell F1 hypergeometric function. Given $$ \begin{align} \theta_1 &= \text{beta}(\alpha_1, \beta_1) \\ \theta_2 &= \text{beta}(\alpha_2, \beta_2) \\ \theta_d &= \theta_0 - \theta_1 \end{align} $$ Then the probability of the difference of $\theta_d$ is piecewise over $\theta_d$. I've re-written it here, in case you can't access the paper. I'm using $\cdot$ to indicate multiplication when I need to break the equation over several lines. Given $A = \text{Beta}(\alpha_1, \beta_1)\text{Beta}(\alpha_2, \beta_2)$. For $-1 \leq \theta_d < 0$: $$ \begin{align} p(\theta_d) = &\text{Beta}(\alpha_2, \beta_1)\theta_d^{\beta_1 + \beta_2 - 1}(1 - \theta_d)^{\alpha_2 + \beta_1 - 1} \\ &\cdot F_1(\beta_1, \alpha_1 + \beta_1 + \alpha_2 + \beta_2 - 2, 1 - \alpha_1; \beta_1 + \alpha_2; 1 - \theta_d, 1 - \theta_d^2) \\ &/ A \end{align} $$ For $0 < \theta_d \leq 1$: $$ \begin{align} p(\theta_d) = &\text{Beta}(\alpha_1, \beta_2)\theta_d^{\beta_1 + \beta_2 - 1}(1 - \theta_d)^{\alpha_1 + \beta_2 - 1} \\ &\cdot F_1(\beta_2, 1 - \alpha_2, \alpha_1 + \beta_1 + \alpha_2 + \beta_2 - 2; \alpha_1 + \beta_2; 1 - \theta_d^2, 1 + \theta_d) \\ &/ A \end{align} $$ And for $\theta_d = 0$, $\alpha_1 + \alpha_2 > 1$, $\beta_1 + \beta_2 > 1$: $$ p(\theta_d) = \text{Beta}(\alpha_1 + \alpha_2 - 1, \beta_1 + \beta_2 -1) / A $$ As for the family of this distribution, I'm honestly not sure. Somebody else may be able to jump in there.
How to calculate the PDF of the 'difference' between two Beta distributions?
I know this is a bit of an old question but for what it's worth there is an established closed-form solution to this problem, found by Pham-Gia, Turkkan, and Eng in 1993. It's a piecewise solution tha
How to calculate the PDF of the 'difference' between two Beta distributions? I know this is a bit of an old question but for what it's worth there is an established closed-form solution to this problem, found by Pham-Gia, Turkkan, and Eng in 1993. It's a piecewise solution that relies on the Appell F1 hypergeometric function. Given $$ \begin{align} \theta_1 &= \text{beta}(\alpha_1, \beta_1) \\ \theta_2 &= \text{beta}(\alpha_2, \beta_2) \\ \theta_d &= \theta_0 - \theta_1 \end{align} $$ Then the probability of the difference of $\theta_d$ is piecewise over $\theta_d$. I've re-written it here, in case you can't access the paper. I'm using $\cdot$ to indicate multiplication when I need to break the equation over several lines. Given $A = \text{Beta}(\alpha_1, \beta_1)\text{Beta}(\alpha_2, \beta_2)$. For $-1 \leq \theta_d < 0$: $$ \begin{align} p(\theta_d) = &\text{Beta}(\alpha_2, \beta_1)\theta_d^{\beta_1 + \beta_2 - 1}(1 - \theta_d)^{\alpha_2 + \beta_1 - 1} \\ &\cdot F_1(\beta_1, \alpha_1 + \beta_1 + \alpha_2 + \beta_2 - 2, 1 - \alpha_1; \beta_1 + \alpha_2; 1 - \theta_d, 1 - \theta_d^2) \\ &/ A \end{align} $$ For $0 < \theta_d \leq 1$: $$ \begin{align} p(\theta_d) = &\text{Beta}(\alpha_1, \beta_2)\theta_d^{\beta_1 + \beta_2 - 1}(1 - \theta_d)^{\alpha_1 + \beta_2 - 1} \\ &\cdot F_1(\beta_2, 1 - \alpha_2, \alpha_1 + \beta_1 + \alpha_2 + \beta_2 - 2; \alpha_1 + \beta_2; 1 - \theta_d^2, 1 + \theta_d) \\ &/ A \end{align} $$ And for $\theta_d = 0$, $\alpha_1 + \alpha_2 > 1$, $\beta_1 + \beta_2 > 1$: $$ p(\theta_d) = \text{Beta}(\alpha_1 + \alpha_2 - 1, \beta_1 + \beta_2 -1) / A $$ As for the family of this distribution, I'm honestly not sure. Somebody else may be able to jump in there.
How to calculate the PDF of the 'difference' between two Beta distributions? I know this is a bit of an old question but for what it's worth there is an established closed-form solution to this problem, found by Pham-Gia, Turkkan, and Eng in 1993. It's a piecewise solution tha
28,296
When do we "stop" using multiple correction techniques?
Multiple comparisons corrections are intended to control the familywise error rate--or something like it--so they should be applied across a "family" of related hypothesis tests. In your first example, the overarching goal probably to determine whether Groups A and B differ. If you didn't control for multiple comparisons, you could trivially find an effect by adding more and more tests: if there's no difference in height or weight, throw in BMI, Zodiac Sign, and annual ice cream consumption. Eventually, one of these tests will, by chance, cross your $\alpha$ threshold, and you'll be tempted to write something goofy like "Although As and Bs may seem similar, we observed a statistically significant difference (p=0.04) in the number of pets owned raised to the mother's age power". In your second example, the tests are unrelated. Client #1 wants to know whether customers prefer red vs. orange trim on their cars. Client #2 wants to know if drug X shrinks tumors more than drug Y, Client #3 wants to know which factors affect her crop yields, and so on. These are all unrelated: any compound hypothesis relating them would be very bizarre. So...how do you define "a family" of tests? I'm not sure that any hard-and-fast rules exist. Here are some guidelines: Will multiple (formal) tests lead to the same substantial conclusion[*]? For example, suppose you're interested in the effects of diet on fitness. Differences in resting heart rate OR 40 yard dash time OR BMI OR bench press performance might lead you to the same conclusion: "Diet D improves fitness." If so, these tests all belong to the same family, and you ought to apply a multiple comparisons correction. T Reusing the same subjects or the same hypothesis also suggests they belong to the same family. For example, maybe you test the distribution of salaries paid to men vs. women in 20 different countries. Each of those tests ought to be corrected. [*] This requires a little subject matter expertise. For example, suppose you did 10 fitness tests, five of which could be said to measure "strength" and five of which measure "endurance." Do you apply a correction to all of the tests together, or separately within the "strength" and "endurance" families? Either might be okay, though you ought to be very clear about what you actually did. A better approach might be to generate composite scores, and sidestep the need for multiple comparisons corrections altogether.
When do we "stop" using multiple correction techniques?
Multiple comparisons corrections are intended to control the familywise error rate--or something like it--so they should be applied across a "family" of related hypothesis tests. In your first exampl
When do we "stop" using multiple correction techniques? Multiple comparisons corrections are intended to control the familywise error rate--or something like it--so they should be applied across a "family" of related hypothesis tests. In your first example, the overarching goal probably to determine whether Groups A and B differ. If you didn't control for multiple comparisons, you could trivially find an effect by adding more and more tests: if there's no difference in height or weight, throw in BMI, Zodiac Sign, and annual ice cream consumption. Eventually, one of these tests will, by chance, cross your $\alpha$ threshold, and you'll be tempted to write something goofy like "Although As and Bs may seem similar, we observed a statistically significant difference (p=0.04) in the number of pets owned raised to the mother's age power". In your second example, the tests are unrelated. Client #1 wants to know whether customers prefer red vs. orange trim on their cars. Client #2 wants to know if drug X shrinks tumors more than drug Y, Client #3 wants to know which factors affect her crop yields, and so on. These are all unrelated: any compound hypothesis relating them would be very bizarre. So...how do you define "a family" of tests? I'm not sure that any hard-and-fast rules exist. Here are some guidelines: Will multiple (formal) tests lead to the same substantial conclusion[*]? For example, suppose you're interested in the effects of diet on fitness. Differences in resting heart rate OR 40 yard dash time OR BMI OR bench press performance might lead you to the same conclusion: "Diet D improves fitness." If so, these tests all belong to the same family, and you ought to apply a multiple comparisons correction. T Reusing the same subjects or the same hypothesis also suggests they belong to the same family. For example, maybe you test the distribution of salaries paid to men vs. women in 20 different countries. Each of those tests ought to be corrected. [*] This requires a little subject matter expertise. For example, suppose you did 10 fitness tests, five of which could be said to measure "strength" and five of which measure "endurance." Do you apply a correction to all of the tests together, or separately within the "strength" and "endurance" families? Either might be okay, though you ought to be very clear about what you actually did. A better approach might be to generate composite scores, and sidestep the need for multiple comparisons corrections altogether.
When do we "stop" using multiple correction techniques? Multiple comparisons corrections are intended to control the familywise error rate--or something like it--so they should be applied across a "family" of related hypothesis tests. In your first exampl
28,297
When do we "stop" using multiple correction techniques?
The only real answer is - whenever you want to, as long as you can justify it. A reasonable case can be made for not adjusting at all. A reasonable case can be made for doing different things in different cases. This is more generally true of statistical analysis than most people think (see Statistics as Principled Argument by Robert Abelson for a lot more First, recognize that 5% is arbitrary. Why not 1%? Why not 10%? Why is the usual power set at 80% or 90% instead of 95% or 99%? Second, taking a tiny bit of a Bayesian view, how sure are we that the null is false? Except for some categorical tests with small populations, the null is never exactly true. If you (say) compare the heights of people with even and odd social security numbers and somehow get data for the entire population of the USA, the means will be different. Maybe in the 4th or 5th decimal place, but they won't be identical. But, in most research, we are pretty sure that the null isn't even approximately true. The whole structure is an unfortunate legacy of Fisher's situation: He was testing different treatments of plots of land at Rothamstead. In this case, the notion that the null might be approximately true was sensible. Is treatment A better than treatment B? He had no real idea - so, he tested. But, often, we do know. If we are testing a medical treatment, for instance, we can be pretty sure it has some effect. The more certain we are, a priori that the null is not close to true, the less inclined we should be to adjust p values. Also, if recruiting more subjects and doing the measurements is expensive, we may think twice about adjusting. But if we have "big data" then it's no problem. Third, remember that decreasing type I error will either increase type II error or require a bigger sample. Is a type I error worse than a type II error? The usual choices of 5% and 20% indicate that we think so. But sometimes type II error is much much worse. Suppose we have a drug that we think might reverse some disease which is terminal and currently untreatable. Then a type I error means giving an ineffective drug to a dying person while a type II error means letting someone die who could be cured. Finally, remember that the whole significance testing apparatus is increasingly criticized, with varying degrees of severity. I'm a pretty harsh critic (you may have figured that out by now!) but who am I? Just some guy on Cross Validated. But the American Statistical Association has (to a much lesser degree) joined the critics.
When do we "stop" using multiple correction techniques?
The only real answer is - whenever you want to, as long as you can justify it. A reasonable case can be made for not adjusting at all. A reasonable case can be made for doing different things in diffe
When do we "stop" using multiple correction techniques? The only real answer is - whenever you want to, as long as you can justify it. A reasonable case can be made for not adjusting at all. A reasonable case can be made for doing different things in different cases. This is more generally true of statistical analysis than most people think (see Statistics as Principled Argument by Robert Abelson for a lot more First, recognize that 5% is arbitrary. Why not 1%? Why not 10%? Why is the usual power set at 80% or 90% instead of 95% or 99%? Second, taking a tiny bit of a Bayesian view, how sure are we that the null is false? Except for some categorical tests with small populations, the null is never exactly true. If you (say) compare the heights of people with even and odd social security numbers and somehow get data for the entire population of the USA, the means will be different. Maybe in the 4th or 5th decimal place, but they won't be identical. But, in most research, we are pretty sure that the null isn't even approximately true. The whole structure is an unfortunate legacy of Fisher's situation: He was testing different treatments of plots of land at Rothamstead. In this case, the notion that the null might be approximately true was sensible. Is treatment A better than treatment B? He had no real idea - so, he tested. But, often, we do know. If we are testing a medical treatment, for instance, we can be pretty sure it has some effect. The more certain we are, a priori that the null is not close to true, the less inclined we should be to adjust p values. Also, if recruiting more subjects and doing the measurements is expensive, we may think twice about adjusting. But if we have "big data" then it's no problem. Third, remember that decreasing type I error will either increase type II error or require a bigger sample. Is a type I error worse than a type II error? The usual choices of 5% and 20% indicate that we think so. But sometimes type II error is much much worse. Suppose we have a drug that we think might reverse some disease which is terminal and currently untreatable. Then a type I error means giving an ineffective drug to a dying person while a type II error means letting someone die who could be cured. Finally, remember that the whole significance testing apparatus is increasingly criticized, with varying degrees of severity. I'm a pretty harsh critic (you may have figured that out by now!) but who am I? Just some guy on Cross Validated. But the American Statistical Association has (to a much lesser degree) joined the critics.
When do we "stop" using multiple correction techniques? The only real answer is - whenever you want to, as long as you can justify it. A reasonable case can be made for not adjusting at all. A reasonable case can be made for doing different things in diffe
28,298
Is mean absolute deviation smaller than standard deviation for $n\ge 3$?
No, in general this is not true. A simple way to look at this is to simulate. I typically hack together an infinite loop that stops if it finds a counterexample. If it runs for a long time, I start thinking about whether the claim might be true. In the present case, my R code looks like this: while ( TRUE ) { xx <- runif(3) mad <- sum(abs(xx-mean(xx)))/(length(xx)-1) sd <- sqrt(sum((xx-mean(xx))^2)/(length(xx)-1)) if ( mad > sd ) break } xx It yields this counterexample: [1] 0.7852480 0.0760231 0.8295893
Is mean absolute deviation smaller than standard deviation for $n\ge 3$?
No, in general this is not true. A simple way to look at this is to simulate. I typically hack together an infinite loop that stops if it finds a counterexample. If it runs for a long time, I start th
Is mean absolute deviation smaller than standard deviation for $n\ge 3$? No, in general this is not true. A simple way to look at this is to simulate. I typically hack together an infinite loop that stops if it finds a counterexample. If it runs for a long time, I start thinking about whether the claim might be true. In the present case, my R code looks like this: while ( TRUE ) { xx <- runif(3) mad <- sum(abs(xx-mean(xx)))/(length(xx)-1) sd <- sqrt(sum((xx-mean(xx))^2)/(length(xx)-1)) if ( mad > sd ) break } xx It yields this counterexample: [1] 0.7852480 0.0760231 0.8295893
Is mean absolute deviation smaller than standard deviation for $n\ge 3$? No, in general this is not true. A simple way to look at this is to simulate. I typically hack together an infinite loop that stops if it finds a counterexample. If it runs for a long time, I start th
28,299
Is mean absolute deviation smaller than standard deviation for $n\ge 3$?
Here is a more mathematical approach. Firstly, it's probably true that by a change of variables, one can assume that the mean is zero. Certainly from the point of view of finding a counter example, this is acceptable. So, setting $ \mu = 0$, squaring both sides of the proposed inequality and multiplying through by (n-1) one is left with the proposed inequality - $ (\sum_{i=1}^{i=n}|x_i|)^2 \leq (n-1)(\sum_{i=1}^{i=n}|x_i|^2))$ This looks fishy. (n-1) isn't enough to make up for all the $|x_i| |x_j|$ terms . Particularly if all the $x_i$ are the same in absolute value. My first guess was n=4 and $ x_1 = x_2 =1, x_3=x_4 = -1$. This leads to $\frac{4}{3} \leq \sqrt{\frac{4}{3}}$ . I would think that this sort of thing is well known to people interested in inequalities.
Is mean absolute deviation smaller than standard deviation for $n\ge 3$?
Here is a more mathematical approach. Firstly, it's probably true that by a change of variables, one can assume that the mean is zero. Certainly from the point of view of finding a counter example, t
Is mean absolute deviation smaller than standard deviation for $n\ge 3$? Here is a more mathematical approach. Firstly, it's probably true that by a change of variables, one can assume that the mean is zero. Certainly from the point of view of finding a counter example, this is acceptable. So, setting $ \mu = 0$, squaring both sides of the proposed inequality and multiplying through by (n-1) one is left with the proposed inequality - $ (\sum_{i=1}^{i=n}|x_i|)^2 \leq (n-1)(\sum_{i=1}^{i=n}|x_i|^2))$ This looks fishy. (n-1) isn't enough to make up for all the $|x_i| |x_j|$ terms . Particularly if all the $x_i$ are the same in absolute value. My first guess was n=4 and $ x_1 = x_2 =1, x_3=x_4 = -1$. This leads to $\frac{4}{3} \leq \sqrt{\frac{4}{3}}$ . I would think that this sort of thing is well known to people interested in inequalities.
Is mean absolute deviation smaller than standard deviation for $n\ge 3$? Here is a more mathematical approach. Firstly, it's probably true that by a change of variables, one can assume that the mean is zero. Certainly from the point of view of finding a counter example, t
28,300
Choosing conf.type for survfit in R
The typical formula for the Kaplan-Meier survival function is $$\hat{S}(t) = \prod_{j|t_j \le t} \left( \dfrac{n_j - d_j}{n_j} \right)$$ where $t_j$ are the times at which failure $j=1,\dots,$ occurs, $n_j$ is the number at risk just before time $t_j$ and $d_j$ is the number of failures at time $t_j$. Importantly, $0 \le \hat{S}(t) \le 1$. Greenwood in 1926 gave us the formula for the standard error of $\hat{S}(t)$ through its variance: $$\widehat{Var}\{\hat{S}(t)\} = \hat{S^2}(t) \sum_{j|t_j \le t} \dfrac{d_j}{n_j (n_j - d_j)}$$ Using the standard error derived from Greenwood's formula, we can calculate the $(\alpha \times 100)$ percent pointwise confidence interval of $\hat{S}(t)$ as $$\left[\hat{S}(t) - z_{1-\alpha/2}\sqrt{\widehat{Var}\{\hat{S}(t)\}},\ \hat{S}(t) + z_{1-\alpha/2}\sqrt{\widehat{Var}\{\hat{S}(t)\}} \right]$$ This is what you get when you specify conf.type="plain". There are several well-known problems with the Greenwood formula. One nasty one is that it may produce limits beyond the range of zero or one. That is to say, you can produce negative point estimates or point estimates exceeding 100%. In common practice, we just clip the confidence interval at zero or one and move on. Still the problem persists and, for teaching purposes, the Greenwood formula is relatively simple to calculate by hand and countless Master's students have learned to calculate confidence intervals for Kaplan-Meier curves on Greenwood's formula. One way around this is to change the scale of the survival function $\hat{S}(t)$ by taking its log (that is, $\log\hat{S}(t)$. If we do that, it turns out that the confidence interval is similar $$\left[\hat{S}(t) e^{- z_{1-\alpha/2}\sqrt{\widehat{Var}\{\hat{S}(t)\}}},\ \hat{S}(t)e^{z_{1-\alpha/2}\sqrt{\widehat{Var}\{\hat{S}(t)\}}} \right]$$ This is what you get when you specify conf.type="log" (the default). However, while we might have solved the problem of negative values for $\hat{S}(t)$, there is nothing that constrains the upper confidence limit from exceeding 1. This brings us to the final attempt at taming the confidence limits. Here, we first take the negative of the log of $\hat{S}(t)$. Then, we take the log of that. That is, we try to calculate confidence limits for $\hat{S}(t)$ in the complimentary log-log scale: $\log \{-\log \hat{S}(t) \}$. This is what you get when you specify conf.type="log-log". The formula is rather unruly, so I won't replicate it here. Of course, there are other transformations you can use to deal with the problem, but the log and log-log ones are the most in use. Now, to your question. What confidence interval type should you use? There is no general consensus. The plain setting is great for its simplicity, the log setting produces variances that are stable, and the log-log produces intervals that are well-behaved, but may differ greatly compared to the other two settings. Finally, you must know that statistics packages differ in their default settings for the method of calculating confidence limits. R's default is the log setting while Stata and SAS use the complimentary log-log method. I do hope this helps.
Choosing conf.type for survfit in R
The typical formula for the Kaplan-Meier survival function is $$\hat{S}(t) = \prod_{j|t_j \le t} \left( \dfrac{n_j - d_j}{n_j} \right)$$ where $t_j$ are the times at which failure $j=1,\dots,$ occurs,
Choosing conf.type for survfit in R The typical formula for the Kaplan-Meier survival function is $$\hat{S}(t) = \prod_{j|t_j \le t} \left( \dfrac{n_j - d_j}{n_j} \right)$$ where $t_j$ are the times at which failure $j=1,\dots,$ occurs, $n_j$ is the number at risk just before time $t_j$ and $d_j$ is the number of failures at time $t_j$. Importantly, $0 \le \hat{S}(t) \le 1$. Greenwood in 1926 gave us the formula for the standard error of $\hat{S}(t)$ through its variance: $$\widehat{Var}\{\hat{S}(t)\} = \hat{S^2}(t) \sum_{j|t_j \le t} \dfrac{d_j}{n_j (n_j - d_j)}$$ Using the standard error derived from Greenwood's formula, we can calculate the $(\alpha \times 100)$ percent pointwise confidence interval of $\hat{S}(t)$ as $$\left[\hat{S}(t) - z_{1-\alpha/2}\sqrt{\widehat{Var}\{\hat{S}(t)\}},\ \hat{S}(t) + z_{1-\alpha/2}\sqrt{\widehat{Var}\{\hat{S}(t)\}} \right]$$ This is what you get when you specify conf.type="plain". There are several well-known problems with the Greenwood formula. One nasty one is that it may produce limits beyond the range of zero or one. That is to say, you can produce negative point estimates or point estimates exceeding 100%. In common practice, we just clip the confidence interval at zero or one and move on. Still the problem persists and, for teaching purposes, the Greenwood formula is relatively simple to calculate by hand and countless Master's students have learned to calculate confidence intervals for Kaplan-Meier curves on Greenwood's formula. One way around this is to change the scale of the survival function $\hat{S}(t)$ by taking its log (that is, $\log\hat{S}(t)$. If we do that, it turns out that the confidence interval is similar $$\left[\hat{S}(t) e^{- z_{1-\alpha/2}\sqrt{\widehat{Var}\{\hat{S}(t)\}}},\ \hat{S}(t)e^{z_{1-\alpha/2}\sqrt{\widehat{Var}\{\hat{S}(t)\}}} \right]$$ This is what you get when you specify conf.type="log" (the default). However, while we might have solved the problem of negative values for $\hat{S}(t)$, there is nothing that constrains the upper confidence limit from exceeding 1. This brings us to the final attempt at taming the confidence limits. Here, we first take the negative of the log of $\hat{S}(t)$. Then, we take the log of that. That is, we try to calculate confidence limits for $\hat{S}(t)$ in the complimentary log-log scale: $\log \{-\log \hat{S}(t) \}$. This is what you get when you specify conf.type="log-log". The formula is rather unruly, so I won't replicate it here. Of course, there are other transformations you can use to deal with the problem, but the log and log-log ones are the most in use. Now, to your question. What confidence interval type should you use? There is no general consensus. The plain setting is great for its simplicity, the log setting produces variances that are stable, and the log-log produces intervals that are well-behaved, but may differ greatly compared to the other two settings. Finally, you must know that statistics packages differ in their default settings for the method of calculating confidence limits. R's default is the log setting while Stata and SAS use the complimentary log-log method. I do hope this helps.
Choosing conf.type for survfit in R The typical formula for the Kaplan-Meier survival function is $$\hat{S}(t) = \prod_{j|t_j \le t} \left( \dfrac{n_j - d_j}{n_j} \right)$$ where $t_j$ are the times at which failure $j=1,\dots,$ occurs,