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
30,301
beta-binomial as conjugate to hypergeometric
Hypergeometric distribution describes sampling without replacement from the urn containing $N$ balls, out of which $M \le N$ are target balls, let's say blue. The conjugate beta-binomial prior distribution leads to posterior distribution for unknown $M \in \{x,x+1,\dots,N-n+x\}$ in form $$ f(M\mid x,N,\alpha,\beta) = {N-n \choose M-x} \frac{\Gamma(\alpha+M)\,\Gamma(\beta+N-x)\,\Gamma(\alpha+\beta+n)}{\Gamma(\alpha+x)\,\Gamma(\beta+n-x)\,\Gamma(\alpha+\beta+N)} $$ as described in Dyer, D. and Pierce, R.L. (1993). On the Choice of the Prior Distribution in Hypergeometric Sampling. Communications in Statistics - Theory and Methods, 22(8), 2125-2146.
beta-binomial as conjugate to hypergeometric
Hypergeometric distribution describes sampling without replacement from the urn containing $N$ balls, out of which $M \le N$ are target balls, let's say blue. The conjugate beta-binomial prior distrib
beta-binomial as conjugate to hypergeometric Hypergeometric distribution describes sampling without replacement from the urn containing $N$ balls, out of which $M \le N$ are target balls, let's say blue. The conjugate beta-binomial prior distribution leads to posterior distribution for unknown $M \in \{x,x+1,\dots,N-n+x\}$ in form $$ f(M\mid x,N,\alpha,\beta) = {N-n \choose M-x} \frac{\Gamma(\alpha+M)\,\Gamma(\beta+N-x)\,\Gamma(\alpha+\beta+n)}{\Gamma(\alpha+x)\,\Gamma(\beta+n-x)\,\Gamma(\alpha+\beta+N)} $$ as described in Dyer, D. and Pierce, R.L. (1993). On the Choice of the Prior Distribution in Hypergeometric Sampling. Communications in Statistics - Theory and Methods, 22(8), 2125-2146.
beta-binomial as conjugate to hypergeometric Hypergeometric distribution describes sampling without replacement from the urn containing $N$ balls, out of which $M \le N$ are target balls, let's say blue. The conjugate beta-binomial prior distrib
30,302
beta-binomial as conjugate to hypergeometric
As I cannot comment: the formula given by @Tom is not correct, the correct formula is : $$ f(M\mid x,N,\alpha,\beta) = {N-n \choose M-x} \frac{\Gamma(\alpha+M)\,\Gamma(\beta+N-M)\,\Gamma(\alpha+\beta+n)}{\Gamma(\alpha+x)\,\Gamma(\beta+n-x)\,\Gamma(\alpha+\beta+N)} $$ The formula is also wrong in the reference: Dyer, D. and Pierce, R.L. (1993). On the Choice of the Prior Distribution in Hypergeometric Sampling. Communications in Statistics Theory and Methods, 22(8), 2125-2146. at p. 2131. It is clearly a typo because on the same page, few lines below, that formula (in its correct form) is used to derive equation (3.1.3)
beta-binomial as conjugate to hypergeometric
As I cannot comment: the formula given by @Tom is not correct, the correct formula is : $$ f(M\mid x,N,\alpha,\beta) = {N-n \choose M-x} \frac{\Gamma(\alpha+M)\,\Gamma(\beta+N-M)\,\Gamma(\alpha+\beta+
beta-binomial as conjugate to hypergeometric As I cannot comment: the formula given by @Tom is not correct, the correct formula is : $$ f(M\mid x,N,\alpha,\beta) = {N-n \choose M-x} \frac{\Gamma(\alpha+M)\,\Gamma(\beta+N-M)\,\Gamma(\alpha+\beta+n)}{\Gamma(\alpha+x)\,\Gamma(\beta+n-x)\,\Gamma(\alpha+\beta+N)} $$ The formula is also wrong in the reference: Dyer, D. and Pierce, R.L. (1993). On the Choice of the Prior Distribution in Hypergeometric Sampling. Communications in Statistics Theory and Methods, 22(8), 2125-2146. at p. 2131. It is clearly a typo because on the same page, few lines below, that formula (in its correct form) is used to derive equation (3.1.3)
beta-binomial as conjugate to hypergeometric As I cannot comment: the formula given by @Tom is not correct, the correct formula is : $$ f(M\mid x,N,\alpha,\beta) = {N-n \choose M-x} \frac{\Gamma(\alpha+M)\,\Gamma(\beta+N-M)\,\Gamma(\alpha+\beta+
30,303
Density estimation for large dataset
There are some tricks you can play with kernel density estimators (KDEs) to improve runtime. For example, you can use a kernel with compact support (e.g. an Epanechnikov or triweight kernel). To obtain perfect accuracy using a kernel with infinite support (e.g. a Gaussian), you'd have to sum over all kernels every time you want to evaluate the KDE. However, with compact support, you'd only need to sum over kernels whose support the evaluation point falls within (because the kernels have value 0 outside this range). Say the data points are $\{x_1, ..., x_n\}$ and you want to evaluate the KDE at point $x'$. Let $r$ be the 'radius' of the kernel function (half the width of the support). You can search for data points that fall within distance $r$ of $x'$, and evaluate those kernels only. The search can be performed efficiently (requiring sublinear time). In general, people use tree data structures (e.g. kd trees, ball trees) to accelerate the search. Since your data are 1d, you might be able to get away with something simpler (like storing the data in a sorted list and using binary search). For kernels with infinite support, it's possible to employ a similar strategy (evaluating only nearby kernels), at the cost of a decrease in accuracy. The following paper describes the use of tree data structures for accelerating KDEs. It also describes a 'dual tree' strategy, where a second tree is used to partition the points at which the KDE is to be evaluated. This allows processing them in chunks, with further efficiency gains. Gray and Moore (2003). Nonparametric Density Estimation: Toward Computational Tractability For example implementations, see scikit-learn (python) and the kernel density estimation toolbox (Matlab). Another strategy for accelerating KDEs is binning/gridding. In this approach, the data are approximated using a set of bins, which receive weight according to the proximity of data points. The KDE is also evaluated at the bins (evaluation points will no longer be exact, which may or may not work for your application). This strategy reduces the number of kernel evaluations at the cost of accuracy. Further performance gains can be had by using the fast Fourier transform (FFT) to compute the binned KDE. Hall and Wand (1994). On the Accuracy of Binned Kernel Density Estimators Silverman (1982). Kernel Density Estimation Using the Fast Fourier Transform Gray and Moore (2003). [Above] For example implementation using FFTs, see StatsModels (python). This blog post discusses tree-based and FFT-based KDEs, and gives some benchmark results. If you care about evaluation time but not training time, you could use a mixture model instead of a KDE (KDEs being a special case of mixture models, with a mixture component centered over each data point, all sharing the same width). Using fewer mixture components will speed up evaluation time. It may be possible to combine the first strategy (compact support + efficient search) with mixture models. Another option would be to use interpolation. Fit whatever density estimator you like and evaluate it at a fixed number of points $y = \{y_1, ..., y_m\}$, giving corresponding density values $p = \{p_1, ..., p_m\}$. To evaluate the density at a new point $x'$, perform interpolation using $y$ and $p$. This could be simple linear interpolation, or something fancier like splines. Decreasing $m$ will give a less faithful representation of the density estimate, but faster evaluation times. You could even choose $y$ adaptively, since fewer points will be required in regions where the function is smoother. Interpolation will require finding points in $y$ that are near to $x'$. As before, efficient search procedures can be used.
Density estimation for large dataset
There are some tricks you can play with kernel density estimators (KDEs) to improve runtime. For example, you can use a kernel with compact support (e.g. an Epanechnikov or triweight kernel). To obtai
Density estimation for large dataset There are some tricks you can play with kernel density estimators (KDEs) to improve runtime. For example, you can use a kernel with compact support (e.g. an Epanechnikov or triweight kernel). To obtain perfect accuracy using a kernel with infinite support (e.g. a Gaussian), you'd have to sum over all kernels every time you want to evaluate the KDE. However, with compact support, you'd only need to sum over kernels whose support the evaluation point falls within (because the kernels have value 0 outside this range). Say the data points are $\{x_1, ..., x_n\}$ and you want to evaluate the KDE at point $x'$. Let $r$ be the 'radius' of the kernel function (half the width of the support). You can search for data points that fall within distance $r$ of $x'$, and evaluate those kernels only. The search can be performed efficiently (requiring sublinear time). In general, people use tree data structures (e.g. kd trees, ball trees) to accelerate the search. Since your data are 1d, you might be able to get away with something simpler (like storing the data in a sorted list and using binary search). For kernels with infinite support, it's possible to employ a similar strategy (evaluating only nearby kernels), at the cost of a decrease in accuracy. The following paper describes the use of tree data structures for accelerating KDEs. It also describes a 'dual tree' strategy, where a second tree is used to partition the points at which the KDE is to be evaluated. This allows processing them in chunks, with further efficiency gains. Gray and Moore (2003). Nonparametric Density Estimation: Toward Computational Tractability For example implementations, see scikit-learn (python) and the kernel density estimation toolbox (Matlab). Another strategy for accelerating KDEs is binning/gridding. In this approach, the data are approximated using a set of bins, which receive weight according to the proximity of data points. The KDE is also evaluated at the bins (evaluation points will no longer be exact, which may or may not work for your application). This strategy reduces the number of kernel evaluations at the cost of accuracy. Further performance gains can be had by using the fast Fourier transform (FFT) to compute the binned KDE. Hall and Wand (1994). On the Accuracy of Binned Kernel Density Estimators Silverman (1982). Kernel Density Estimation Using the Fast Fourier Transform Gray and Moore (2003). [Above] For example implementation using FFTs, see StatsModels (python). This blog post discusses tree-based and FFT-based KDEs, and gives some benchmark results. If you care about evaluation time but not training time, you could use a mixture model instead of a KDE (KDEs being a special case of mixture models, with a mixture component centered over each data point, all sharing the same width). Using fewer mixture components will speed up evaluation time. It may be possible to combine the first strategy (compact support + efficient search) with mixture models. Another option would be to use interpolation. Fit whatever density estimator you like and evaluate it at a fixed number of points $y = \{y_1, ..., y_m\}$, giving corresponding density values $p = \{p_1, ..., p_m\}$. To evaluate the density at a new point $x'$, perform interpolation using $y$ and $p$. This could be simple linear interpolation, or something fancier like splines. Decreasing $m$ will give a less faithful representation of the density estimate, but faster evaluation times. You could even choose $y$ adaptively, since fewer points will be required in regions where the function is smoother. Interpolation will require finding points in $y$ that are near to $x'$. As before, efficient search procedures can be used.
Density estimation for large dataset There are some tricks you can play with kernel density estimators (KDEs) to improve runtime. For example, you can use a kernel with compact support (e.g. an Epanechnikov or triweight kernel). To obtai
30,304
Density estimation for large dataset
A vector of $10^6$ elements is not a particularly large sample for density estimation. Linear binning can be used to accelerate kernel density estimation (similar to usual binning, but probability mass is linearly distributed from data points to surrounding grid points), as well as FFT or even splines (which are very fast to evaluate, once the coefficients have been computed). There is a very nice pre-print on the topic by Henry Deng and Hadley Wickham. If you are only interested in kernel density approaches, and not in stuff such as shifted histograms or penalized likelihood, then the tricks mentioned before are implemented in some R packages, such as KernSmooth, sm and density (this last one is included in base R). Personally, I found also ASH and logspline to work well (and be fast), but they're not based on the KDE paradigm, which may or may not be what you're looking for. Also, another thing that sometimes makes a difference (for example, it speeds up the FFT step, which however is rarely the limiting step in terms of performance), is to use an R binary which is optimized to take full advantage of the BLAS and LAPACK for the specific machine you're working on, as well as run on multiple cores if your PC has a multicore CPU (which I think is true for all PCs on the market today). For this, If you have a Windows pc, I definitely recommend using Microsoft R Open. If you have a Mac, then compiling R with the Accelerate framework should do the trick. I don't know how to get architecture-optimized BLAS & LAPACK under Linux, but I'm sure there's a way.
Density estimation for large dataset
A vector of $10^6$ elements is not a particularly large sample for density estimation. Linear binning can be used to accelerate kernel density estimation (similar to usual binning, but probability mas
Density estimation for large dataset A vector of $10^6$ elements is not a particularly large sample for density estimation. Linear binning can be used to accelerate kernel density estimation (similar to usual binning, but probability mass is linearly distributed from data points to surrounding grid points), as well as FFT or even splines (which are very fast to evaluate, once the coefficients have been computed). There is a very nice pre-print on the topic by Henry Deng and Hadley Wickham. If you are only interested in kernel density approaches, and not in stuff such as shifted histograms or penalized likelihood, then the tricks mentioned before are implemented in some R packages, such as KernSmooth, sm and density (this last one is included in base R). Personally, I found also ASH and logspline to work well (and be fast), but they're not based on the KDE paradigm, which may or may not be what you're looking for. Also, another thing that sometimes makes a difference (for example, it speeds up the FFT step, which however is rarely the limiting step in terms of performance), is to use an R binary which is optimized to take full advantage of the BLAS and LAPACK for the specific machine you're working on, as well as run on multiple cores if your PC has a multicore CPU (which I think is true for all PCs on the market today). For this, If you have a Windows pc, I definitely recommend using Microsoft R Open. If you have a Mac, then compiling R with the Accelerate framework should do the trick. I don't know how to get architecture-optimized BLAS & LAPACK under Linux, but I'm sure there's a way.
Density estimation for large dataset A vector of $10^6$ elements is not a particularly large sample for density estimation. Linear binning can be used to accelerate kernel density estimation (similar to usual binning, but probability mas
30,305
intuitive difference between joint probability and conditional probability in this example
You actually had your answer right there. $P(H=hit)$ is the marginal probability. It reads "The probability of getting hit.". It is the proportion of people that got hit crossing the street, irrespective of traffic light. $P(H=hit|L=red)$ is the conditional probability. It reads "The probability that you get hit, given that the light is red". It is the proportion of hits among the people that cross the street in red light. Finally, $P(H=hit, L=red)$ is the joint probability. It reads "the probability that a person gets hit by a car and that the light is red". It is the proportion of hits in red light among all people. You certainly know the relationship $P(H=hit, L=red) = P(H=hit | L=red) * P(L=red)$ In "layman's parlance", we can look at it as follows. Assume that the probability of having a red light is extremely small, but that people always get hit when crossing in red light. Let us assume you are an observer at the side of the street. You will see people getting hit, and rarely will you see the light turning red. Out of all people that cross the street, the chance they will get hit in red light is very tiny, since they almost never have that opportunity ($P(H=hit,L=red)$ is small because a red light is rare). However, if you observe long enough, you will eventually see people getting hit in red light, and notice that whenever the light is red, people crossing the street will get hit for sure ($P(H=hit|L=red)=1$).
intuitive difference between joint probability and conditional probability in this example
You actually had your answer right there. $P(H=hit)$ is the marginal probability. It reads "The probability of getting hit.". It is the proportion of people that got hit crossing the street, irrespect
intuitive difference between joint probability and conditional probability in this example You actually had your answer right there. $P(H=hit)$ is the marginal probability. It reads "The probability of getting hit.". It is the proportion of people that got hit crossing the street, irrespective of traffic light. $P(H=hit|L=red)$ is the conditional probability. It reads "The probability that you get hit, given that the light is red". It is the proportion of hits among the people that cross the street in red light. Finally, $P(H=hit, L=red)$ is the joint probability. It reads "the probability that a person gets hit by a car and that the light is red". It is the proportion of hits in red light among all people. You certainly know the relationship $P(H=hit, L=red) = P(H=hit | L=red) * P(L=red)$ In "layman's parlance", we can look at it as follows. Assume that the probability of having a red light is extremely small, but that people always get hit when crossing in red light. Let us assume you are an observer at the side of the street. You will see people getting hit, and rarely will you see the light turning red. Out of all people that cross the street, the chance they will get hit in red light is very tiny, since they almost never have that opportunity ($P(H=hit,L=red)$ is small because a red light is rare). However, if you observe long enough, you will eventually see people getting hit in red light, and notice that whenever the light is red, people crossing the street will get hit for sure ($P(H=hit|L=red)=1$).
intuitive difference between joint probability and conditional probability in this example You actually had your answer right there. $P(H=hit)$ is the marginal probability. It reads "The probability of getting hit.". It is the proportion of people that got hit crossing the street, irrespect
30,306
intuitive difference between joint probability and conditional probability in this example
$H$ and $L$ are random variables. $H$ takes a value in $\{ \text{hit, not hit} \}$ and $L$ takes a value in $\{ \text{red, yellow, green} \}$. In this example, the joint distribution $P(H, L)$ gives the probability of two things both happening: that $H$ takes a particular value $h$ and $L$ takes a particular value $l$. You can also write this as $P(H=h \text{ and } L=l)$. To get the probability of a particular combination, you plug in values for $h$ and $l$. For example, $P(H=\text{hit}, L=\text{red})$ is the probability that the person is hit and the light is red. You can think of there being a total probability (that sums to 1), which is like a fixed amount of 'stuff' (e.g. a liquid). The joint distribution takes this and spreads it out in different amounts over all possible combinations of values for $H$ and $L$.
intuitive difference between joint probability and conditional probability in this example
$H$ and $L$ are random variables. $H$ takes a value in $\{ \text{hit, not hit} \}$ and $L$ takes a value in $\{ \text{red, yellow, green} \}$. In this example, the joint distribution $P(H, L)$ gives t
intuitive difference between joint probability and conditional probability in this example $H$ and $L$ are random variables. $H$ takes a value in $\{ \text{hit, not hit} \}$ and $L$ takes a value in $\{ \text{red, yellow, green} \}$. In this example, the joint distribution $P(H, L)$ gives the probability of two things both happening: that $H$ takes a particular value $h$ and $L$ takes a particular value $l$. You can also write this as $P(H=h \text{ and } L=l)$. To get the probability of a particular combination, you plug in values for $h$ and $l$. For example, $P(H=\text{hit}, L=\text{red})$ is the probability that the person is hit and the light is red. You can think of there being a total probability (that sums to 1), which is like a fixed amount of 'stuff' (e.g. a liquid). The joint distribution takes this and spreads it out in different amounts over all possible combinations of values for $H$ and $L$.
intuitive difference between joint probability and conditional probability in this example $H$ and $L$ are random variables. $H$ takes a value in $\{ \text{hit, not hit} \}$ and $L$ takes a value in $\{ \text{red, yellow, green} \}$. In this example, the joint distribution $P(H, L)$ gives t
30,307
intuitive difference between joint probability and conditional probability in this example
I have tried to explain this example with assumed values of Joint Probability:
intuitive difference between joint probability and conditional probability in this example
I have tried to explain this example with assumed values of Joint Probability:
intuitive difference between joint probability and conditional probability in this example I have tried to explain this example with assumed values of Joint Probability:
intuitive difference between joint probability and conditional probability in this example I have tried to explain this example with assumed values of Joint Probability:
30,308
intuitive difference between joint probability and conditional probability in this example
This is all about perspective. Imagine a much simpler context. Say there are two different events A and B within a rectangular event space. We can colour the event spaces in green and blue circles and the overlapping area in red. Now, when we are saying P(A,B), or P(A|B), both of this indicates the events within the red area. But the perspective is different. In case of P(A,B), the probability is (the area of the red space) / (the area of the whole rectangle) In case of P(A|B), the probability is (the area of the red space) / (the area of the blue circle B) Now, imagine the traffic scenerio. Say, you are counting how many pedestrians are crossing the road and how many pedestrians are getting hit. Your counts are following, Number of pedestrians crossing the road in green, yellow and red signals = X, Y, Z Number of pedestrians getting hit crossing the road in green, yellow and red signals = A, B, C Now, P(Hit, Red) = C/(X + Y + Z) P(Hit|Red) = (C/(X+Y+Z))/(Z/(X+Y+Z)) = C/Z So, in each case, of course, you have to count the pedestrians getting hit in red signals only to calculate C. When you count the probability P(Hit, Red), you have to count all the crossing pedestrians. But when you count the probability P(Hit|Red) you only have to count the pedestrian crossing, when the red light is on.
intuitive difference between joint probability and conditional probability in this example
This is all about perspective. Imagine a much simpler context. Say there are two different events A and B within a rectangular event space. We can colour the event spaces in green and blue circles and
intuitive difference between joint probability and conditional probability in this example This is all about perspective. Imagine a much simpler context. Say there are two different events A and B within a rectangular event space. We can colour the event spaces in green and blue circles and the overlapping area in red. Now, when we are saying P(A,B), or P(A|B), both of this indicates the events within the red area. But the perspective is different. In case of P(A,B), the probability is (the area of the red space) / (the area of the whole rectangle) In case of P(A|B), the probability is (the area of the red space) / (the area of the blue circle B) Now, imagine the traffic scenerio. Say, you are counting how many pedestrians are crossing the road and how many pedestrians are getting hit. Your counts are following, Number of pedestrians crossing the road in green, yellow and red signals = X, Y, Z Number of pedestrians getting hit crossing the road in green, yellow and red signals = A, B, C Now, P(Hit, Red) = C/(X + Y + Z) P(Hit|Red) = (C/(X+Y+Z))/(Z/(X+Y+Z)) = C/Z So, in each case, of course, you have to count the pedestrians getting hit in red signals only to calculate C. When you count the probability P(Hit, Red), you have to count all the crossing pedestrians. But when you count the probability P(Hit|Red) you only have to count the pedestrian crossing, when the red light is on.
intuitive difference between joint probability and conditional probability in this example This is all about perspective. Imagine a much simpler context. Say there are two different events A and B within a rectangular event space. We can colour the event spaces in green and blue circles and
30,309
intuitive difference between joint probability and conditional probability in this example
Maybe there is a simpler explanation without requiring equations. A fraction of people get hit regardless of light color (marginal prob). Of these hit people, a fraction get hit on red (conditional on red prob). Thus, to get an actual fraction of total population, multiply the two (joint probability).
intuitive difference between joint probability and conditional probability in this example
Maybe there is a simpler explanation without requiring equations. A fraction of people get hit regardless of light color (marginal prob). Of these hit people, a fraction get hit on red (conditional on
intuitive difference between joint probability and conditional probability in this example Maybe there is a simpler explanation without requiring equations. A fraction of people get hit regardless of light color (marginal prob). Of these hit people, a fraction get hit on red (conditional on red prob). Thus, to get an actual fraction of total population, multiply the two (joint probability).
intuitive difference between joint probability and conditional probability in this example Maybe there is a simpler explanation without requiring equations. A fraction of people get hit regardless of light color (marginal prob). Of these hit people, a fraction get hit on red (conditional on
30,310
intuitive difference between joint probability and conditional probability in this example
The intuitive difference among the two are: 1) Conditional probability P(H=hit|L=red) - Probability when light was red and people got hit, It doesn't consider all the people crossing the traffic. 2) Joint probability P(H=hit,L=red) - Probability of people getting hit and the light being red. Key difference - in 1), sample space are not all the people, It's only those people crossing red light, in 2) sample space are everyone and intersection of people crossing red light and getting hit is the joint probability.
intuitive difference between joint probability and conditional probability in this example
The intuitive difference among the two are: 1) Conditional probability P(H=hit|L=red) - Probability when light was red and people got hit, It doesn't consider all the people crossing the traffic. 2) J
intuitive difference between joint probability and conditional probability in this example The intuitive difference among the two are: 1) Conditional probability P(H=hit|L=red) - Probability when light was red and people got hit, It doesn't consider all the people crossing the traffic. 2) Joint probability P(H=hit,L=red) - Probability of people getting hit and the light being red. Key difference - in 1), sample space are not all the people, It's only those people crossing red light, in 2) sample space are everyone and intersection of people crossing red light and getting hit is the joint probability.
intuitive difference between joint probability and conditional probability in this example The intuitive difference among the two are: 1) Conditional probability P(H=hit|L=red) - Probability when light was red and people got hit, It doesn't consider all the people crossing the traffic. 2) J
30,311
"t value" associated with nlme/lme4
Basically $t$ is just $\beta/\mathrm{SE}(\beta)$, where $\beta$ is regression parameter. There is nothing misleading in this value if you consider it as this ratio, or as "standarized" parameter. If you look at Bates' original arguments against $p$-values in lme4 he writes mostly about the degrees of freedom that are problematic rather than the $t$ of $F$ values themselves (see also r-sig-mixed-models FAQ). Notice that different statistical software can have different naming convention, e.g. as SPSS calls parameters as $B$'s and standarized parameters as $\beta$'s -- lme4 follows the lm convention to call them Estimate and t value. Pinheiro and Bates describe usage of $p$-values in "Mixed-Effects Models in S and S-PLUS", so it is hard to look for arguments against them in this book. The ratios are also discussed by Bates in "lme4: Mixed-effects modeling with R" in comparison to $t$ and $F$ values for fixed effects models, for example (p. 70): In a fixed-effects model the profile traces in the original scale will always be straight lines. For mixed models these traces can fail to be linear, as we see here, contradicting the widely-held belief that inferences for the fixed-effects parameters in linear mixed models, based on $T$ or $F$ distributions with suitably adjusted degrees of freedom, will be completely accurate. The actual patterns of deviance contours are more complex than that. what makes them somehow similar while not exactly adequate as we would expect them to be for proper hypothesis testing. Notice also that other authors not always consider the df issue to be problematic, e.g. Gałecki and Burzykowski in "Linear Mixed-Effects Models Using R" just assume $n-p$ degrees of freedom and treat their distribution as approximately $t$, e.g. (p. 84): The null distribution of the $t$-test statistic is the $t$-distribution with $n − p$ degrees of freedom. and (p. 140): Confidence intervals for individual components of the parameter vector $\beta$ can be constructed based on a $t$-distribution used as an approximate distribution for the test statistic So it seems that the main rationale is that while $p$-values can be misleading because of unclear null distribution, $t$ values can still be useful, at least as standardized parameters. You can also use them for hypothesis testing but you need to make some assumption about their distribution and verify them by looking at profile plots. What Bates seems to be saying is that you use them at your own risk.
"t value" associated with nlme/lme4
Basically $t$ is just $\beta/\mathrm{SE}(\beta)$, where $\beta$ is regression parameter. There is nothing misleading in this value if you consider it as this ratio, or as "standarized" parameter. If y
"t value" associated with nlme/lme4 Basically $t$ is just $\beta/\mathrm{SE}(\beta)$, where $\beta$ is regression parameter. There is nothing misleading in this value if you consider it as this ratio, or as "standarized" parameter. If you look at Bates' original arguments against $p$-values in lme4 he writes mostly about the degrees of freedom that are problematic rather than the $t$ of $F$ values themselves (see also r-sig-mixed-models FAQ). Notice that different statistical software can have different naming convention, e.g. as SPSS calls parameters as $B$'s and standarized parameters as $\beta$'s -- lme4 follows the lm convention to call them Estimate and t value. Pinheiro and Bates describe usage of $p$-values in "Mixed-Effects Models in S and S-PLUS", so it is hard to look for arguments against them in this book. The ratios are also discussed by Bates in "lme4: Mixed-effects modeling with R" in comparison to $t$ and $F$ values for fixed effects models, for example (p. 70): In a fixed-effects model the profile traces in the original scale will always be straight lines. For mixed models these traces can fail to be linear, as we see here, contradicting the widely-held belief that inferences for the fixed-effects parameters in linear mixed models, based on $T$ or $F$ distributions with suitably adjusted degrees of freedom, will be completely accurate. The actual patterns of deviance contours are more complex than that. what makes them somehow similar while not exactly adequate as we would expect them to be for proper hypothesis testing. Notice also that other authors not always consider the df issue to be problematic, e.g. Gałecki and Burzykowski in "Linear Mixed-Effects Models Using R" just assume $n-p$ degrees of freedom and treat their distribution as approximately $t$, e.g. (p. 84): The null distribution of the $t$-test statistic is the $t$-distribution with $n − p$ degrees of freedom. and (p. 140): Confidence intervals for individual components of the parameter vector $\beta$ can be constructed based on a $t$-distribution used as an approximate distribution for the test statistic So it seems that the main rationale is that while $p$-values can be misleading because of unclear null distribution, $t$ values can still be useful, at least as standardized parameters. You can also use them for hypothesis testing but you need to make some assumption about their distribution and verify them by looking at profile plots. What Bates seems to be saying is that you use them at your own risk.
"t value" associated with nlme/lme4 Basically $t$ is just $\beta/\mathrm{SE}(\beta)$, where $\beta$ is regression parameter. There is nothing misleading in this value if you consider it as this ratio, or as "standarized" parameter. If y
30,312
"t value" associated with nlme/lme4
Correct, the Wald statistic (reported as a "t statistic" by lme4) is, in general, at best only approximately t-distributed for linear mixed models (LMMs). It is only exactly t-distributed in certain very special cases, for example, mixed-model ANOVA with nested random factors and balanced data. For generalized linear mixed models (GLMMs) with a non-normal response, the distribution of the Wald statistic might not even be very t-like at all. For example, see this thread on logistic regression, where we show that the tails of the sampling distribution can tend be be thinner-than-normal rather than thicker-than-normal. (That thread does not focus on mixed models, but the same issue arises there.)
"t value" associated with nlme/lme4
Correct, the Wald statistic (reported as a "t statistic" by lme4) is, in general, at best only approximately t-distributed for linear mixed models (LMMs). It is only exactly t-distributed in certain v
"t value" associated with nlme/lme4 Correct, the Wald statistic (reported as a "t statistic" by lme4) is, in general, at best only approximately t-distributed for linear mixed models (LMMs). It is only exactly t-distributed in certain very special cases, for example, mixed-model ANOVA with nested random factors and balanced data. For generalized linear mixed models (GLMMs) with a non-normal response, the distribution of the Wald statistic might not even be very t-like at all. For example, see this thread on logistic regression, where we show that the tails of the sampling distribution can tend be be thinner-than-normal rather than thicker-than-normal. (That thread does not focus on mixed models, but the same issue arises there.)
"t value" associated with nlme/lme4 Correct, the Wald statistic (reported as a "t statistic" by lme4) is, in general, at best only approximately t-distributed for linear mixed models (LMMs). It is only exactly t-distributed in certain v
30,313
Numeric Gradient Checking: How close is close enough?
The closest I have seen to addressing this was in the Stanford UFLDL tutorial within the softmax regression section. Copying the key statement: The norm of the difference between the numerical gradient and your analytical gradient should be small, on the order of $10^{-9}$. In python the code would look something like this: norm(gradients - numericalGradients)/norm(gradients + numericalGradients) where gradients are you results from the derivative and numericalGradients are the approximated gradients.
Numeric Gradient Checking: How close is close enough?
The closest I have seen to addressing this was in the Stanford UFLDL tutorial within the softmax regression section. Copying the key statement: The norm of the difference between the numerical gradi
Numeric Gradient Checking: How close is close enough? The closest I have seen to addressing this was in the Stanford UFLDL tutorial within the softmax regression section. Copying the key statement: The norm of the difference between the numerical gradient and your analytical gradient should be small, on the order of $10^{-9}$. In python the code would look something like this: norm(gradients - numericalGradients)/norm(gradients + numericalGradients) where gradients are you results from the derivative and numericalGradients are the approximated gradients.
Numeric Gradient Checking: How close is close enough? The closest I have seen to addressing this was in the Stanford UFLDL tutorial within the softmax regression section. Copying the key statement: The norm of the difference between the numerical gradi
30,314
Numeric Gradient Checking: How close is close enough?
Background Theory that's helpful One small fact that you can use to help understand whether a numeric derivative is correctly calculated or not is the Cauchy Remainder of the Taylor expansion. That is, $f(x + h) = f(x) + hf'(x) + \frac{h^2}{2}f''(\xi)$ for some $\xi \in [x, x+ h]$ This is helpful, because you've probably approximated your first derivative by $f'(x)\approx \frac{f(x+h) - f(x-h)}{2h}$ with some small $h$ (I typically use $10^{-4}$, but I'm sure some day I'll run across a case where that's not appropriate). After a little algebra, we can use the Cauchy remainder to see that our numeric approximation theoretically should be within $h f''(\xi), \xi \in [x-h, x+h]$ of $f'(x)$. In fact, you can actually bound it by $h (f''(\xi_1) - f''(\xi_2) )$, where $\xi_1 \in [x-h, x]$ and $\xi_2 \in [x, x+h]$...which is equivalent to $h^2f'''(\xi)$, $\xi \in [x-h, x+h]$. Problems in Practice Okay, we have nice theory bounding the error of the numeric derivative. But there are two holes in directly trying to use those results: 1.) We don't know $f'''(x)$ (and probably don't want to spend the time approximating it) 2.) as $h \rightarrow 0$, $\frac{f(x+h) - f(x-h)}{2h}$ suffers from numeric instability So using what we know from earlier the way I check my analytic derivatives (which might not be the best way) is that I write the numeric derivative function as a function of $h$. If I can't tell whether the difference between the numeric and analytic derivatives is due to a coding mistake or just numeric approximation, I can reduce $h$ and see if my numeric derivative approaches my analytic derivative before suffering from numeric instability (when this happens, your numeric approximations will become less consistent as $h$ gets smaller). Note that $f'''(\xi)$ term should be disappearing quadratically, so if my error is about $0.01$ with $h = 10^{-4}$, it should be around $0.0001$ with $h = 10^{-5}$ assuming numeric instability has not kicked in yet. Unfortunately, there's no hard and fast guideline for always determining these things; it's very dependent on how stable the function is (and I mean both in terms in numeric stability and higher derivatives). But in my experiences, I've never seen a case where the error from $h^2 f'''(\xi)$ was not definitively going to 0 (i.e. using $h = 10^{-4}$ gave virtually the same answer as $h = 10^{-5}$) by the time the numeric instability from $h \rightarrow 0$ kicked in.
Numeric Gradient Checking: How close is close enough?
Background Theory that's helpful One small fact that you can use to help understand whether a numeric derivative is correctly calculated or not is the Cauchy Remainder of the Taylor expansion. That is
Numeric Gradient Checking: How close is close enough? Background Theory that's helpful One small fact that you can use to help understand whether a numeric derivative is correctly calculated or not is the Cauchy Remainder of the Taylor expansion. That is, $f(x + h) = f(x) + hf'(x) + \frac{h^2}{2}f''(\xi)$ for some $\xi \in [x, x+ h]$ This is helpful, because you've probably approximated your first derivative by $f'(x)\approx \frac{f(x+h) - f(x-h)}{2h}$ with some small $h$ (I typically use $10^{-4}$, but I'm sure some day I'll run across a case where that's not appropriate). After a little algebra, we can use the Cauchy remainder to see that our numeric approximation theoretically should be within $h f''(\xi), \xi \in [x-h, x+h]$ of $f'(x)$. In fact, you can actually bound it by $h (f''(\xi_1) - f''(\xi_2) )$, where $\xi_1 \in [x-h, x]$ and $\xi_2 \in [x, x+h]$...which is equivalent to $h^2f'''(\xi)$, $\xi \in [x-h, x+h]$. Problems in Practice Okay, we have nice theory bounding the error of the numeric derivative. But there are two holes in directly trying to use those results: 1.) We don't know $f'''(x)$ (and probably don't want to spend the time approximating it) 2.) as $h \rightarrow 0$, $\frac{f(x+h) - f(x-h)}{2h}$ suffers from numeric instability So using what we know from earlier the way I check my analytic derivatives (which might not be the best way) is that I write the numeric derivative function as a function of $h$. If I can't tell whether the difference between the numeric and analytic derivatives is due to a coding mistake or just numeric approximation, I can reduce $h$ and see if my numeric derivative approaches my analytic derivative before suffering from numeric instability (when this happens, your numeric approximations will become less consistent as $h$ gets smaller). Note that $f'''(\xi)$ term should be disappearing quadratically, so if my error is about $0.01$ with $h = 10^{-4}$, it should be around $0.0001$ with $h = 10^{-5}$ assuming numeric instability has not kicked in yet. Unfortunately, there's no hard and fast guideline for always determining these things; it's very dependent on how stable the function is (and I mean both in terms in numeric stability and higher derivatives). But in my experiences, I've never seen a case where the error from $h^2 f'''(\xi)$ was not definitively going to 0 (i.e. using $h = 10^{-4}$ gave virtually the same answer as $h = 10^{-5}$) by the time the numeric instability from $h \rightarrow 0$ kicked in.
Numeric Gradient Checking: How close is close enough? Background Theory that's helpful One small fact that you can use to help understand whether a numeric derivative is correctly calculated or not is the Cauchy Remainder of the Taylor expansion. That is
30,315
Numeric Gradient Checking: How close is close enough?
Please refer to this tutorial http://cs231n.github.io/neural-networks-3/#ensemble. The "Gradient Check" section is very detailed and helpful. As is suggested by gung, I include the main points of this link: Use $\frac{f(w+h)-f(w-h)}{2h}$ approximation, where $h\sim 10^{-5}$. Monitor the fraction of $\frac{|f_a'(w)-f_n'(w)|}{max(|f_a'(w)|,|f_n'(w)|)}$, where $f'_a(w)$ is the analytical gradient and $f'_n(w)$ is the numerically approximated gradient. Usually, the preferred range of this fraction should $<10^{-2}$. Use double precision instead of float. Mind of kink(s) in activation functions, e.g., $x=0$ when one uses ReLU. When there is kink(s), one needs to monitor the values of $x-h$ and $x+h$. If these two values are on two sides of a kink, one should exclude this gradient check. Use few datapoints. Do not do gradient checking at the very beginning stage of the training process. First check model without regularization and then with it. Turn off dropout and inverted dropout when doing gradient checking. Only check randomly few dimensions.
Numeric Gradient Checking: How close is close enough?
Please refer to this tutorial http://cs231n.github.io/neural-networks-3/#ensemble. The "Gradient Check" section is very detailed and helpful. As is suggested by gung, I include the main points of this
Numeric Gradient Checking: How close is close enough? Please refer to this tutorial http://cs231n.github.io/neural-networks-3/#ensemble. The "Gradient Check" section is very detailed and helpful. As is suggested by gung, I include the main points of this link: Use $\frac{f(w+h)-f(w-h)}{2h}$ approximation, where $h\sim 10^{-5}$. Monitor the fraction of $\frac{|f_a'(w)-f_n'(w)|}{max(|f_a'(w)|,|f_n'(w)|)}$, where $f'_a(w)$ is the analytical gradient and $f'_n(w)$ is the numerically approximated gradient. Usually, the preferred range of this fraction should $<10^{-2}$. Use double precision instead of float. Mind of kink(s) in activation functions, e.g., $x=0$ when one uses ReLU. When there is kink(s), one needs to monitor the values of $x-h$ and $x+h$. If these two values are on two sides of a kink, one should exclude this gradient check. Use few datapoints. Do not do gradient checking at the very beginning stage of the training process. First check model without regularization and then with it. Turn off dropout and inverted dropout when doing gradient checking. Only check randomly few dimensions.
Numeric Gradient Checking: How close is close enough? Please refer to this tutorial http://cs231n.github.io/neural-networks-3/#ensemble. The "Gradient Check" section is very detailed and helpful. As is suggested by gung, I include the main points of this
30,316
What are Gaussian Scale mixtures? And how to generate samples of Gaussian scale mixture with given scale and location parameter?
The normal (or gaussian) pdf (probability density function) is $$ \DeclareMathOperator{\E}{E} \DeclareMathOperator{\Var}{Var} f(x;\mu,\sigma^2) = \frac1{\sqrt{2\pi\sigma^2}}\cdot \exp\left(-\frac12 (\frac{x-\mu}{\sigma})^2 \right) $$ Here $\mu$ is the location parameter (mean) and $\sigma^2$ is the scale parameter (variance). A Gaussian mixture is usually when we take Gaussian distribution with different location parameters, but a scale mixture refers to the case with varying scale parameters, so is given by (a discrete mixture) $$ \sum_{i=1}^n \pi_i \cdot f(x; \mu, \sigma_i^2) $$ where the weights $\pi_i$ are non-negative and sums to 1. We can also have a continuous mixture $$ \int_0^\infty g(\sigma^2) f(x;\mu,\sigma^2) \; d\sigma^2 $$ where $g(\sigma^2)$ is a density function. One could also have mixtures where both parameters are varying. There are some Cross Validated posts about estimating mixture distributions from data, see https://stats.stackexchange.com/search?q=estimating+mixture+distributions The question about expectation and variance of the mixture distribution: In the scale mixture, all the components have the same expectation, so that will be the expectation of the mixture also. That can be seen formally by using the double expectation theorem as below. We will look at the general case, where both parameters can vary, so we can write the mixture distribution as $X | I \sim \text{N}(\mu_i, \sigma^2_i)$ where the conditioning variable $I$ have the distribution $\{ \pi_i\}$ in discrete case, $g(\cdot)$ in continuous case. In the general case, $g(\cdot)$ must be a density in both $\mu$ and $\sigma^2$, we indicate which joint/marginal we are using by the arguments. Then the expectation of the mixture becomes (since the varying variances do not contribute anything to the expectation) $$ \mu = \E X = \E [\E X|I] =\begin{cases} \sum \pi_i \mu_i &~ \text{discrete case} ~ \\ \int_{-\infty}^\infty \mu g(\mu) \; d \mu &~ \text{continuous case} ~ \end{cases} $$ For the variance we need the double variance theorem, which is $\Var X = \E \Var X|I + \Var \E X|I$, which gives: $$ \Var X = \E \Var X|I + \Var \E X|I = \sum \pi_i \sigma^2_i + \sum \pi_i (\mu_i-\mu)^2 $$ and I leave the continuous case as an exercise. So for random generation: The mixture distribution can be represented stochastically by (as above) $$ X | I=i \sim \text{N}(\mu_i, \sigma^2_i) $$ and then we must specify the distribution of $I$. For the discrete case, say $P(I=i)=\pi_i, i=1,2\dots,n$. Then the simulation follows this, but in the opposite order: We start with $I$, simulate that, and conditional on the result, we simulate $X|I=i$. For a concrete example, lets say $I$ has a Poisson distribution with parameter (mean) $\lambda=1$, and $X|I=i \sim \text{N}(\mu=i, \sigma^2=i^2)$. We can implement this in R as follows: > I <- rpois(10000,1.0) > X <- rnorm(10000,I,I) > hist(X,prob=TRUE) the histogram shown below:
What are Gaussian Scale mixtures? And how to generate samples of Gaussian scale mixture with given s
The normal (or gaussian) pdf (probability density function) is $$ \DeclareMathOperator{\E}{E} \DeclareMathOperator{\Var}{Var} f(x;\mu,\sigma^2) = \frac1{\sqrt{2\pi\sigma^2}}\cdot \exp\left(-\fra
What are Gaussian Scale mixtures? And how to generate samples of Gaussian scale mixture with given scale and location parameter? The normal (or gaussian) pdf (probability density function) is $$ \DeclareMathOperator{\E}{E} \DeclareMathOperator{\Var}{Var} f(x;\mu,\sigma^2) = \frac1{\sqrt{2\pi\sigma^2}}\cdot \exp\left(-\frac12 (\frac{x-\mu}{\sigma})^2 \right) $$ Here $\mu$ is the location parameter (mean) and $\sigma^2$ is the scale parameter (variance). A Gaussian mixture is usually when we take Gaussian distribution with different location parameters, but a scale mixture refers to the case with varying scale parameters, so is given by (a discrete mixture) $$ \sum_{i=1}^n \pi_i \cdot f(x; \mu, \sigma_i^2) $$ where the weights $\pi_i$ are non-negative and sums to 1. We can also have a continuous mixture $$ \int_0^\infty g(\sigma^2) f(x;\mu,\sigma^2) \; d\sigma^2 $$ where $g(\sigma^2)$ is a density function. One could also have mixtures where both parameters are varying. There are some Cross Validated posts about estimating mixture distributions from data, see https://stats.stackexchange.com/search?q=estimating+mixture+distributions The question about expectation and variance of the mixture distribution: In the scale mixture, all the components have the same expectation, so that will be the expectation of the mixture also. That can be seen formally by using the double expectation theorem as below. We will look at the general case, where both parameters can vary, so we can write the mixture distribution as $X | I \sim \text{N}(\mu_i, \sigma^2_i)$ where the conditioning variable $I$ have the distribution $\{ \pi_i\}$ in discrete case, $g(\cdot)$ in continuous case. In the general case, $g(\cdot)$ must be a density in both $\mu$ and $\sigma^2$, we indicate which joint/marginal we are using by the arguments. Then the expectation of the mixture becomes (since the varying variances do not contribute anything to the expectation) $$ \mu = \E X = \E [\E X|I] =\begin{cases} \sum \pi_i \mu_i &~ \text{discrete case} ~ \\ \int_{-\infty}^\infty \mu g(\mu) \; d \mu &~ \text{continuous case} ~ \end{cases} $$ For the variance we need the double variance theorem, which is $\Var X = \E \Var X|I + \Var \E X|I$, which gives: $$ \Var X = \E \Var X|I + \Var \E X|I = \sum \pi_i \sigma^2_i + \sum \pi_i (\mu_i-\mu)^2 $$ and I leave the continuous case as an exercise. So for random generation: The mixture distribution can be represented stochastically by (as above) $$ X | I=i \sim \text{N}(\mu_i, \sigma^2_i) $$ and then we must specify the distribution of $I$. For the discrete case, say $P(I=i)=\pi_i, i=1,2\dots,n$. Then the simulation follows this, but in the opposite order: We start with $I$, simulate that, and conditional on the result, we simulate $X|I=i$. For a concrete example, lets say $I$ has a Poisson distribution with parameter (mean) $\lambda=1$, and $X|I=i \sim \text{N}(\mu=i, \sigma^2=i^2)$. We can implement this in R as follows: > I <- rpois(10000,1.0) > X <- rnorm(10000,I,I) > hist(X,prob=TRUE) the histogram shown below:
What are Gaussian Scale mixtures? And how to generate samples of Gaussian scale mixture with given s The normal (or gaussian) pdf (probability density function) is $$ \DeclareMathOperator{\E}{E} \DeclareMathOperator{\Var}{Var} f(x;\mu,\sigma^2) = \frac1{\sqrt{2\pi\sigma^2}}\cdot \exp\left(-\fra
30,317
What are Gaussian Scale mixtures? And how to generate samples of Gaussian scale mixture with given scale and location parameter?
A Gaussian scale mixture (not to be confused with a mixture of gaussians) is a random variable $Y$ that can be expressed as the following mixture distribution $$ Y|(Z=z) \sim N(\mu,z^{-1}\Sigma) $$ where Z is a random variable with positive domain. For more details see these papers https://academic.oup.com/biomet/article-abstract/74/3/646/238820 https://www.jstor.org/stable/2984774 One example is when $Z\sim gamma(d/2,d/2)$, then we have the multivariate $t$ distribution with $d$ degrees of freedom. To simulate from these distributions you first simulate one observation $z$ from $Z$ and then simulate your variable from $N(\mu,z^{-1}\Sigma)$. A gaussian mixture is what kjetil b halvorsen answered
What are Gaussian Scale mixtures? And how to generate samples of Gaussian scale mixture with given s
A Gaussian scale mixture (not to be confused with a mixture of gaussians) is a random variable $Y$ that can be expressed as the following mixture distribution $$ Y|(Z=z) \sim N(\mu,z^{-1}\Sigma) $$ wh
What are Gaussian Scale mixtures? And how to generate samples of Gaussian scale mixture with given scale and location parameter? A Gaussian scale mixture (not to be confused with a mixture of gaussians) is a random variable $Y$ that can be expressed as the following mixture distribution $$ Y|(Z=z) \sim N(\mu,z^{-1}\Sigma) $$ where Z is a random variable with positive domain. For more details see these papers https://academic.oup.com/biomet/article-abstract/74/3/646/238820 https://www.jstor.org/stable/2984774 One example is when $Z\sim gamma(d/2,d/2)$, then we have the multivariate $t$ distribution with $d$ degrees of freedom. To simulate from these distributions you first simulate one observation $z$ from $Z$ and then simulate your variable from $N(\mu,z^{-1}\Sigma)$. A gaussian mixture is what kjetil b halvorsen answered
What are Gaussian Scale mixtures? And how to generate samples of Gaussian scale mixture with given s A Gaussian scale mixture (not to be confused with a mixture of gaussians) is a random variable $Y$ that can be expressed as the following mixture distribution $$ Y|(Z=z) \sim N(\mu,z^{-1}\Sigma) $$ wh
30,318
Why linear and logistic regression coefficients cannot be estimated using same method?
You're confusing apples with oranges. That's ok, because they are both delicious. Maximum likelihood estimation is about what you minimize, gradient descent is about how you minimize it. Why not MLE for linear regression? In fact, linear regression is solved with maximum likelihood estimation. The standard "minimize the sum of squared errors" method is exactly mathematically equivalent to maximum likelihood estimation using a conditional normal distribution. Why not gradient descent for logistic regression? You can totally solve logistic regression by minimizing the likelihood function using gradient descent. It's a great exercise in fact, and I'd recommend everyone do it at least once. Gradient descent is not the standard method though. That prize goes to iteratively re-weighted least squares / Newton's method, which is an enhancement to gradient descent that takes into account the second derivative as well. This method just turns out to have much better properties than gradient descent, but is trickier to understand and implement.
Why linear and logistic regression coefficients cannot be estimated using same method?
You're confusing apples with oranges. That's ok, because they are both delicious. Maximum likelihood estimation is about what you minimize, gradient descent is about how you minimize it. Why not MLE
Why linear and logistic regression coefficients cannot be estimated using same method? You're confusing apples with oranges. That's ok, because they are both delicious. Maximum likelihood estimation is about what you minimize, gradient descent is about how you minimize it. Why not MLE for linear regression? In fact, linear regression is solved with maximum likelihood estimation. The standard "minimize the sum of squared errors" method is exactly mathematically equivalent to maximum likelihood estimation using a conditional normal distribution. Why not gradient descent for logistic regression? You can totally solve logistic regression by minimizing the likelihood function using gradient descent. It's a great exercise in fact, and I'd recommend everyone do it at least once. Gradient descent is not the standard method though. That prize goes to iteratively re-weighted least squares / Newton's method, which is an enhancement to gradient descent that takes into account the second derivative as well. This method just turns out to have much better properties than gradient descent, but is trickier to understand and implement.
Why linear and logistic regression coefficients cannot be estimated using same method? You're confusing apples with oranges. That's ok, because they are both delicious. Maximum likelihood estimation is about what you minimize, gradient descent is about how you minimize it. Why not MLE
30,319
SPSS and Stata output different
The problem (amazingly) has to do with rounding the values during pasting. In Excel, most of the values were computed elsewhere and are recorded as doubles (about 16 decimal places of precision). Only % Food Insecure actually is stored to a small number of decimal places (one). None of the data columns is stored as it appears in Excel. During pasting, the receiving application typically will accept the data as they appear, not as they are actually stored! Rounding of data matters in this situation because for several variables--especially percent female and percent food insecurity--the amounts rounded off can be an appreciable fraction of the standard deviation of the data. When I read the Excel data directly in R using xlsx::read.xlsx, I reproduce the SPSS results exactly. When I round the data to integers (for % Free Lunch) and to one decimal place for the others--as they appear when pasting them into R--I get new results, but the estimated coefficients change appreciably. For instance, the intercept of $-139.616$ becomes $-133.897$. I have not been able to reproduce the Stata results in R (my summary statistics do not quite agree with those presented by Nick Cox: my mean for % Food insecure is $15.67$ instead of $15.81$), but I suspect that if I were to paste them into my copy of Stata, I would get the reported Stata results. (A big clue is the rounded values presented for the minima and maxima: in most cases these are not the minima and maxima actually recorded in the Excel file.) The differences between the two sets of results are a small fraction of a standard error, so they are--in this statistical sense--of no consequence. There is no collinearity problem: the VIFs are nice and low. Moral When you care about your data, read them directly: do not intervene manually via copy-and-paste or transcription.
SPSS and Stata output different
The problem (amazingly) has to do with rounding the values during pasting. In Excel, most of the values were computed elsewhere and are recorded as doubles (about 16 decimal places of precision). Onl
SPSS and Stata output different The problem (amazingly) has to do with rounding the values during pasting. In Excel, most of the values were computed elsewhere and are recorded as doubles (about 16 decimal places of precision). Only % Food Insecure actually is stored to a small number of decimal places (one). None of the data columns is stored as it appears in Excel. During pasting, the receiving application typically will accept the data as they appear, not as they are actually stored! Rounding of data matters in this situation because for several variables--especially percent female and percent food insecurity--the amounts rounded off can be an appreciable fraction of the standard deviation of the data. When I read the Excel data directly in R using xlsx::read.xlsx, I reproduce the SPSS results exactly. When I round the data to integers (for % Free Lunch) and to one decimal place for the others--as they appear when pasting them into R--I get new results, but the estimated coefficients change appreciably. For instance, the intercept of $-139.616$ becomes $-133.897$. I have not been able to reproduce the Stata results in R (my summary statistics do not quite agree with those presented by Nick Cox: my mean for % Food insecure is $15.67$ instead of $15.81$), but I suspect that if I were to paste them into my copy of Stata, I would get the reported Stata results. (A big clue is the rounded values presented for the minima and maxima: in most cases these are not the minima and maxima actually recorded in the Excel file.) The differences between the two sets of results are a small fraction of a standard error, so they are--in this statistical sense--of no consequence. There is no collinearity problem: the VIFs are nice and low. Moral When you care about your data, read them directly: do not intervene manually via copy-and-paste or transcription.
SPSS and Stata output different The problem (amazingly) has to do with rounding the values during pasting. In Excel, most of the values were computed elsewhere and are recorded as doubles (about 16 decimal places of precision). Onl
30,320
SPSS and Stata output different
This isn't really an answer, but there is no easy way to show output except here. This is what I got in Stata 13, after copy and paste and some renaming. There are no missing values on the variables used, so what either program might do with missing values is irrelevant here. 2/6 variables are presented as integers; 4/6 are presented with one decimal place. Note that the exact route I followed has the consequence that variables with decimal places are held as double. Other routes might produce variables of float type. Check that 36 observations (cases) are included in both regressions. Please check whether you got the same. . d percentfreelunch percentfoodinsecure rural female under18 hispanic storage display value variable name type format label variable label ----------------------------------------------------------------------------------------- percentfreelu~h byte %10.0g % Free Lunch percentfoodin~e byte %10.0g % Food Insecure rural double %10.0g Rural female double %10.0g Female under18 double %10.0g < 18 hispanic double %10.0g Hispanic . reg percentfreelunch percentfoodinsecure rural female under18 hispanic Source | SS df MS Number of obs = 36 -------------+------------------------------ F( 5, 30) = 8.27 Model | 1578.09245 5 315.61849 Prob > F = 0.0001 Residual | 1145.12977 30 38.1709925 R-squared = 0.5795 -------------+------------------------------ Adj R-squared = 0.5094 Total | 2723.22222 35 77.8063492 Root MSE = 6.1783 ------------------------------------------------------------------------------------- percentfreelunch | Coef. Std. Err. t P>|t| [95% Conf. Interval] --------------------+---------------------------------------------------------------- percentfoodinsecure | 2.76532 .6741544 4.10 0.000 1.388513 4.142127 rural | .1378976 .0495354 2.78 0.009 .0367327 .2390624 female | 2.82671 1.204272 2.35 0.026 .3672593 5.286162 under18 | -.3799895 .588423 -0.65 0.523 -1.58171 .8217307 hispanic | 1.168375 .2398765 4.87 0.000 .6784822 1.658269 _cons | -149.3857 69.08908 -2.16 0.039 -290.4845 -8.287025 ------------------------------------------------------------------------------------- EDIT: Some summary statistics from Stata . su percentfreelunch percentfoodinsecure rural female under18 hispanic, sep(0) Variable | Obs Mean Std. Dev. Min Max -------------+-------------------------------------------------------- percentfre~h | 36 46.27778 8.820791 29 72 percentfoo~e | 36 15.80556 1.785968 12 20 rural | 36 44.37222 27.25343 1.3 100 female | 36 49.95833 1.233201 45.9 51.5 under18 | 36 21.26389 3.069216 15.6 28 hispanic | 36 10.86944 8.315178 2.3 32.2
SPSS and Stata output different
This isn't really an answer, but there is no easy way to show output except here. This is what I got in Stata 13, after copy and paste and some renaming. There are no missing values on the variables
SPSS and Stata output different This isn't really an answer, but there is no easy way to show output except here. This is what I got in Stata 13, after copy and paste and some renaming. There are no missing values on the variables used, so what either program might do with missing values is irrelevant here. 2/6 variables are presented as integers; 4/6 are presented with one decimal place. Note that the exact route I followed has the consequence that variables with decimal places are held as double. Other routes might produce variables of float type. Check that 36 observations (cases) are included in both regressions. Please check whether you got the same. . d percentfreelunch percentfoodinsecure rural female under18 hispanic storage display value variable name type format label variable label ----------------------------------------------------------------------------------------- percentfreelu~h byte %10.0g % Free Lunch percentfoodin~e byte %10.0g % Food Insecure rural double %10.0g Rural female double %10.0g Female under18 double %10.0g < 18 hispanic double %10.0g Hispanic . reg percentfreelunch percentfoodinsecure rural female under18 hispanic Source | SS df MS Number of obs = 36 -------------+------------------------------ F( 5, 30) = 8.27 Model | 1578.09245 5 315.61849 Prob > F = 0.0001 Residual | 1145.12977 30 38.1709925 R-squared = 0.5795 -------------+------------------------------ Adj R-squared = 0.5094 Total | 2723.22222 35 77.8063492 Root MSE = 6.1783 ------------------------------------------------------------------------------------- percentfreelunch | Coef. Std. Err. t P>|t| [95% Conf. Interval] --------------------+---------------------------------------------------------------- percentfoodinsecure | 2.76532 .6741544 4.10 0.000 1.388513 4.142127 rural | .1378976 .0495354 2.78 0.009 .0367327 .2390624 female | 2.82671 1.204272 2.35 0.026 .3672593 5.286162 under18 | -.3799895 .588423 -0.65 0.523 -1.58171 .8217307 hispanic | 1.168375 .2398765 4.87 0.000 .6784822 1.658269 _cons | -149.3857 69.08908 -2.16 0.039 -290.4845 -8.287025 ------------------------------------------------------------------------------------- EDIT: Some summary statistics from Stata . su percentfreelunch percentfoodinsecure rural female under18 hispanic, sep(0) Variable | Obs Mean Std. Dev. Min Max -------------+-------------------------------------------------------- percentfre~h | 36 46.27778 8.820791 29 72 percentfoo~e | 36 15.80556 1.785968 12 20 rural | 36 44.37222 27.25343 1.3 100 female | 36 49.95833 1.233201 45.9 51.5 under18 | 36 21.26389 3.069216 15.6 28 hispanic | 36 10.86944 8.315178 2.3 32.2
SPSS and Stata output different This isn't really an answer, but there is no easy way to show output except here. This is what I got in Stata 13, after copy and paste and some renaming. There are no missing values on the variables
30,321
Does Boruta feature selection (in R) take into account the correlation between variables?
... , two (of the 20 variables selected) are highly correlated, and two others are completely correlated. Is this normal? Shouldn't the Boruta method have classified one of the two as unimportant? Yes it is normal. Boruta tends to find all features relevant to the response variable $y$. Rigorously speaking, a predictor variable $x_i$ is said to be relevant to $y$ if $x_i$ and $y$ are not conditionally independent given some other predictor variables (or given nothing, which would simply mean that $x_i$ and $y$ are not independent). Consider this simple example : set.seed(666) n <- 100 x1 <- rnorm(n) x2 <- x1 + rnorm(n,sd=0.5) x3 <- rnorm(n) y <- x2 + rnorm(n) You see that $y=x_2+\text{noise}$, then $x_2$ is relevant to $y$, because $y$ and $x_2$ are not independent. You also see that $x_2=x_1+\text{noise}$ and then $y$ is not independent of $x_2$. The only variable not relevant to $y$ is $x_3$, because: $y$ and $x_3$ are independent $y$ and $x_3$ are conditionally independent given $x_1$ $y$ and $x_3$ are conditionnaly independent given $(x_1,x_2)$ Then Boruta finds the expected result: > library(Boruta) > Boruta(data.frame(x1,x2,x3), y) Boruta performed 30 iterations in 2.395286 secs. 2 attributes confirmed important: x1, x2. 1 attributes confirmed unimportant: x3. There is a high correlation between $x_1$ and $x_2$, but Boruta does not mind about that: > cor(x1,x2) [1] 0.896883
Does Boruta feature selection (in R) take into account the correlation between variables?
... , two (of the 20 variables selected) are highly correlated, and two others are completely correlated. Is this normal? Shouldn't the Boruta method have classified one of the two as unimportant?
Does Boruta feature selection (in R) take into account the correlation between variables? ... , two (of the 20 variables selected) are highly correlated, and two others are completely correlated. Is this normal? Shouldn't the Boruta method have classified one of the two as unimportant? Yes it is normal. Boruta tends to find all features relevant to the response variable $y$. Rigorously speaking, a predictor variable $x_i$ is said to be relevant to $y$ if $x_i$ and $y$ are not conditionally independent given some other predictor variables (or given nothing, which would simply mean that $x_i$ and $y$ are not independent). Consider this simple example : set.seed(666) n <- 100 x1 <- rnorm(n) x2 <- x1 + rnorm(n,sd=0.5) x3 <- rnorm(n) y <- x2 + rnorm(n) You see that $y=x_2+\text{noise}$, then $x_2$ is relevant to $y$, because $y$ and $x_2$ are not independent. You also see that $x_2=x_1+\text{noise}$ and then $y$ is not independent of $x_2$. The only variable not relevant to $y$ is $x_3$, because: $y$ and $x_3$ are independent $y$ and $x_3$ are conditionally independent given $x_1$ $y$ and $x_3$ are conditionnaly independent given $(x_1,x_2)$ Then Boruta finds the expected result: > library(Boruta) > Boruta(data.frame(x1,x2,x3), y) Boruta performed 30 iterations in 2.395286 secs. 2 attributes confirmed important: x1, x2. 1 attributes confirmed unimportant: x3. There is a high correlation between $x_1$ and $x_2$, but Boruta does not mind about that: > cor(x1,x2) [1] 0.896883
Does Boruta feature selection (in R) take into account the correlation between variables? ... , two (of the 20 variables selected) are highly correlated, and two others are completely correlated. Is this normal? Shouldn't the Boruta method have classified one of the two as unimportant?
30,322
Does Boruta feature selection (in R) take into account the correlation between variables?
It lies in the nature of the algorithm. Let us assume that we have two meaningful features $X_1$ and $X_2$ that are strongly correlated. From the paper http://arxiv.org/abs/1106.5112 (The All Relevant Feature Selection using Random Forest, Miron B. Kursa, Witold R. Rudnicki) we can take a short description of the boruta algorithm: "To deal with this problem, we developed an algorithm which provides criteria for selection of important attributes. The algorithm arises from the spirit of random forest – we cope with problems by adding more randomness to the system. The essential idea is very simple: we make a randomised copy of the system, merge the copy with the original and build the classifier for this extended system. To asses importance of the variable in the original system we compare it with that of the randomised variables. Only variables for whose importance is higher than that of the randomised variables are considered important." Essentially the Boruta algorithm trains a random forest on the set of original and randomized features. This random forest during training, as every random forest, only sees a subset of all features at every node. Hence sometimes it will not have a choice between $X_1$ and $X_2$ when picking the variable for the current node and it cannot prefer one of the two variables $X_1$ and $X_2$ over the other. This is is the reason why Boruta can not classify one of the variables $X_1$ and $X_2$ as unimportant. One would have to modify the underlying random forest algorithm to always see $X_1$ and $X_2$ with their random shadow variables $\hat X_1$ and $\hat X_2$ at every node. Then the random forest could often for example select the variables $X_1$ and $\hat X_2$ which would result in Boruta selecting variable $X_1$ and rejecting $X_2$. (Here $X_2$ is rejected because $\hat X_2$ has a higher importance than $X_2$)
Does Boruta feature selection (in R) take into account the correlation between variables?
It lies in the nature of the algorithm. Let us assume that we have two meaningful features $X_1$ and $X_2$ that are strongly correlated. From the paper http://arxiv.org/abs/1106.5112 (The All Relevant
Does Boruta feature selection (in R) take into account the correlation between variables? It lies in the nature of the algorithm. Let us assume that we have two meaningful features $X_1$ and $X_2$ that are strongly correlated. From the paper http://arxiv.org/abs/1106.5112 (The All Relevant Feature Selection using Random Forest, Miron B. Kursa, Witold R. Rudnicki) we can take a short description of the boruta algorithm: "To deal with this problem, we developed an algorithm which provides criteria for selection of important attributes. The algorithm arises from the spirit of random forest – we cope with problems by adding more randomness to the system. The essential idea is very simple: we make a randomised copy of the system, merge the copy with the original and build the classifier for this extended system. To asses importance of the variable in the original system we compare it with that of the randomised variables. Only variables for whose importance is higher than that of the randomised variables are considered important." Essentially the Boruta algorithm trains a random forest on the set of original and randomized features. This random forest during training, as every random forest, only sees a subset of all features at every node. Hence sometimes it will not have a choice between $X_1$ and $X_2$ when picking the variable for the current node and it cannot prefer one of the two variables $X_1$ and $X_2$ over the other. This is is the reason why Boruta can not classify one of the variables $X_1$ and $X_2$ as unimportant. One would have to modify the underlying random forest algorithm to always see $X_1$ and $X_2$ with their random shadow variables $\hat X_1$ and $\hat X_2$ at every node. Then the random forest could often for example select the variables $X_1$ and $\hat X_2$ which would result in Boruta selecting variable $X_1$ and rejecting $X_2$. (Here $X_2$ is rejected because $\hat X_2$ has a higher importance than $X_2$)
Does Boruta feature selection (in R) take into account the correlation between variables? It lies in the nature of the algorithm. Let us assume that we have two meaningful features $X_1$ and $X_2$ that are strongly correlated. From the paper http://arxiv.org/abs/1106.5112 (The All Relevant
30,323
Does Boruta feature selection (in R) take into account the correlation between variables?
Yes it is normal. Boruta algorithm throws out attributes that have no value to the classifier, leaving the 'all-relevant' set of attributes, which may well include correlated ones. Contrast that to the 'minimal-optimal' set (which should not contain correlated). So why then, should one use this method for feature selection? You may find this quote from the original paper useful: Finding all relevant attributes, instead of only the non-redundant ones, may be very useful in itself. In particular, this is necessary when one is interested in understanding mechanisms related to the subject of interest, instead of merely building a black box predictive model. For example, when dealing with results of gene expression measurements in context of cancer, identification of all genes which are related to cancer is necessary for complete understanding of the process, whereas a minimal-optimal set of genes might be more useful as genetic markers. So if your primary goal is to understand causal links between the predictors and the outcomes, considering only the optimal set of variables may lead you astray and you need study the all-relevant set. However, if what you are seeking is an efficient model to fit, you are better off using the minimal-optimal set.
Does Boruta feature selection (in R) take into account the correlation between variables?
Yes it is normal. Boruta algorithm throws out attributes that have no value to the classifier, leaving the 'all-relevant' set of attributes, which may well include correlated ones. Contrast that to th
Does Boruta feature selection (in R) take into account the correlation between variables? Yes it is normal. Boruta algorithm throws out attributes that have no value to the classifier, leaving the 'all-relevant' set of attributes, which may well include correlated ones. Contrast that to the 'minimal-optimal' set (which should not contain correlated). So why then, should one use this method for feature selection? You may find this quote from the original paper useful: Finding all relevant attributes, instead of only the non-redundant ones, may be very useful in itself. In particular, this is necessary when one is interested in understanding mechanisms related to the subject of interest, instead of merely building a black box predictive model. For example, when dealing with results of gene expression measurements in context of cancer, identification of all genes which are related to cancer is necessary for complete understanding of the process, whereas a minimal-optimal set of genes might be more useful as genetic markers. So if your primary goal is to understand causal links between the predictors and the outcomes, considering only the optimal set of variables may lead you astray and you need study the all-relevant set. However, if what you are seeking is an efficient model to fit, you are better off using the minimal-optimal set.
Does Boruta feature selection (in R) take into account the correlation between variables? Yes it is normal. Boruta algorithm throws out attributes that have no value to the classifier, leaving the 'all-relevant' set of attributes, which may well include correlated ones. Contrast that to th
30,324
Can a sample be too large for ANOVA or a t-test?
No, a sample cannot be too large for an ANOVA or a t-test. You will almost invariably get statistically significant results because you have a great deal of power; however, this does not mean that you detect differences that are false. Indeed, regardless of how many cases you have, an effect that does not exist will not become significant. This is a common misconception. A lot of power means that you might detect differences that are almost meaningless in terms of size, however. For example, maybe you find that two races are on average of different heights, but the difference is only half a millimetre. Make sure to interpret the effect size associated with your statistical test. In this case, the p value is worth less than the effect size (as it often is)!
Can a sample be too large for ANOVA or a t-test?
No, a sample cannot be too large for an ANOVA or a t-test. You will almost invariably get statistically significant results because you have a great deal of power; however, this does not mean that you
Can a sample be too large for ANOVA or a t-test? No, a sample cannot be too large for an ANOVA or a t-test. You will almost invariably get statistically significant results because you have a great deal of power; however, this does not mean that you detect differences that are false. Indeed, regardless of how many cases you have, an effect that does not exist will not become significant. This is a common misconception. A lot of power means that you might detect differences that are almost meaningless in terms of size, however. For example, maybe you find that two races are on average of different heights, but the difference is only half a millimetre. Make sure to interpret the effect size associated with your statistical test. In this case, the p value is worth less than the effect size (as it often is)!
Can a sample be too large for ANOVA or a t-test? No, a sample cannot be too large for an ANOVA or a t-test. You will almost invariably get statistically significant results because you have a great deal of power; however, this does not mean that you
30,325
Can a sample be too large for ANOVA or a t-test?
I suggest you look at the following (all very readable and non-technical): Anderson DR, Burnham KP, Thompson WL (2000) Null hypothesis testing: Problems, prevalence, and an alternative. Journal of Wildlife Management 64: 912-923. Gigerenzer G (2004) Mindless statistics. Journal of Socio-Economics 33: 587-606. Johnson DH (1999) The Insignificance of Statistical Significance Testing. The Journal of Wildlife Management 63: 763-772.
Can a sample be too large for ANOVA or a t-test?
I suggest you look at the following (all very readable and non-technical): Anderson DR, Burnham KP, Thompson WL (2000) Null hypothesis testing: Problems, prevalence, and an alternative. Journal of Wi
Can a sample be too large for ANOVA or a t-test? I suggest you look at the following (all very readable and non-technical): Anderson DR, Burnham KP, Thompson WL (2000) Null hypothesis testing: Problems, prevalence, and an alternative. Journal of Wildlife Management 64: 912-923. Gigerenzer G (2004) Mindless statistics. Journal of Socio-Economics 33: 587-606. Johnson DH (1999) The Insignificance of Statistical Significance Testing. The Journal of Wildlife Management 63: 763-772.
Can a sample be too large for ANOVA or a t-test? I suggest you look at the following (all very readable and non-technical): Anderson DR, Burnham KP, Thompson WL (2000) Null hypothesis testing: Problems, prevalence, and an alternative. Journal of Wi
30,326
Calculating Jaccard or other association coefficient for binary data using matrix multiplication
We know that Jaccard (computed between any two columns of binary data $\bf{X}$) is $\frac{a}{a+b+c}$, while Rogers-Tanimoto is $\frac{a+d}{a+d+2(b+c)}$, where a - number of rows where both columns are 1 b - number of rows where this and not the other column is 1 c - number of rows where the other and not this column is 1 d - number of rows where both columns are 0 $a+b+c+d=n$, the number of rows in $\bf{X}$ Then we have: $\bf X'X=A$ is the square symmetric matrix of $a$ between all columns. $\bf (not X)'(not X)=D$ is the square symmetric matrix of $d$ between all columns ("not X" is converting 1->0 and 0->1 in X). So, $\frac{\bf A}{n-\bf D}$ is the square symmetric matrix of Jaccard between all columns. $\frac{\bf A+D}{\bf A+D+2(n-(A+D))}=\frac{\bf A+D}{2n-\bf A-D}$ is the square symmetric matrix of Rogers-Tanimoto between all columns. I checked numerically if these formulas give correct result. They do. Upd. You can also obtain matrices $\bf B$ and $\bf C$: $\bf B= [1]'X-A$, where "[1]" denotes matrix of ones, sized as $\bf X$. $\bf B$ is the square asymmetric matrix of $b$ between all columns; its element ij is the number of rows in $\bf X$ with 0 in column i and 1 in column j. Consequently, $\bf C=B'$. Matrix $\bf D$ can be also computed this way, of course: $n \bf -A-B-C$. Knowing matrices $\bf A, B, C, D$, you are able to calculate a matrix of any pairwise (dis)similarity coefficient invented for binary data.
Calculating Jaccard or other association coefficient for binary data using matrix multiplication
We know that Jaccard (computed between any two columns of binary data $\bf{X}$) is $\frac{a}{a+b+c}$, while Rogers-Tanimoto is $\frac{a+d}{a+d+2(b+c)}$, where a - number of rows where both columns ar
Calculating Jaccard or other association coefficient for binary data using matrix multiplication We know that Jaccard (computed between any two columns of binary data $\bf{X}$) is $\frac{a}{a+b+c}$, while Rogers-Tanimoto is $\frac{a+d}{a+d+2(b+c)}$, where a - number of rows where both columns are 1 b - number of rows where this and not the other column is 1 c - number of rows where the other and not this column is 1 d - number of rows where both columns are 0 $a+b+c+d=n$, the number of rows in $\bf{X}$ Then we have: $\bf X'X=A$ is the square symmetric matrix of $a$ between all columns. $\bf (not X)'(not X)=D$ is the square symmetric matrix of $d$ between all columns ("not X" is converting 1->0 and 0->1 in X). So, $\frac{\bf A}{n-\bf D}$ is the square symmetric matrix of Jaccard between all columns. $\frac{\bf A+D}{\bf A+D+2(n-(A+D))}=\frac{\bf A+D}{2n-\bf A-D}$ is the square symmetric matrix of Rogers-Tanimoto between all columns. I checked numerically if these formulas give correct result. They do. Upd. You can also obtain matrices $\bf B$ and $\bf C$: $\bf B= [1]'X-A$, where "[1]" denotes matrix of ones, sized as $\bf X$. $\bf B$ is the square asymmetric matrix of $b$ between all columns; its element ij is the number of rows in $\bf X$ with 0 in column i and 1 in column j. Consequently, $\bf C=B'$. Matrix $\bf D$ can be also computed this way, of course: $n \bf -A-B-C$. Knowing matrices $\bf A, B, C, D$, you are able to calculate a matrix of any pairwise (dis)similarity coefficient invented for binary data.
Calculating Jaccard or other association coefficient for binary data using matrix multiplication We know that Jaccard (computed between any two columns of binary data $\bf{X}$) is $\frac{a}{a+b+c}$, while Rogers-Tanimoto is $\frac{a+d}{a+d+2(b+c)}$, where a - number of rows where both columns ar
30,327
Calculating Jaccard or other association coefficient for binary data using matrix multiplication
The above solution is not very good if X is sparse. Because taking !X will make a dense matrix, taking huge amount of memory and computation. A better solution is to use formula Jaccard[i,j] = #common / (#i + #j - #common). With sparse matrixes you can do it as follows (note the code also works for non-sparse matrices): library(Matrix) jaccard <- function(m) { ## common values: A = tcrossprod(m) ## indexes for non-zero common values im = which(A > 0, arr.ind=TRUE) ## counts for each row b = rowSums(m) ## only non-zero values of common Aim = A[im] ## Jacard formula: #common / (#i + #j - #common) J = sparseMatrix( i = im[,1], j = im[,2], x = Aim / (b[im[,1]] + b[im[,2]] - Aim), dims = dim(A) ) return( J ) }
Calculating Jaccard or other association coefficient for binary data using matrix multiplication
The above solution is not very good if X is sparse. Because taking !X will make a dense matrix, taking huge amount of memory and computation. A better solution is to use formula Jaccard[i,j] = #common
Calculating Jaccard or other association coefficient for binary data using matrix multiplication The above solution is not very good if X is sparse. Because taking !X will make a dense matrix, taking huge amount of memory and computation. A better solution is to use formula Jaccard[i,j] = #common / (#i + #j - #common). With sparse matrixes you can do it as follows (note the code also works for non-sparse matrices): library(Matrix) jaccard <- function(m) { ## common values: A = tcrossprod(m) ## indexes for non-zero common values im = which(A > 0, arr.ind=TRUE) ## counts for each row b = rowSums(m) ## only non-zero values of common Aim = A[im] ## Jacard formula: #common / (#i + #j - #common) J = sparseMatrix( i = im[,1], j = im[,2], x = Aim / (b[im[,1]] + b[im[,2]] - Aim), dims = dim(A) ) return( J ) }
Calculating Jaccard or other association coefficient for binary data using matrix multiplication The above solution is not very good if X is sparse. Because taking !X will make a dense matrix, taking huge amount of memory and computation. A better solution is to use formula Jaccard[i,j] = #common
30,328
Calculating Jaccard or other association coefficient for binary data using matrix multiplication
This may or may not be useful to you, depending on what your needs are. Assuming that you're interested in similarity between clustering assignments: The Jaccard Similarity Coefficient or Jaccard Index can be used to calculate the similarity of two clustering assignments. Given the labelings L1 and L2, Ben-Hur, Elisseeff, and Guyon (2002) have shown that the Jaccard index can be calculated using dot-products of an intermediate matrix. The code below leverages this to quickly calculate the Jaccard Index without having to store the intermediate matrices in memory. The code is written in C++, but can be loaded into R using the sourceCpp command. /** * The Jaccard Similarity Coefficient or Jaccard Index is used to compare the * similarity/diversity of sample sets. It is defined as the size of the * intersection of the sets divided by the size of the union of the sets. Here, * it is used to determine how similar to clustering assignments are. * * INPUTS: * L1: A list. Each element of the list is a number indicating the cluster * assignment of that number. * L2: The same as L1. Must be the same length as L1. * * RETURNS: * The Jaccard Similarity Index * * SIDE-EFFECTS: * None * * COMPLEXITY: * Time: O(K^2+n), where K = number of clusters * Space: O(K^2) * * SOURCES: * Asa Ben-Hur, Andre Elisseeff, and Isabelle Guyon (2001) A stability based * method for discovering structure in clustered data. Biocomputing 2002: pp. * 6-17. */ // [[Rcpp::export]] NumericVector JaccardIndex(const NumericVector L1, const NumericVector L2){ int n = L1.size(); int K = max(L1); int overlaps[K][K]; int cluster_sizes1[K], cluster_sizes2[K]; for(int i = 0; i < K; i++){ // We can use NumericMatrix (default 0) cluster_sizes1[i] = 0; cluster_sizes2[i] = 0; for(int j = 0; j < K; j++) overlaps[i][j] = 0; } //O(n) time. O(K^2) space. Determine the size of each cluster as well as the //size of the overlaps between the clusters. for(int i = 0; i < n; i++){ cluster_sizes1[(int)L1[i] - 1]++; // -1's account for zero-based indexing cluster_sizes2[(int)L2[i] - 1]++; overlaps[(int)L1[i] - 1][(int)L2[i] - 1]++; } // O(K^2) time. O(1) space. Square the overlap values. int C1dotC2 = 0; for(int j = 0; j < K; j++){ for(int k = 0; k < K; k++){ C1dotC2 += pow(overlaps[j][k], 2); } } // O(K) time. O(1) space. Square the cluster sizes int C1dotC1 = 0, C2dotC2 = 0; for(int i = 0; i < K; i++){ C1dotC1 += pow(cluster_sizes1[i], 2); C2dotC2 += pow(cluster_sizes2[i], 2); } return NumericVector::create((double)C1dotC2/(double)(C1dotC1+C2dotC2-C1dotC2)); }
Calculating Jaccard or other association coefficient for binary data using matrix multiplication
This may or may not be useful to you, depending on what your needs are. Assuming that you're interested in similarity between clustering assignments: The Jaccard Similarity Coefficient or Jaccard Inde
Calculating Jaccard or other association coefficient for binary data using matrix multiplication This may or may not be useful to you, depending on what your needs are. Assuming that you're interested in similarity between clustering assignments: The Jaccard Similarity Coefficient or Jaccard Index can be used to calculate the similarity of two clustering assignments. Given the labelings L1 and L2, Ben-Hur, Elisseeff, and Guyon (2002) have shown that the Jaccard index can be calculated using dot-products of an intermediate matrix. The code below leverages this to quickly calculate the Jaccard Index without having to store the intermediate matrices in memory. The code is written in C++, but can be loaded into R using the sourceCpp command. /** * The Jaccard Similarity Coefficient or Jaccard Index is used to compare the * similarity/diversity of sample sets. It is defined as the size of the * intersection of the sets divided by the size of the union of the sets. Here, * it is used to determine how similar to clustering assignments are. * * INPUTS: * L1: A list. Each element of the list is a number indicating the cluster * assignment of that number. * L2: The same as L1. Must be the same length as L1. * * RETURNS: * The Jaccard Similarity Index * * SIDE-EFFECTS: * None * * COMPLEXITY: * Time: O(K^2+n), where K = number of clusters * Space: O(K^2) * * SOURCES: * Asa Ben-Hur, Andre Elisseeff, and Isabelle Guyon (2001) A stability based * method for discovering structure in clustered data. Biocomputing 2002: pp. * 6-17. */ // [[Rcpp::export]] NumericVector JaccardIndex(const NumericVector L1, const NumericVector L2){ int n = L1.size(); int K = max(L1); int overlaps[K][K]; int cluster_sizes1[K], cluster_sizes2[K]; for(int i = 0; i < K; i++){ // We can use NumericMatrix (default 0) cluster_sizes1[i] = 0; cluster_sizes2[i] = 0; for(int j = 0; j < K; j++) overlaps[i][j] = 0; } //O(n) time. O(K^2) space. Determine the size of each cluster as well as the //size of the overlaps between the clusters. for(int i = 0; i < n; i++){ cluster_sizes1[(int)L1[i] - 1]++; // -1's account for zero-based indexing cluster_sizes2[(int)L2[i] - 1]++; overlaps[(int)L1[i] - 1][(int)L2[i] - 1]++; } // O(K^2) time. O(1) space. Square the overlap values. int C1dotC2 = 0; for(int j = 0; j < K; j++){ for(int k = 0; k < K; k++){ C1dotC2 += pow(overlaps[j][k], 2); } } // O(K) time. O(1) space. Square the cluster sizes int C1dotC1 = 0, C2dotC2 = 0; for(int i = 0; i < K; i++){ C1dotC1 += pow(cluster_sizes1[i], 2); C2dotC2 += pow(cluster_sizes2[i], 2); } return NumericVector::create((double)C1dotC2/(double)(C1dotC1+C2dotC2-C1dotC2)); }
Calculating Jaccard or other association coefficient for binary data using matrix multiplication This may or may not be useful to you, depending on what your needs are. Assuming that you're interested in similarity between clustering assignments: The Jaccard Similarity Coefficient or Jaccard Inde
30,329
Generating samples from Gibbs sampling
In your simple example, once you've computed $\mathbb P(x_1=0 | x_2=1,x_3=1)=p_{0,11}$, $\mathbb P(x_1=1 |x_2=1,x_3=1)=p_{1,11}$ and $\mathbb P(x_1=2 |x_2=1,x_3=1)=p_{2,11}$, you draw $x_1=0$ with probability $p_{0,11}$, $x_1=1$ with probability $p_{1,11}$, and $x_1=2$ with probability $p_{2,11}$. You can operationalize this as Draw $U\sim U[0,1]$ If $U \le p_{0,11}$, assign $x_1=0$, and you are done. If $p_{0,11} < U \le p_{0,11} + p_{1,11}$, assign $x_1=1$, and you are done. If $ p_{0,11} + p_{1,11}<U$, assign $x_1=2$. It is easy to see that thus generated $x_1$ has the required distribution. If you drew the modal value, you will quickly get stuck in the local mode of the joint distribution, which is not what you want.
Generating samples from Gibbs sampling
In your simple example, once you've computed $\mathbb P(x_1=0 | x_2=1,x_3=1)=p_{0,11}$, $\mathbb P(x_1=1 |x_2=1,x_3=1)=p_{1,11}$ and $\mathbb P(x_1=2 |x_2=1,x_3=1)=p_{2,11}$, you draw $x_1=0$ with pro
Generating samples from Gibbs sampling In your simple example, once you've computed $\mathbb P(x_1=0 | x_2=1,x_3=1)=p_{0,11}$, $\mathbb P(x_1=1 |x_2=1,x_3=1)=p_{1,11}$ and $\mathbb P(x_1=2 |x_2=1,x_3=1)=p_{2,11}$, you draw $x_1=0$ with probability $p_{0,11}$, $x_1=1$ with probability $p_{1,11}$, and $x_1=2$ with probability $p_{2,11}$. You can operationalize this as Draw $U\sim U[0,1]$ If $U \le p_{0,11}$, assign $x_1=0$, and you are done. If $p_{0,11} < U \le p_{0,11} + p_{1,11}$, assign $x_1=1$, and you are done. If $ p_{0,11} + p_{1,11}<U$, assign $x_1=2$. It is easy to see that thus generated $x_1$ has the required distribution. If you drew the modal value, you will quickly get stuck in the local mode of the joint distribution, which is not what you want.
Generating samples from Gibbs sampling In your simple example, once you've computed $\mathbb P(x_1=0 | x_2=1,x_3=1)=p_{0,11}$, $\mathbb P(x_1=1 |x_2=1,x_3=1)=p_{1,11}$ and $\mathbb P(x_1=2 |x_2=1,x_3=1)=p_{2,11}$, you draw $x_1=0$ with pro
30,330
Generating samples from Gibbs sampling
I have posted a link to a previous great answer which is more of an intuitive nature. I am going to focus on more technical details and to provide a simple example implemented in R. Gibbs sampling is a Markov Chain Monte Carlo (MCMC) method that is used to simulate from a random vector $(X_1,...,X_n)$. Suppose that you want to obtain a simulated sample of size $N$ from this vector and denote the $j$th simulation as $(x_1^j,...,x_n^j)$. Assume also that you know the conditional distributions $X_j\vert X_1,{j-1},X_{j+1},...,X_n$ for $j=1,...,n$ and that you can simulate from them. The Gibbs sampler is defined as the following iterative algorithm Start at the initial value $(x_1^0,...,x_n^0)$. For $k=1,...,N$ obtain a simulation of each conditional $X_j^{k}\vert x_1^{k},...,x_{j-1}^k,x_{j+1}^{k-1},...,x_{n}^{k-1}$. For this step it is essential to be able to simulate from each univariate conditional for the model parameters of interest. With this algorithm you will obtain a sample $\{(x_1^j,...,x_n^j)\}$ of size $N$ from the joint distribution of $(X_1,...,X_n)$. Note that there is no need to evaluate any probability. In order to ensure that the sample is approximately independent and from the target distribution you have to ignore the first $M$ samples, for a large $M$, this is called burn-in, and also to subsample every $m$ iterations, this is called thinning. In your particular case, you have to be able to simulate from the conditional distributions of $X_1\vert X_2,X_3$; $X_2\vert X_1,X_3$; and $X_3\vert X_1,X_2$. A toy example Suppose that you want to simulate from $(X_1,X_2)$ distributed as a bivariate normal with mean $(0,0)$ and covariance matrix $\begin{bmatrix}1 & \rho\\ \rho & 1\end{bmatrix}$ with $\rho=0.5$. It is known that the conditional distributions are given by $$X_1\vert X_2 \sim \mbox{Normal}(\rho X_2,1-\rho^2),\\ X_2\vert X_1 \sim \mbox{Normal}(\rho X_1,1-\rho^2).$$ Note that these distributions are easy to simulate and then we can easily implement a Gibbs sampler. The following R code shows how to do this. N = 26000 # Total number of iterations rho = 0.5 simx = simy = vector() simx[1] = simy[1] = 0 # Initialise vectors # Gibbs sampler for(i in 2:N){ simx[i] = rnorm(1,rho*simy[i-1],sqrt(1-rho^2)) simy[i] = rnorm(1,rho*simx[i],sqrt(1-rho^2)) } # burnin and thinning burnin = 1000 thinning = 25 # Gibbs sample sim = cbind(simx[seq(from=burnin,to=N,by=thinning)],simy[seq(from=burnin,to=N,by=thinning)]) # A diagnosis tool to assess the convergence of the sampler plot(ts(sim[,1])) plot(ts(sim[,2])) # Plots of the marginals and the joint distribution hist(sim[,1]) hist(sim[,2]) plot(sim,col=1:1000) plot(sim,type="l") As you can see, there is no need for evaluating of the conditional densities or distributions. The only thing we need to do is to simulate from the corresponding conditionals. In your case you just need to simulate from the aforementioned conditionals and to conduct an analogous iterative algorithm.
Generating samples from Gibbs sampling
I have posted a link to a previous great answer which is more of an intuitive nature. I am going to focus on more technical details and to provide a simple example implemented in R. Gibbs sampling is
Generating samples from Gibbs sampling I have posted a link to a previous great answer which is more of an intuitive nature. I am going to focus on more technical details and to provide a simple example implemented in R. Gibbs sampling is a Markov Chain Monte Carlo (MCMC) method that is used to simulate from a random vector $(X_1,...,X_n)$. Suppose that you want to obtain a simulated sample of size $N$ from this vector and denote the $j$th simulation as $(x_1^j,...,x_n^j)$. Assume also that you know the conditional distributions $X_j\vert X_1,{j-1},X_{j+1},...,X_n$ for $j=1,...,n$ and that you can simulate from them. The Gibbs sampler is defined as the following iterative algorithm Start at the initial value $(x_1^0,...,x_n^0)$. For $k=1,...,N$ obtain a simulation of each conditional $X_j^{k}\vert x_1^{k},...,x_{j-1}^k,x_{j+1}^{k-1},...,x_{n}^{k-1}$. For this step it is essential to be able to simulate from each univariate conditional for the model parameters of interest. With this algorithm you will obtain a sample $\{(x_1^j,...,x_n^j)\}$ of size $N$ from the joint distribution of $(X_1,...,X_n)$. Note that there is no need to evaluate any probability. In order to ensure that the sample is approximately independent and from the target distribution you have to ignore the first $M$ samples, for a large $M$, this is called burn-in, and also to subsample every $m$ iterations, this is called thinning. In your particular case, you have to be able to simulate from the conditional distributions of $X_1\vert X_2,X_3$; $X_2\vert X_1,X_3$; and $X_3\vert X_1,X_2$. A toy example Suppose that you want to simulate from $(X_1,X_2)$ distributed as a bivariate normal with mean $(0,0)$ and covariance matrix $\begin{bmatrix}1 & \rho\\ \rho & 1\end{bmatrix}$ with $\rho=0.5$. It is known that the conditional distributions are given by $$X_1\vert X_2 \sim \mbox{Normal}(\rho X_2,1-\rho^2),\\ X_2\vert X_1 \sim \mbox{Normal}(\rho X_1,1-\rho^2).$$ Note that these distributions are easy to simulate and then we can easily implement a Gibbs sampler. The following R code shows how to do this. N = 26000 # Total number of iterations rho = 0.5 simx = simy = vector() simx[1] = simy[1] = 0 # Initialise vectors # Gibbs sampler for(i in 2:N){ simx[i] = rnorm(1,rho*simy[i-1],sqrt(1-rho^2)) simy[i] = rnorm(1,rho*simx[i],sqrt(1-rho^2)) } # burnin and thinning burnin = 1000 thinning = 25 # Gibbs sample sim = cbind(simx[seq(from=burnin,to=N,by=thinning)],simy[seq(from=burnin,to=N,by=thinning)]) # A diagnosis tool to assess the convergence of the sampler plot(ts(sim[,1])) plot(ts(sim[,2])) # Plots of the marginals and the joint distribution hist(sim[,1]) hist(sim[,2]) plot(sim,col=1:1000) plot(sim,type="l") As you can see, there is no need for evaluating of the conditional densities or distributions. The only thing we need to do is to simulate from the corresponding conditionals. In your case you just need to simulate from the aforementioned conditionals and to conduct an analogous iterative algorithm.
Generating samples from Gibbs sampling I have posted a link to a previous great answer which is more of an intuitive nature. I am going to focus on more technical details and to provide a simple example implemented in R. Gibbs sampling is
30,331
What will be the correct answer, if we modify the "Best statistics question ever"?
The apparent paradoxes (of logic or probability) can be resolved by framing the questions clearly and carefully. The following analysis is motivated by the idea of defending an answer: when a test-taker can exhibit a possible state of affairs (consistent with all available information) in which their answer indeed is correct, then it should be marked as correct. Equivalently, an answer is incorrect when no such defense exists; it is considered correct otherwise. This models the usual interactions between (benevolent, rational) graders and (rational) test-takers :-). The apparent paradox is resolved by exhibiting multiple such defenses for the second question, only one of which could apply in any instance. I will take the meaning of "random" in these questions in a conventional sense: to model a random choice of answer, I will write each answer on a slip of paper ("ticket") and put it in a box: that will be four tickets total. Drawing a ticket out of the box (after carefully and blindly shuffling the box's contents) is a physical model for a "random" choice. It motivates and justifies a corresponding probability model. Now, what does it mean to "be correct"? In my ignorance, I will explore all possibilities. In any case, I take it as definite that zero, one, or even more of the tickets may be "correct." (How might I know? I simply consult the grading sheet!) I will mark the "correct" answers as such by writing the value $1$ on each correct ticket and writing $0$ on the others. That's routine and should not be controversial. An obvious but important thing to notice is that the rule for writing $0$ or $1$ must be based solely on the answer written on each ticket: mathematically, it is a mapping (or reassignment) sending the set of listed answers ($\{.25, .50, .60\}$ in both questions) into the set $\{0,1\}$. This rule is needed for self-consistency. Let's turn to the probabilistic element of the question: by definition, the chance of being correct, under a random drawing of tickets, is the expectation of the values with which they have been marked. The expectation is computed by summing the values on the tickets and dividing that by their total number. It will therefore be either $0$, $.25$, $.50$, $.75$, or $1$. A marking will make sense provided that only the tickets whose answers equal the expectation are marked with $1$s. This also is a self-consistency requirement. I claim that this is the crux of the matter: to find and interpret the markings that make sense. If there are none, then the question itself can be branded as being meaningless. It there is a unique marking, then there will be no controversy. Only if two or more markings make sense will there be any potential difficulty. Which markings make sense? We don't even need to make an exhaustive search. In the first question, the expectations listed on the tickets are 25%, 50% and 60%. The latter is impossible with four tickets. The first would require exactly one ticket to be marked; the second, two tickets. That gives at most $3+3=6$ possible markings to explore. The only marking that makes sense puts $0$s on each ticket. For this marking, the expectation is $(0+0+0+0)/4 = 0$. That justifies the stated answer to the first question. (Arguably, the sole correct response to the first question is not to select any answer!) In the second question, the same answers appear and once again there are six markings to explore. This time, three markings are self-consistent. I tabulate them: Solution 1 Solution 2 Solution 3 Ticket Answer Mark Ticket Answer Mark Ticket Answer Mark A 50% 1 A 50% 0 A 50% 0 B 25% 0 B 25% 1 B 25% 0 C 60% 0 C 60% 0 C 60% 0 D 50% 1 D 50% 0 D 50% 0 Therefore, there are three distinct possible definitions of "correct" in the second problem, leading to either A or D being correct (in solution 1) or only B being correct (in solution 2), or none of the answers being correct (in solution 3). One way to interpret this state of affairs is that for each of the answers A, B, and D, there exists at least one way of marking the tickets that makes those answers correct. This does not imply that all three are simultaneously correct: they couldn't be, because $.25 \ne .50$. If you were the grader of the test, then if you marked any of A, B, or D correct, then you would not get an argument from the test-taker; but if you marked any of them incorrect, the test-taker would have a legitimate basis to dispute your scoring: they would invoke either solution 1 or solution 2. Indeed, if a test-taker refused to answer the question, solution 3 would give them a legitimate basis to argue that their non-response ought to get full credit, too! In summary, this analysis addresses the second part of the question by concluding that any of the following responses to question 2 should be marked correct because each of them are defensible: A, B, D, A and D, and nothing. No other response can be defended and therefore would not be correct.
What will be the correct answer, if we modify the "Best statistics question ever"?
The apparent paradoxes (of logic or probability) can be resolved by framing the questions clearly and carefully. The following analysis is motivated by the idea of defending an answer: when a test-tak
What will be the correct answer, if we modify the "Best statistics question ever"? The apparent paradoxes (of logic or probability) can be resolved by framing the questions clearly and carefully. The following analysis is motivated by the idea of defending an answer: when a test-taker can exhibit a possible state of affairs (consistent with all available information) in which their answer indeed is correct, then it should be marked as correct. Equivalently, an answer is incorrect when no such defense exists; it is considered correct otherwise. This models the usual interactions between (benevolent, rational) graders and (rational) test-takers :-). The apparent paradox is resolved by exhibiting multiple such defenses for the second question, only one of which could apply in any instance. I will take the meaning of "random" in these questions in a conventional sense: to model a random choice of answer, I will write each answer on a slip of paper ("ticket") and put it in a box: that will be four tickets total. Drawing a ticket out of the box (after carefully and blindly shuffling the box's contents) is a physical model for a "random" choice. It motivates and justifies a corresponding probability model. Now, what does it mean to "be correct"? In my ignorance, I will explore all possibilities. In any case, I take it as definite that zero, one, or even more of the tickets may be "correct." (How might I know? I simply consult the grading sheet!) I will mark the "correct" answers as such by writing the value $1$ on each correct ticket and writing $0$ on the others. That's routine and should not be controversial. An obvious but important thing to notice is that the rule for writing $0$ or $1$ must be based solely on the answer written on each ticket: mathematically, it is a mapping (or reassignment) sending the set of listed answers ($\{.25, .50, .60\}$ in both questions) into the set $\{0,1\}$. This rule is needed for self-consistency. Let's turn to the probabilistic element of the question: by definition, the chance of being correct, under a random drawing of tickets, is the expectation of the values with which they have been marked. The expectation is computed by summing the values on the tickets and dividing that by their total number. It will therefore be either $0$, $.25$, $.50$, $.75$, or $1$. A marking will make sense provided that only the tickets whose answers equal the expectation are marked with $1$s. This also is a self-consistency requirement. I claim that this is the crux of the matter: to find and interpret the markings that make sense. If there are none, then the question itself can be branded as being meaningless. It there is a unique marking, then there will be no controversy. Only if two or more markings make sense will there be any potential difficulty. Which markings make sense? We don't even need to make an exhaustive search. In the first question, the expectations listed on the tickets are 25%, 50% and 60%. The latter is impossible with four tickets. The first would require exactly one ticket to be marked; the second, two tickets. That gives at most $3+3=6$ possible markings to explore. The only marking that makes sense puts $0$s on each ticket. For this marking, the expectation is $(0+0+0+0)/4 = 0$. That justifies the stated answer to the first question. (Arguably, the sole correct response to the first question is not to select any answer!) In the second question, the same answers appear and once again there are six markings to explore. This time, three markings are self-consistent. I tabulate them: Solution 1 Solution 2 Solution 3 Ticket Answer Mark Ticket Answer Mark Ticket Answer Mark A 50% 1 A 50% 0 A 50% 0 B 25% 0 B 25% 1 B 25% 0 C 60% 0 C 60% 0 C 60% 0 D 50% 1 D 50% 0 D 50% 0 Therefore, there are three distinct possible definitions of "correct" in the second problem, leading to either A or D being correct (in solution 1) or only B being correct (in solution 2), or none of the answers being correct (in solution 3). One way to interpret this state of affairs is that for each of the answers A, B, and D, there exists at least one way of marking the tickets that makes those answers correct. This does not imply that all three are simultaneously correct: they couldn't be, because $.25 \ne .50$. If you were the grader of the test, then if you marked any of A, B, or D correct, then you would not get an argument from the test-taker; but if you marked any of them incorrect, the test-taker would have a legitimate basis to dispute your scoring: they would invoke either solution 1 or solution 2. Indeed, if a test-taker refused to answer the question, solution 3 would give them a legitimate basis to argue that their non-response ought to get full credit, too! In summary, this analysis addresses the second part of the question by concluding that any of the following responses to question 2 should be marked correct because each of them are defensible: A, B, D, A and D, and nothing. No other response can be defended and therefore would not be correct.
What will be the correct answer, if we modify the "Best statistics question ever"? The apparent paradoxes (of logic or probability) can be resolved by framing the questions clearly and carefully. The following analysis is motivated by the idea of defending an answer: when a test-tak
30,332
What will be the correct answer, if we modify the "Best statistics question ever"?
I think there is an issue of semantics here in addition to probability. Choosing at random is clear. Each of A, B, C, and D will be selected 25%. But what does it mean to be correct when you pick at random? It seems that it should mean given that you pick A does As answer give the correct % of samples that will be correct and the same for B, C, and D. So you have to count 1/4 for each correct answer and sum over all correct answers to get the correct percentage. But this leads to a circular argument. Hence the paradox. This really seems to be a question in logic rather than probability or statistics.
What will be the correct answer, if we modify the "Best statistics question ever"?
I think there is an issue of semantics here in addition to probability. Choosing at random is clear. Each of A, B, C, and D will be selected 25%. But what does it mean to be correct when you pick at
What will be the correct answer, if we modify the "Best statistics question ever"? I think there is an issue of semantics here in addition to probability. Choosing at random is clear. Each of A, B, C, and D will be selected 25%. But what does it mean to be correct when you pick at random? It seems that it should mean given that you pick A does As answer give the correct % of samples that will be correct and the same for B, C, and D. So you have to count 1/4 for each correct answer and sum over all correct answers to get the correct percentage. But this leads to a circular argument. Hence the paradox. This really seems to be a question in logic rather than probability or statistics.
What will be the correct answer, if we modify the "Best statistics question ever"? I think there is an issue of semantics here in addition to probability. Choosing at random is clear. Each of A, B, C, and D will be selected 25%. But what does it mean to be correct when you pick at
30,333
What will be the correct answer, if we modify the "Best statistics question ever"?
whuber gives a great analysis where multiple answers are allowed. However, there is also a consistent way to understand the question such that there is only a single correct answer (though we need to state this as part of the question): If you choose an answer to this question at random, what is the chance you will be correct, given that there is only a single correct answer? A) 50% B) 25% C) 60% D) 50% Again, we will define a "correct" answer as one that is rationally defensible and will follow the argument of whuber. A marking is a map from the set of answers to $\{0,1\}$ such that correct answers are sent to 1 and incorrect answers to 0. There are three possible self-consistent markings: Solution 1 Solution 2 Solution 3 Ticket Answer Mark Ticket Answer Mark Ticket Answer Mark A 50% 1 A 50% 0 A 50% 0 B 25% 0 B 25% 1 B 25% 0 C 60% 0 C 60% 0 C 60% 0 D 50% 1 D 50% 0 D 50% 0 Yet we need another logical step to narrow these down to a single defensible answer. When making this problem, the teacher was faced with three possible markings, each of which could be as equally an acceptable single answer as the others. However, as only one answer can be correct, the teacher should choose randomly between them. This assigns an equal probability to each marking so that: $1/3$ of the time the student will be right $50\%$ of the time $1/3$ of the time the student will be right $25\%$ of the time $1/3$ of the time the student will be right $0\%$ of the time This results in the expectation that the student will be right $(50+25+0)/3=25$% of the time. Thus 25% should be the correct answer and the marking for Solution 2 should be chosen. This is a self-consistent update of the teacher's prior over the three possible markings, i.e. if Solution 2 is fixed to be the correct marking 100% of the time, then 25% is still the one correct answer. Summary: If we specify that there is only a single correct answer, then that answer is 25%.
What will be the correct answer, if we modify the "Best statistics question ever"?
whuber gives a great analysis where multiple answers are allowed. However, there is also a consistent way to understand the question such that there is only a single correct answer (though we need to
What will be the correct answer, if we modify the "Best statistics question ever"? whuber gives a great analysis where multiple answers are allowed. However, there is also a consistent way to understand the question such that there is only a single correct answer (though we need to state this as part of the question): If you choose an answer to this question at random, what is the chance you will be correct, given that there is only a single correct answer? A) 50% B) 25% C) 60% D) 50% Again, we will define a "correct" answer as one that is rationally defensible and will follow the argument of whuber. A marking is a map from the set of answers to $\{0,1\}$ such that correct answers are sent to 1 and incorrect answers to 0. There are three possible self-consistent markings: Solution 1 Solution 2 Solution 3 Ticket Answer Mark Ticket Answer Mark Ticket Answer Mark A 50% 1 A 50% 0 A 50% 0 B 25% 0 B 25% 1 B 25% 0 C 60% 0 C 60% 0 C 60% 0 D 50% 1 D 50% 0 D 50% 0 Yet we need another logical step to narrow these down to a single defensible answer. When making this problem, the teacher was faced with three possible markings, each of which could be as equally an acceptable single answer as the others. However, as only one answer can be correct, the teacher should choose randomly between them. This assigns an equal probability to each marking so that: $1/3$ of the time the student will be right $50\%$ of the time $1/3$ of the time the student will be right $25\%$ of the time $1/3$ of the time the student will be right $0\%$ of the time This results in the expectation that the student will be right $(50+25+0)/3=25$% of the time. Thus 25% should be the correct answer and the marking for Solution 2 should be chosen. This is a self-consistent update of the teacher's prior over the three possible markings, i.e. if Solution 2 is fixed to be the correct marking 100% of the time, then 25% is still the one correct answer. Summary: If we specify that there is only a single correct answer, then that answer is 25%.
What will be the correct answer, if we modify the "Best statistics question ever"? whuber gives a great analysis where multiple answers are allowed. However, there is also a consistent way to understand the question such that there is only a single correct answer (though we need to
30,334
What will be the correct answer, if we modify the "Best statistics question ever"?
I believe the answer is 1/3. We don't know which answer (25%, 50%, or 60%) is correct. So, each answer, 25%, 50%, and 60% has a 1/3 chance of being correct if selected. Even though 25% appears twice, it still has a 1/3 chance of being the correct answer. It actually does not matter how many times 25% appears as an answer. If it appears 10 times along with the 50% and the 60%, the chance that it is the correct answer would still be 1/3.This assumes that one of the answers is correct. If there is a possibility of none of the answers being correct, then the answer would be 1/4. This is based on my interpretation of what the question is asking.
What will be the correct answer, if we modify the "Best statistics question ever"?
I believe the answer is 1/3. We don't know which answer (25%, 50%, or 60%) is correct. So, each answer, 25%, 50%, and 60% has a 1/3 chance of being correct if selected. Even though 25% appears twice,
What will be the correct answer, if we modify the "Best statistics question ever"? I believe the answer is 1/3. We don't know which answer (25%, 50%, or 60%) is correct. So, each answer, 25%, 50%, and 60% has a 1/3 chance of being correct if selected. Even though 25% appears twice, it still has a 1/3 chance of being the correct answer. It actually does not matter how many times 25% appears as an answer. If it appears 10 times along with the 50% and the 60%, the chance that it is the correct answer would still be 1/3.This assumes that one of the answers is correct. If there is a possibility of none of the answers being correct, then the answer would be 1/4. This is based on my interpretation of what the question is asking.
What will be the correct answer, if we modify the "Best statistics question ever"? I believe the answer is 1/3. We don't know which answer (25%, 50%, or 60%) is correct. So, each answer, 25%, 50%, and 60% has a 1/3 chance of being correct if selected. Even though 25% appears twice,
30,335
What will be the correct answer, if we modify the "Best statistics question ever"?
This multiple choice question isn't really a question. It's nonsense text which fails to communicate any meaning. In order for it to communicate meaning, the meaning of the subconcept of "a correct answer to this question" would first have to be understood - but that is impossible without first understanding the meaning of the whole question. This creates an unresolvable circular dependency. You might as well ask, "What is the probability that asdfaghauerg fhafufha?" Consider this Python function: def get_correct_answer(): correct_answer = get_correct_answer() if correct_answer == 0.25: return 0.25 if correct_answer == 0.5: return 0.5 if correct_answer == 0.6: return 0.25 return 0 One might argue that the only consistent values for the output of get_correct_answer are 0, 0.25, and 0.5, so the function must return one of those. But really the function just keeps calling itself recursively and never returns anything - which is the same thing that happens when you try to resolve this multiple choice question.
What will be the correct answer, if we modify the "Best statistics question ever"?
This multiple choice question isn't really a question. It's nonsense text which fails to communicate any meaning. In order for it to communicate meaning, the meaning of the subconcept of "a correct an
What will be the correct answer, if we modify the "Best statistics question ever"? This multiple choice question isn't really a question. It's nonsense text which fails to communicate any meaning. In order for it to communicate meaning, the meaning of the subconcept of "a correct answer to this question" would first have to be understood - but that is impossible without first understanding the meaning of the whole question. This creates an unresolvable circular dependency. You might as well ask, "What is the probability that asdfaghauerg fhafufha?" Consider this Python function: def get_correct_answer(): correct_answer = get_correct_answer() if correct_answer == 0.25: return 0.25 if correct_answer == 0.5: return 0.5 if correct_answer == 0.6: return 0.25 return 0 One might argue that the only consistent values for the output of get_correct_answer are 0, 0.25, and 0.5, so the function must return one of those. But really the function just keeps calling itself recursively and never returns anything - which is the same thing that happens when you try to resolve this multiple choice question.
What will be the correct answer, if we modify the "Best statistics question ever"? This multiple choice question isn't really a question. It's nonsense text which fails to communicate any meaning. In order for it to communicate meaning, the meaning of the subconcept of "a correct an
30,336
How do I reference a regression model's coefficient's standard errors? [closed]
Quite generally you want the vcov function which provides the complete parameter covariance matrix. To get the regular asymptotic standard errors reported by summary you can use se <- sqrt(diag(vcov(model))) btw you would want the off-diagonals of vcov(model) to get marginal effects for interaction terms: see Brambor et al. (2006). Note also packages like sandwich devoted to constructing different types of standard errors, e.g. ones 'robust' to various types of violations.
How do I reference a regression model's coefficient's standard errors? [closed]
Quite generally you want the vcov function which provides the complete parameter covariance matrix. To get the regular asymptotic standard errors reported by summary you can use se <- sqrt(diag(vcov(
How do I reference a regression model's coefficient's standard errors? [closed] Quite generally you want the vcov function which provides the complete parameter covariance matrix. To get the regular asymptotic standard errors reported by summary you can use se <- sqrt(diag(vcov(model))) btw you would want the off-diagonals of vcov(model) to get marginal effects for interaction terms: see Brambor et al. (2006). Note also packages like sandwich devoted to constructing different types of standard errors, e.g. ones 'robust' to various types of violations.
How do I reference a regression model's coefficient's standard errors? [closed] Quite generally you want the vcov function which provides the complete parameter covariance matrix. To get the regular asymptotic standard errors reported by summary you can use se <- sqrt(diag(vcov(
30,337
How do I reference a regression model's coefficient's standard errors? [closed]
To extract without performing any other calculations, while using the object$model syntax: summary(model)$coefficients["rprice2","Std. Error"]
How do I reference a regression model's coefficient's standard errors? [closed]
To extract without performing any other calculations, while using the object$model syntax: summary(model)$coefficients["rprice2","Std. Error"]
How do I reference a regression model's coefficient's standard errors? [closed] To extract without performing any other calculations, while using the object$model syntax: summary(model)$coefficients["rprice2","Std. Error"]
How do I reference a regression model's coefficient's standard errors? [closed] To extract without performing any other calculations, while using the object$model syntax: summary(model)$coefficients["rprice2","Std. Error"]
30,338
How do I reference a regression model's coefficient's standard errors? [closed]
As I understand it you want to do this in R: f <- lm(speed~dist, data=cars) coef(f) confint(f) sd = sqrt(diag(vcov(f))) cbind("2.5 %"=-sd*1.96+coef(f),"97.5 %"=sd*1.96+coef(f)) Gives: > coef(f) (Intercept) dist 8.2839056 0.1655676 > confint(f) 2.5 % 97.5 % (Intercept) 6.5258378 10.0419735 dist 0.1303926 0.2007426 > cbind("2.5 %"=-sd*1.96+coef(f),"97.5 %"=sd*1.96+coef(f)) 2.5 % 97.5 % (Intercept) 6.5701120 9.9976992 dist 0.1312784 0.1998568
How do I reference a regression model's coefficient's standard errors? [closed]
As I understand it you want to do this in R: f <- lm(speed~dist, data=cars) coef(f) confint(f) sd = sqrt(diag(vcov(f))) cbind("2.5 %"=-sd*1.96+coef(f),"97.5 %"=sd*1.96+coef(f)) Gives: > coef(f) (Inte
How do I reference a regression model's coefficient's standard errors? [closed] As I understand it you want to do this in R: f <- lm(speed~dist, data=cars) coef(f) confint(f) sd = sqrt(diag(vcov(f))) cbind("2.5 %"=-sd*1.96+coef(f),"97.5 %"=sd*1.96+coef(f)) Gives: > coef(f) (Intercept) dist 8.2839056 0.1655676 > confint(f) 2.5 % 97.5 % (Intercept) 6.5258378 10.0419735 dist 0.1303926 0.2007426 > cbind("2.5 %"=-sd*1.96+coef(f),"97.5 %"=sd*1.96+coef(f)) 2.5 % 97.5 % (Intercept) 6.5701120 9.9976992 dist 0.1312784 0.1998568
How do I reference a regression model's coefficient's standard errors? [closed] As I understand it you want to do this in R: f <- lm(speed~dist, data=cars) coef(f) confint(f) sd = sqrt(diag(vcov(f))) cbind("2.5 %"=-sd*1.96+coef(f),"97.5 %"=sd*1.96+coef(f)) Gives: > coef(f) (Inte
30,339
How do I reference a regression model's coefficient's standard errors? [closed]
To obtain a matrix with the results of the linear regression: > coef(summary(f)) To extract a specific value from the matrix: > coef(summary(f))["rprice2","Std. Error"] [1] 0.5139
How do I reference a regression model's coefficient's standard errors? [closed]
To obtain a matrix with the results of the linear regression: > coef(summary(f)) To extract a specific value from the matrix: > coef(summary(f))["rprice2","Std. Error"] [1] 0.5139
How do I reference a regression model's coefficient's standard errors? [closed] To obtain a matrix with the results of the linear regression: > coef(summary(f)) To extract a specific value from the matrix: > coef(summary(f))["rprice2","Std. Error"] [1] 0.5139
How do I reference a regression model's coefficient's standard errors? [closed] To obtain a matrix with the results of the linear regression: > coef(summary(f)) To extract a specific value from the matrix: > coef(summary(f))["rprice2","Std. Error"] [1] 0.5139
30,340
How to quickly select important variables from a very large dataset?
You could start with a simple Univariate filter, and use cross-validation to decide which variables to keep. The sbf function in the caret package for R is really useful. You can read more about it here, starting on page 19.
How to quickly select important variables from a very large dataset?
You could start with a simple Univariate filter, and use cross-validation to decide which variables to keep. The sbf function in the caret package for R is really useful. You can read more about it
How to quickly select important variables from a very large dataset? You could start with a simple Univariate filter, and use cross-validation to decide which variables to keep. The sbf function in the caret package for R is really useful. You can read more about it here, starting on page 19.
How to quickly select important variables from a very large dataset? You could start with a simple Univariate filter, and use cross-validation to decide which variables to keep. The sbf function in the caret package for R is really useful. You can read more about it
30,341
How to quickly select important variables from a very large dataset?
This sounds like a suitable problem for lasso and friends that do shrinkage and variable selection. The Elements of Statistical Learning describes lasso and elastic net for regression and, what is more relevant for this problem, logistic regression. The authors of the book have made an efficient implementation of lasso and elastic net available as an R package called glmnet. I have previously used this package for binary data analysis with data matrices of approximately 250,000 rows, though somewhat fewer columns, but actually running regressions of all columns against all other columns. If the data matrix is also sparse, the implementation can take advantage of that too, and I believe the method can actually work for the OPs full data set. Here are some comments on lasso: Lasso achieves variable selection by using a penalty function that is non-smooth (the $\ell_1$-norm), which generally results in parameter estimates with some parameters being exactly equal to 0. How many non-zero parameters that are estimated, and how much the non-zero parameters are shrunken, is determined by a tuning parameter. The efficiency of the implementation in glmnet relies heavily on the fact that for a large penalty only few parameters are different from 0. The selection of the tuning parameter is often done by cross-validation, but even without the cross-validation step the method may be able to give a good sequence of selected variables indexed by the penalty parameter. On the downside, for variable selection, is that lasso can be unstable in the selection of variables, in particular, if they are somewhat correlated. The more general elastic net penalty was invented to improve on this instability, but it does not solve the problem completely. Adaptive lasso is another idea to improve on variable selection for lasso. Stability Selection is a general method suggested by Meinshausen and Bühlmann to achieve greater stability of the selected variables with methods like lasso. It requires a number of fits to subsamples of the data set and is, as such, much more computationally demanding. A reasonable way of thinking of lasso is as a method for generating a one-dimensional set of "good" models ranging from a single-variable model to a more complicated model (not necessarily including all variables) parametrized by the penalty parameter. In contrast, univariate filters produce an selection, or ordering, of good single-variable models only. For Python there is an implementation in scikit-learn of methods such as lasso and elastic net.
How to quickly select important variables from a very large dataset?
This sounds like a suitable problem for lasso and friends that do shrinkage and variable selection. The Elements of Statistical Learning describes lasso and elastic net for regression and, what is mor
How to quickly select important variables from a very large dataset? This sounds like a suitable problem for lasso and friends that do shrinkage and variable selection. The Elements of Statistical Learning describes lasso and elastic net for regression and, what is more relevant for this problem, logistic regression. The authors of the book have made an efficient implementation of lasso and elastic net available as an R package called glmnet. I have previously used this package for binary data analysis with data matrices of approximately 250,000 rows, though somewhat fewer columns, but actually running regressions of all columns against all other columns. If the data matrix is also sparse, the implementation can take advantage of that too, and I believe the method can actually work for the OPs full data set. Here are some comments on lasso: Lasso achieves variable selection by using a penalty function that is non-smooth (the $\ell_1$-norm), which generally results in parameter estimates with some parameters being exactly equal to 0. How many non-zero parameters that are estimated, and how much the non-zero parameters are shrunken, is determined by a tuning parameter. The efficiency of the implementation in glmnet relies heavily on the fact that for a large penalty only few parameters are different from 0. The selection of the tuning parameter is often done by cross-validation, but even without the cross-validation step the method may be able to give a good sequence of selected variables indexed by the penalty parameter. On the downside, for variable selection, is that lasso can be unstable in the selection of variables, in particular, if they are somewhat correlated. The more general elastic net penalty was invented to improve on this instability, but it does not solve the problem completely. Adaptive lasso is another idea to improve on variable selection for lasso. Stability Selection is a general method suggested by Meinshausen and Bühlmann to achieve greater stability of the selected variables with methods like lasso. It requires a number of fits to subsamples of the data set and is, as such, much more computationally demanding. A reasonable way of thinking of lasso is as a method for generating a one-dimensional set of "good" models ranging from a single-variable model to a more complicated model (not necessarily including all variables) parametrized by the penalty parameter. In contrast, univariate filters produce an selection, or ordering, of good single-variable models only. For Python there is an implementation in scikit-learn of methods such as lasso and elastic net.
How to quickly select important variables from a very large dataset? This sounds like a suitable problem for lasso and friends that do shrinkage and variable selection. The Elements of Statistical Learning describes lasso and elastic net for regression and, what is mor
30,342
How to quickly select important variables from a very large dataset?
You could do a logistic regression/chi-square test of association for each variable and only retain those that have a p-value less than some value, say .2.
How to quickly select important variables from a very large dataset?
You could do a logistic regression/chi-square test of association for each variable and only retain those that have a p-value less than some value, say .2.
How to quickly select important variables from a very large dataset? You could do a logistic regression/chi-square test of association for each variable and only retain those that have a p-value less than some value, say .2.
How to quickly select important variables from a very large dataset? You could do a logistic regression/chi-square test of association for each variable and only retain those that have a p-value less than some value, say .2.
30,343
How to calculate stock volatility in %?
You're looking for the standard deviation of log returns, appropriately annualized and converted to percentage (i.e. multiplied by 100). Here is an example of computing annual vol from daily prices: library(tseries) data <- get.hist.quote('VOD.L') price <- data$Close ret <- log(lag(price)) - log(price) vol <- sd(ret) * sqrt(250) * 100 Notes: The above code should really be using prices adjusted for corporate actions (dividends, splits etc). 250 is the (approximate) number of trading days in a year.
How to calculate stock volatility in %?
You're looking for the standard deviation of log returns, appropriately annualized and converted to percentage (i.e. multiplied by 100). Here is an example of computing annual vol from daily prices: l
How to calculate stock volatility in %? You're looking for the standard deviation of log returns, appropriately annualized and converted to percentage (i.e. multiplied by 100). Here is an example of computing annual vol from daily prices: library(tseries) data <- get.hist.quote('VOD.L') price <- data$Close ret <- log(lag(price)) - log(price) vol <- sd(ret) * sqrt(250) * 100 Notes: The above code should really be using prices adjusted for corporate actions (dividends, splits etc). 250 is the (approximate) number of trading days in a year.
How to calculate stock volatility in %? You're looking for the standard deviation of log returns, appropriately annualized and converted to percentage (i.e. multiplied by 100). Here is an example of computing annual vol from daily prices: l
30,344
How to calculate stock volatility in %?
When volatility is described as a percentage, that means it's being given as a fraction of the mean. So if the standard deviation of the price is 10 and the mean is 100, then the price could be described as 10% volatile. In R terms, this would mean: vol_percent = sd(price) / mean(price) EDIT: This could also have been easily found on the Wikipedia article for volatility.
How to calculate stock volatility in %?
When volatility is described as a percentage, that means it's being given as a fraction of the mean. So if the standard deviation of the price is 10 and the mean is 100, then the price could be descri
How to calculate stock volatility in %? When volatility is described as a percentage, that means it's being given as a fraction of the mean. So if the standard deviation of the price is 10 and the mean is 100, then the price could be described as 10% volatile. In R terms, this would mean: vol_percent = sd(price) / mean(price) EDIT: This could also have been easily found on the Wikipedia article for volatility.
How to calculate stock volatility in %? When volatility is described as a percentage, that means it's being given as a fraction of the mean. So if the standard deviation of the price is 10 and the mean is 100, then the price could be descri
30,345
How to calculate stock volatility in %?
BNaul's answer is probably not the one you're looking for. If you want to calculate Black-Scholes style volatility, you need to calculate an annualized volatility of log-returns. That means, calculate the log return series $\ln(s_t/s_{t-1})$ for each $t$, take the standard deviation, and then adjust it by the square root of time to obtain the annualized figure. This volatility can be used in pricing models that require Black Scholes vol.
How to calculate stock volatility in %?
BNaul's answer is probably not the one you're looking for. If you want to calculate Black-Scholes style volatility, you need to calculate an annualized volatility of log-returns. That means, calculate
How to calculate stock volatility in %? BNaul's answer is probably not the one you're looking for. If you want to calculate Black-Scholes style volatility, you need to calculate an annualized volatility of log-returns. That means, calculate the log return series $\ln(s_t/s_{t-1})$ for each $t$, take the standard deviation, and then adjust it by the square root of time to obtain the annualized figure. This volatility can be used in pricing models that require Black Scholes vol.
How to calculate stock volatility in %? BNaul's answer is probably not the one you're looking for. If you want to calculate Black-Scholes style volatility, you need to calculate an annualized volatility of log-returns. That means, calculate
30,346
How to calculate stock volatility in %?
The stock return volatility is not observable, we can only estimate it. I'm assuming that you mean historical volatility, because there's also implied volatility which is estimated from options on stocks. There are several ways of estimating it. For instance, look at this paper "MEASURING HISTORICAL VOLATILITY". Start with the simplest method, which they call "Close-to-close", it's similar to Classical method in Bloomberg terminal ("CLV"). It's always a good idea to check your results against Bloomberg. If you have access to the terminal, then get the document describing how they do it exactly.
How to calculate stock volatility in %?
The stock return volatility is not observable, we can only estimate it. I'm assuming that you mean historical volatility, because there's also implied volatility which is estimated from options on sto
How to calculate stock volatility in %? The stock return volatility is not observable, we can only estimate it. I'm assuming that you mean historical volatility, because there's also implied volatility which is estimated from options on stocks. There are several ways of estimating it. For instance, look at this paper "MEASURING HISTORICAL VOLATILITY". Start with the simplest method, which they call "Close-to-close", it's similar to Classical method in Bloomberg terminal ("CLV"). It's always a good idea to check your results against Bloomberg. If you have access to the terminal, then get the document describing how they do it exactly.
How to calculate stock volatility in %? The stock return volatility is not observable, we can only estimate it. I'm assuming that you mean historical volatility, because there's also implied volatility which is estimated from options on sto
30,347
How to change column names in data frame in R? [closed]
Most obvious solution would be to change your code in for loop with the following: names(mydat)[c(name)] <- paste("newname",i,sep="") But you need to clarify what your variable name is. At the moment this loop will do 4 renames of the single column. In general if the names which you want to change are in vector, this is a standard subsetting procedure: names(mydat)[names(mydat)%in% names_to_be_changed] <- name_changes
How to change column names in data frame in R? [closed]
Most obvious solution would be to change your code in for loop with the following: names(mydat)[c(name)] <- paste("newname",i,sep="") But you need to clarify what your variable name is. At the mom
How to change column names in data frame in R? [closed] Most obvious solution would be to change your code in for loop with the following: names(mydat)[c(name)] <- paste("newname",i,sep="") But you need to clarify what your variable name is. At the moment this loop will do 4 renames of the single column. In general if the names which you want to change are in vector, this is a standard subsetting procedure: names(mydat)[names(mydat)%in% names_to_be_changed] <- name_changes
How to change column names in data frame in R? [closed] Most obvious solution would be to change your code in for loop with the following: names(mydat)[c(name)] <- paste("newname",i,sep="") But you need to clarify what your variable name is. At the mom
30,348
How to change column names in data frame in R? [closed]
Try using sprintf or paste, like this: names(mydat)<-sprintf("name%d",1:10) Also, note that the names(mydat)[c(name)] is a more-less a nonsense; c(name) is equivalent to writing just name and means "get the value of variable called name'; bracket will at least extract elements of names(mydat) but only if name variable holds a numeric or boolean index. If you want to replace columns called name with name1, name2, ..., nameN, use something like this: names(mydat)[names(mydat)=="name"]<-sprintf("name%d",1:sum(names(mydat)=="name")) EDIT: Well, if you just want to remove duplicated column names, there is even easier way; R has a make.names function which fixes this problem; it can be used like this: names(mydat)<-make.names(names(mydat),unique=TRUE) Even shorter, the same can be obtained only by writing: data.frame(mydat)->mydat #The magic is in check.names, but it is TRUE by default
How to change column names in data frame in R? [closed]
Try using sprintf or paste, like this: names(mydat)<-sprintf("name%d",1:10) Also, note that the names(mydat)[c(name)] is a more-less a nonsense; c(name) is equivalent to writing just name and means "
How to change column names in data frame in R? [closed] Try using sprintf or paste, like this: names(mydat)<-sprintf("name%d",1:10) Also, note that the names(mydat)[c(name)] is a more-less a nonsense; c(name) is equivalent to writing just name and means "get the value of variable called name'; bracket will at least extract elements of names(mydat) but only if name variable holds a numeric or boolean index. If you want to replace columns called name with name1, name2, ..., nameN, use something like this: names(mydat)[names(mydat)=="name"]<-sprintf("name%d",1:sum(names(mydat)=="name")) EDIT: Well, if you just want to remove duplicated column names, there is even easier way; R has a make.names function which fixes this problem; it can be used like this: names(mydat)<-make.names(names(mydat),unique=TRUE) Even shorter, the same can be obtained only by writing: data.frame(mydat)->mydat #The magic is in check.names, but it is TRUE by default
How to change column names in data frame in R? [closed] Try using sprintf or paste, like this: names(mydat)<-sprintf("name%d",1:10) Also, note that the names(mydat)[c(name)] is a more-less a nonsense; c(name) is equivalent to writing just name and means "
30,349
How to change column names in data frame in R? [closed]
I had the same problem and I solved it with this code: names(mydat) <- paste("newname", 1:ncol(mydat), sep="");
How to change column names in data frame in R? [closed]
I had the same problem and I solved it with this code: names(mydat) <- paste("newname", 1:ncol(mydat), sep="");
How to change column names in data frame in R? [closed] I had the same problem and I solved it with this code: names(mydat) <- paste("newname", 1:ncol(mydat), sep="");
How to change column names in data frame in R? [closed] I had the same problem and I solved it with this code: names(mydat) <- paste("newname", 1:ncol(mydat), sep="");
30,350
Differences between tetrachoric and Pearson correlation
My best bet is that you are facing large imbalance between your response categories, for some of your items. If you assume that your binary responses reflect individual locations on an underlying latent (i.e., continuous) trait, then correlating the two variables is ok, provided the cutoff is close to the mean of the bivariate density, as shown below (here cutoffs were set symmetrically at $(.5,.5)$, for a correlation of 0.5): In this case, Pearson correlation will underestimate the true linear relationship between the two latent traits, especially in the mid-range of the correlation metric. On the other hand, when the cutoffs are clearly asymmetrical on both continuous variables, the tetrachoric correlation will generally overestimate the true relationship. The following picture illustrates the ideal case. library(polycor) set.seed(101) n <- 500 rho <- seq(0,1,length=500) pc1 <- pc2 <- tc <- numeric(500) for (i in 1:500) { data <- rmvnorm(n, c(0, 0), matrix(c(1, rho[i], rho[i], 1), 2, 2)) x <- data[,1]; y <- data[,2] xb <- ifelse(x>=mean(x), 1, 0); yb <- ifelse(y>=mean(y), 1, 0) pc1[i] <- cor(x, y) pc2[i] <- cor(xb, yb) tc[i] <- polychor(xb, yb) } plot(pc1, pc2, cex=.6, col="red", xlab="True linear relationship", ylab="Observed correlation") lines(lowess(pc1, pc2), col="red", lwd=2) abline(0, 1, col="lightgray") points(pc1, tc, cex=.6, col="blue") lines(lowess(pc1, tc), col="blue", lwd=2) legend("topleft", c("Pearson (0/1)","Tetrachoric"), col=c(2,4), lty=1, bty="n") Now, you can play with the value of the cutoff, $\tau$, and see what happens when it is asymmetric and largely departs from the mean of the joint density of $x$ and $y$. To complement @shabbychef's response, the phi coefficient is generally used with "truly" categorical variables (no hypothesis about a continuous generating process are made) and reduces to Pearson correlation in this case ($\sqrt{\chi^2}/n$). The problem is then to factor out a correlation matrix constructed in such a way because communalities become meaningless. To avoid this problem, we may rely on parametric item response modeling, e.g. mixed-effects logistic model (in this case, no need to worry about the cutoff, since it is estimated), or non-parametric model, like Mokken scaling. In the latest case, we only assume monotonicity on the latent trait, but no functional form relating one's location on the latent trait and the outcome (i.e., the probability of endorsing the item). However, in your case, it would be a pain and would not allow you to identify a structure in your correlation matrix. But it may be used afterwards. Finally, John Uebersax provides an in-depth discussion on the use of tetrachoric correlation in relation to latent trait modeling, see Introduction to the Tetrachoric and Polychoric Correlation Coefficients. Also, Nunnally discussed a long ago the advantages/disadvantages of relying on Pearson vs. Tetrachoric correlation coefficients in Factor Analysis, see e.g. pp. 570-573 (3rd ed.). References O'Connor, B. Cautions Regarding Item-Level Factor Analyses. Bernstein, I.H., Teng, G. (1989). Factoring items and factoring scales are different: Spurious evidence for multidimensionality due to item categorization. Psychological Bulletin, 105, 467-477. Edwards, J.H. and Edwards, A.W.F. (1984). Approximating the tetrachoric correlation coefficient. Biometrics, 40, 563. Castellan, N.J. (1966). On the estimation of the tetrachoric correlation coefficient. Psychometrika, 31(1), 67-73. Fitzgerald, P., Knuiman, M.W., Divitini, M.L., and Bartholomew, H.C. (1999). Effect of dichotomising a continuous variable on the assessment of familial aggregation: an empirical study using body mass index data from the Busselton Health Study. J. Epidemiol. Biostat., 4(4), 321-327. Nunnally, J.C. and Bernstein, I.H. (1994). Psychometric Theory (Third ed.). McGraw-Hill.
Differences between tetrachoric and Pearson correlation
My best bet is that you are facing large imbalance between your response categories, for some of your items. If you assume that your binary responses reflect individual locations on an underlying late
Differences between tetrachoric and Pearson correlation My best bet is that you are facing large imbalance between your response categories, for some of your items. If you assume that your binary responses reflect individual locations on an underlying latent (i.e., continuous) trait, then correlating the two variables is ok, provided the cutoff is close to the mean of the bivariate density, as shown below (here cutoffs were set symmetrically at $(.5,.5)$, for a correlation of 0.5): In this case, Pearson correlation will underestimate the true linear relationship between the two latent traits, especially in the mid-range of the correlation metric. On the other hand, when the cutoffs are clearly asymmetrical on both continuous variables, the tetrachoric correlation will generally overestimate the true relationship. The following picture illustrates the ideal case. library(polycor) set.seed(101) n <- 500 rho <- seq(0,1,length=500) pc1 <- pc2 <- tc <- numeric(500) for (i in 1:500) { data <- rmvnorm(n, c(0, 0), matrix(c(1, rho[i], rho[i], 1), 2, 2)) x <- data[,1]; y <- data[,2] xb <- ifelse(x>=mean(x), 1, 0); yb <- ifelse(y>=mean(y), 1, 0) pc1[i] <- cor(x, y) pc2[i] <- cor(xb, yb) tc[i] <- polychor(xb, yb) } plot(pc1, pc2, cex=.6, col="red", xlab="True linear relationship", ylab="Observed correlation") lines(lowess(pc1, pc2), col="red", lwd=2) abline(0, 1, col="lightgray") points(pc1, tc, cex=.6, col="blue") lines(lowess(pc1, tc), col="blue", lwd=2) legend("topleft", c("Pearson (0/1)","Tetrachoric"), col=c(2,4), lty=1, bty="n") Now, you can play with the value of the cutoff, $\tau$, and see what happens when it is asymmetric and largely departs from the mean of the joint density of $x$ and $y$. To complement @shabbychef's response, the phi coefficient is generally used with "truly" categorical variables (no hypothesis about a continuous generating process are made) and reduces to Pearson correlation in this case ($\sqrt{\chi^2}/n$). The problem is then to factor out a correlation matrix constructed in such a way because communalities become meaningless. To avoid this problem, we may rely on parametric item response modeling, e.g. mixed-effects logistic model (in this case, no need to worry about the cutoff, since it is estimated), or non-parametric model, like Mokken scaling. In the latest case, we only assume monotonicity on the latent trait, but no functional form relating one's location on the latent trait and the outcome (i.e., the probability of endorsing the item). However, in your case, it would be a pain and would not allow you to identify a structure in your correlation matrix. But it may be used afterwards. Finally, John Uebersax provides an in-depth discussion on the use of tetrachoric correlation in relation to latent trait modeling, see Introduction to the Tetrachoric and Polychoric Correlation Coefficients. Also, Nunnally discussed a long ago the advantages/disadvantages of relying on Pearson vs. Tetrachoric correlation coefficients in Factor Analysis, see e.g. pp. 570-573 (3rd ed.). References O'Connor, B. Cautions Regarding Item-Level Factor Analyses. Bernstein, I.H., Teng, G. (1989). Factoring items and factoring scales are different: Spurious evidence for multidimensionality due to item categorization. Psychological Bulletin, 105, 467-477. Edwards, J.H. and Edwards, A.W.F. (1984). Approximating the tetrachoric correlation coefficient. Biometrics, 40, 563. Castellan, N.J. (1966). On the estimation of the tetrachoric correlation coefficient. Psychometrika, 31(1), 67-73. Fitzgerald, P., Knuiman, M.W., Divitini, M.L., and Bartholomew, H.C. (1999). Effect of dichotomising a continuous variable on the assessment of familial aggregation: an empirical study using body mass index data from the Busselton Health Study. J. Epidemiol. Biostat., 4(4), 321-327. Nunnally, J.C. and Bernstein, I.H. (1994). Psychometric Theory (Third ed.). McGraw-Hill.
Differences between tetrachoric and Pearson correlation My best bet is that you are facing large imbalance between your response categories, for some of your items. If you assume that your binary responses reflect individual locations on an underlying late
30,351
Differences between tetrachoric and Pearson correlation
Tetrachoric coefficient and Phi coefficient are indeed different. The tetrachoric coefficient is suitable for the following problem: Suppose there are two judges who judge cakes, say, on some continuous scale, then based on a fixed, perhaps unknown, cutoff, pronounce the cakes as "bad" or "good". Suppose the latent continuous metric of the two judges has correlation coefficient $\rho$. Now generate 300 cakes, have both judges taste each of them, and generate a 2x2 contingency table of "judge 1 bad/good" vs "judge 2 bad/good". Based on the data in this contingency table, the sample tetrachoric coefficient is an estimator (I believe it is the MLE, in fact), of the 'latent' correlation $\rho$. Note that the cutoffs employed by the two judges need not be known. The Phi coefficient views the pronouncements "bad", "good" themselves as the variable of interest, coded as 0/1, and is the sample Pearson coefficient of the 0/1 data. These are not the same. edit in response to @pbneau's comments: my suspicion was that the tetrachoic and phi coefficients would diverge in the limit cases: as $\rho \to 0$ and as the cutoffs for the latent rating move away from the mean ratings. I tested this with my own code (in Matlab) for tetrachoric and phi coefficient. I tested with zero mean, unit variance Gaussian latent ratings with population correlations of 0.01 and 0.25, and with cutoffs of 0,0 and 1.5,-0.5. I ran 2048 experiments, each with 2048 'cakes'. The scatter fits for tetrachoric versus phi are shown here: (looks like the image upload thing is not working; top row is $c1 = c2 = 0$, bottom is $c1 = 1.5, c2 = -0.5$, left column is $\rho = 0.01,$ right column is $\rho = 0.25$. The best fits along top row are $\rho^* = 1.5 \phi + 0$, $\rho^* = 1.4 \phi + 0.01$, along the bottom row, $\rho^* = 2.2 \phi$ and $\rho^* = 3.1 \phi - 0.04$. perhaps I can get this image hosted somewhere else that doesn't squash them so much...) I'm not sure you can read the text on these (the preview looks bad); the upshot is that when the cutoffs are at the population mean, and thus the contingency tables are 'balanced' row-wise and col-wise (top row of plots), you get good correlation between the two metrics, but the tetrachoric tends to be a bit larger than phi. When the cutoffs are somewhat imbalanced, you get slightly worse correlation between the metrics, and the phi appears to 'shink' towards zero. Thus my initial intuition was only half correct: the worst case appears to be as the latent $\rho$ moves away from zero, and the cutoffs move away from the latent means.
Differences between tetrachoric and Pearson correlation
Tetrachoric coefficient and Phi coefficient are indeed different. The tetrachoric coefficient is suitable for the following problem: Suppose there are two judges who judge cakes, say, on some continuo
Differences between tetrachoric and Pearson correlation Tetrachoric coefficient and Phi coefficient are indeed different. The tetrachoric coefficient is suitable for the following problem: Suppose there are two judges who judge cakes, say, on some continuous scale, then based on a fixed, perhaps unknown, cutoff, pronounce the cakes as "bad" or "good". Suppose the latent continuous metric of the two judges has correlation coefficient $\rho$. Now generate 300 cakes, have both judges taste each of them, and generate a 2x2 contingency table of "judge 1 bad/good" vs "judge 2 bad/good". Based on the data in this contingency table, the sample tetrachoric coefficient is an estimator (I believe it is the MLE, in fact), of the 'latent' correlation $\rho$. Note that the cutoffs employed by the two judges need not be known. The Phi coefficient views the pronouncements "bad", "good" themselves as the variable of interest, coded as 0/1, and is the sample Pearson coefficient of the 0/1 data. These are not the same. edit in response to @pbneau's comments: my suspicion was that the tetrachoic and phi coefficients would diverge in the limit cases: as $\rho \to 0$ and as the cutoffs for the latent rating move away from the mean ratings. I tested this with my own code (in Matlab) for tetrachoric and phi coefficient. I tested with zero mean, unit variance Gaussian latent ratings with population correlations of 0.01 and 0.25, and with cutoffs of 0,0 and 1.5,-0.5. I ran 2048 experiments, each with 2048 'cakes'. The scatter fits for tetrachoric versus phi are shown here: (looks like the image upload thing is not working; top row is $c1 = c2 = 0$, bottom is $c1 = 1.5, c2 = -0.5$, left column is $\rho = 0.01,$ right column is $\rho = 0.25$. The best fits along top row are $\rho^* = 1.5 \phi + 0$, $\rho^* = 1.4 \phi + 0.01$, along the bottom row, $\rho^* = 2.2 \phi$ and $\rho^* = 3.1 \phi - 0.04$. perhaps I can get this image hosted somewhere else that doesn't squash them so much...) I'm not sure you can read the text on these (the preview looks bad); the upshot is that when the cutoffs are at the population mean, and thus the contingency tables are 'balanced' row-wise and col-wise (top row of plots), you get good correlation between the two metrics, but the tetrachoric tends to be a bit larger than phi. When the cutoffs are somewhat imbalanced, you get slightly worse correlation between the metrics, and the phi appears to 'shink' towards zero. Thus my initial intuition was only half correct: the worst case appears to be as the latent $\rho$ moves away from zero, and the cutoffs move away from the latent means.
Differences between tetrachoric and Pearson correlation Tetrachoric coefficient and Phi coefficient are indeed different. The tetrachoric coefficient is suitable for the following problem: Suppose there are two judges who judge cakes, say, on some continuo
30,352
Differences between tetrachoric and Pearson correlation
Well I think it has been widely adressed before as the PEARSON-YULE debate The discrepancy between both measures seems to come from the fact that one assumes an underlying discrete random variable whereas for the other, the underlying (latent trait) is continuous. Apparently a bijective relationship between both exist according to Ekkstrom (2008). It's not an easy task for me to develop the whole think, Ekstrom paper does this in a clear way. Ekstrom's paper http://statistics.ucla.edu/preprints/uclastat-preprint-2008:40
Differences between tetrachoric and Pearson correlation
Well I think it has been widely adressed before as the PEARSON-YULE debate The discrepancy between both measures seems to come from the fact that one assumes an underlying discrete random variable w
Differences between tetrachoric and Pearson correlation Well I think it has been widely adressed before as the PEARSON-YULE debate The discrepancy between both measures seems to come from the fact that one assumes an underlying discrete random variable whereas for the other, the underlying (latent trait) is continuous. Apparently a bijective relationship between both exist according to Ekkstrom (2008). It's not an easy task for me to develop the whole think, Ekstrom paper does this in a clear way. Ekstrom's paper http://statistics.ucla.edu/preprints/uclastat-preprint-2008:40
Differences between tetrachoric and Pearson correlation Well I think it has been widely adressed before as the PEARSON-YULE debate The discrepancy between both measures seems to come from the fact that one assumes an underlying discrete random variable w
30,353
Why are Shapiro-Wilk and Kolmogorov-Smirnov test compared with same sample size?
The main difference between the S-W and the K-S test for normality is that the S-W can be used to assess the goodness of fit to a fitted distribution, whereas the K-S test is only valid to test against a prespecified distribution. So if you estimate the parameters of your distribution from your data, then test the goodness of fit of your data against the distribution with the estimated mean and variance, you can't use the K-S any more - it will have a too optimistic view of the goodness of fit. In this situation, use the S-W test. (Normalizing your data with a mean and variance estimated from the data is the same thing in this context.) If, conversely, you know the precise distribution your data should be coming from (e.g., an N(5,1) distribution), you can use K-S. Thus, the rationale for using one test over another does not hang on the sample size, at least as long as the distinction above is not kept in mind. Once this is kept in mind, you can start looking at power against specific alternatives. There is a lot of statistical misinformation floating around the internet. (Incidentally, there is much less necessity for testing normality than is commonly assumed, see the replies to this chat message:. How to cope with non-normal ANOVA residuals? Assumptions of linear models and what to do if the residuals are not normally distributed Analysis of variance with not normally distributed residuals : how important is normality? ) Edit: John Madden asks a very interesting question: Wouldn't large sample sizes allow for hand-waving away the fact that parameters had to be estimated by standard arguments (i.e. continuous mapping theorem?), and perhaps this is where the idea that KS is more appropriate for large samples comes from? Let's take a look. We will simulate $x_1, \dots, x_n\sim N(0,1)$, for increasing sample sizes $n$. For this vector $x$, we perform a Kolmogorov-Smirnov test against a normal distribution with mean and standard deviation equal to the mean and standard deviation of $x$, and store the $p$ value. For each $n$, we do this simulation exercise 10,000 times and plot the $p$ values in a histogram. If the K-S test were valid, this histogram would be uniform, and if John's question had a positive answer, the histograms would become more uniform as $n$ increases. So we run the exercise for $n\in\{10,100,1000,10000\}$. The histograms don't get any more uniform, so no, the K-S-test against estimated parameters does not get better for large sample sizes: R code: exponents <- 1:4 par(mfrow=c(2,2),mai=c(.5,.1,.5,.1)) for ( ee in exponents ) { p_values <- rep(NA,1e4) for ( ii in seq_along(p_values) ) { sims <- rnorm(10^ee) p_values[ii] <- ks.test(sims,pnorm,mean=mean(sims),sd=sd(sims))$p.value } hist(p_values,xlab="",yaxt="n", main=paste("Histogram of p values\nSample size:",10^ee)) } (It turns out that whuber already did this analysis almost a year ago.) As various commenters point out completely correctly, there are different ways of addressing this property of the K-S test, like the Lilliefors modification, or bootstrapping the test statistic obtained with estimated parameters.
Why are Shapiro-Wilk and Kolmogorov-Smirnov test compared with same sample size?
The main difference between the S-W and the K-S test for normality is that the S-W can be used to assess the goodness of fit to a fitted distribution, whereas the K-S test is only valid to test agains
Why are Shapiro-Wilk and Kolmogorov-Smirnov test compared with same sample size? The main difference between the S-W and the K-S test for normality is that the S-W can be used to assess the goodness of fit to a fitted distribution, whereas the K-S test is only valid to test against a prespecified distribution. So if you estimate the parameters of your distribution from your data, then test the goodness of fit of your data against the distribution with the estimated mean and variance, you can't use the K-S any more - it will have a too optimistic view of the goodness of fit. In this situation, use the S-W test. (Normalizing your data with a mean and variance estimated from the data is the same thing in this context.) If, conversely, you know the precise distribution your data should be coming from (e.g., an N(5,1) distribution), you can use K-S. Thus, the rationale for using one test over another does not hang on the sample size, at least as long as the distinction above is not kept in mind. Once this is kept in mind, you can start looking at power against specific alternatives. There is a lot of statistical misinformation floating around the internet. (Incidentally, there is much less necessity for testing normality than is commonly assumed, see the replies to this chat message:. How to cope with non-normal ANOVA residuals? Assumptions of linear models and what to do if the residuals are not normally distributed Analysis of variance with not normally distributed residuals : how important is normality? ) Edit: John Madden asks a very interesting question: Wouldn't large sample sizes allow for hand-waving away the fact that parameters had to be estimated by standard arguments (i.e. continuous mapping theorem?), and perhaps this is where the idea that KS is more appropriate for large samples comes from? Let's take a look. We will simulate $x_1, \dots, x_n\sim N(0,1)$, for increasing sample sizes $n$. For this vector $x$, we perform a Kolmogorov-Smirnov test against a normal distribution with mean and standard deviation equal to the mean and standard deviation of $x$, and store the $p$ value. For each $n$, we do this simulation exercise 10,000 times and plot the $p$ values in a histogram. If the K-S test were valid, this histogram would be uniform, and if John's question had a positive answer, the histograms would become more uniform as $n$ increases. So we run the exercise for $n\in\{10,100,1000,10000\}$. The histograms don't get any more uniform, so no, the K-S-test against estimated parameters does not get better for large sample sizes: R code: exponents <- 1:4 par(mfrow=c(2,2),mai=c(.5,.1,.5,.1)) for ( ee in exponents ) { p_values <- rep(NA,1e4) for ( ii in seq_along(p_values) ) { sims <- rnorm(10^ee) p_values[ii] <- ks.test(sims,pnorm,mean=mean(sims),sd=sd(sims))$p.value } hist(p_values,xlab="",yaxt="n", main=paste("Histogram of p values\nSample size:",10^ee)) } (It turns out that whuber already did this analysis almost a year ago.) As various commenters point out completely correctly, there are different ways of addressing this property of the K-S test, like the Lilliefors modification, or bootstrapping the test statistic obtained with estimated parameters.
Why are Shapiro-Wilk and Kolmogorov-Smirnov test compared with same sample size? The main difference between the S-W and the K-S test for normality is that the S-W can be used to assess the goodness of fit to a fitted distribution, whereas the K-S test is only valid to test agains
30,354
Why are Shapiro-Wilk and Kolmogorov-Smirnov test compared with same sample size?
I presume that by the Kolmogorov-Smirnov they actually mean the Lilliefors test -- the estimated-parameter version for the normal case that was tabulated by Lilliefors; he did tables for the exponential as well. This (calling Lilliefors' modification for estimated parameters "Kolmogorov-Smirnov") seems to come mostly from SPSS; many authors follow its lead. This has been the cause of many confusions. The Lilliefors can be compared to the Shapiro Wilk, since they're both tests of normality with unspecified parameters. Which one is preferable depends on which alternatives you seek power against (and, occasionally, sample size can make some difference). Often in the sorts of situations people tend to consider in power comparisons - but not always - the Shapiro-Wilk will come out with higher power. In some such cases the Lilliefors has better power, though. The Shapiro–Wilk test is more appropriate method for small sample sizes (<50 samples) although it can also be handling on larger sample size while Kolmogorov–Smirnov test is used for n ≥50. For both of the above tests, null hypothesis states that data are taken from normal distributed population. This is poor advice; you can find it in many places, but it stems from the simple fact that Shapiro and Wilk themselves only produced tables to $n=50$, over half a century ago, as if nobody had done any work on it since. Naturally, that is not the case. Computer functions that will work for much, much larger $n$ have been available for decades. The version of the test that is implemented in R goes out to $n=5000$, using Patrick Royston's algorithms from papers published in 1982 and 1995. The usual advice when you go beyond the end of available Shapiro-Wilk functionality is to use a Shapiro-Francia test. There's nothing that happens at $n=50$ for a wide variety of alternatives that would change the considerations of which test you might use. If you were in some situation where the Shapiro-Wilk is the better test at $n=45$, it's (nearly always) going to be the better option at $n=55$ and $n=75$ as well. It's important to be aware that there are dozens of tests that could be used besides these two, and if broad power against likely alternatives of interest is what you care about, I would tend to avoid both these tests as there are other tests that do typically better in most of the situations these do well at (among the situations that people tend to worry about). If you like the Shapiro-Wilk, why not Chen-Shapiro? If you like ECDF-related tests, why not the version of the Anderson-Darling adjusted for parameter estimation? There are many other possibilities besides. I will add my support for Nick Cox's comments above. Graphical methods come closer to addressing relevant considerations if you're worried about whether the normality assumption for some test should be of concern (at least if you're in a situation where avoiding letting the data choose the hypothesis is impossible to avoid, which would be fairly rare).
Why are Shapiro-Wilk and Kolmogorov-Smirnov test compared with same sample size?
I presume that by the Kolmogorov-Smirnov they actually mean the Lilliefors test -- the estimated-parameter version for the normal case that was tabulated by Lilliefors; he did tables for the exponenti
Why are Shapiro-Wilk and Kolmogorov-Smirnov test compared with same sample size? I presume that by the Kolmogorov-Smirnov they actually mean the Lilliefors test -- the estimated-parameter version for the normal case that was tabulated by Lilliefors; he did tables for the exponential as well. This (calling Lilliefors' modification for estimated parameters "Kolmogorov-Smirnov") seems to come mostly from SPSS; many authors follow its lead. This has been the cause of many confusions. The Lilliefors can be compared to the Shapiro Wilk, since they're both tests of normality with unspecified parameters. Which one is preferable depends on which alternatives you seek power against (and, occasionally, sample size can make some difference). Often in the sorts of situations people tend to consider in power comparisons - but not always - the Shapiro-Wilk will come out with higher power. In some such cases the Lilliefors has better power, though. The Shapiro–Wilk test is more appropriate method for small sample sizes (<50 samples) although it can also be handling on larger sample size while Kolmogorov–Smirnov test is used for n ≥50. For both of the above tests, null hypothesis states that data are taken from normal distributed population. This is poor advice; you can find it in many places, but it stems from the simple fact that Shapiro and Wilk themselves only produced tables to $n=50$, over half a century ago, as if nobody had done any work on it since. Naturally, that is not the case. Computer functions that will work for much, much larger $n$ have been available for decades. The version of the test that is implemented in R goes out to $n=5000$, using Patrick Royston's algorithms from papers published in 1982 and 1995. The usual advice when you go beyond the end of available Shapiro-Wilk functionality is to use a Shapiro-Francia test. There's nothing that happens at $n=50$ for a wide variety of alternatives that would change the considerations of which test you might use. If you were in some situation where the Shapiro-Wilk is the better test at $n=45$, it's (nearly always) going to be the better option at $n=55$ and $n=75$ as well. It's important to be aware that there are dozens of tests that could be used besides these two, and if broad power against likely alternatives of interest is what you care about, I would tend to avoid both these tests as there are other tests that do typically better in most of the situations these do well at (among the situations that people tend to worry about). If you like the Shapiro-Wilk, why not Chen-Shapiro? If you like ECDF-related tests, why not the version of the Anderson-Darling adjusted for parameter estimation? There are many other possibilities besides. I will add my support for Nick Cox's comments above. Graphical methods come closer to addressing relevant considerations if you're worried about whether the normality assumption for some test should be of concern (at least if you're in a situation where avoiding letting the data choose the hypothesis is impossible to avoid, which would be fairly rare).
Why are Shapiro-Wilk and Kolmogorov-Smirnov test compared with same sample size? I presume that by the Kolmogorov-Smirnov they actually mean the Lilliefors test -- the estimated-parameter version for the normal case that was tabulated by Lilliefors; he did tables for the exponenti
30,355
Is it wrong to say that a Riemann sum is an unbiased estimate of an integral?
It seems that you are swapping two different concepts here. The concepts are unbiased and consistent, which are properties of an estimator. A sequence of estimators $(T_n)_{n=1}^\infty$ is said to be unbiased for a quantity $\theta$ if, for all $n\,\in\mathbb{N}$, $$ E[T_n] = \theta \quad.$$ It is said to be consistent if it converges in probability to $\theta$. These are different concepts: the first says that, for every finite sample size, the average of your estimator is $\theta$. The other states that, as the sample sizes grow, the estimator getting arbitrarily close to $\theta$ with increasing probability. Let $I = \int_a^bf(x)dx$ be your quantity of interest (assume it exists). What the most basic Monte Carlo method does is to observe that $$I = \int_a^bf(x)dx = (b-a)\int_a^bf(x)\frac{1}{b-a}dx = (b-a)E[f(X)] \quad.$$ In the last line, we wrote the integral as being the expectation of $f(X)$, where $X$ has a uniform distribution in $(a,b)$. Hence, if we sample i.i.d. random variables $(X_i)_{i=1}^n$ with $X_1 \sim U((a,b))$, then the estimator $$T_n = \frac{(b-a)}{n}\sum_{i=1}^nf(X_i) \quad,$$ is easily shown to be unbiased for $I$. When you think of Riemann sums, it is usual to take a deterministic partition. If it is deterministic, then the expected value for any fixed sample size is the value of the summation it self, which in general is not the value of the integral.
Is it wrong to say that a Riemann sum is an unbiased estimate of an integral?
It seems that you are swapping two different concepts here. The concepts are unbiased and consistent, which are properties of an estimator. A sequence of estimators $(T_n)_{n=1}^\infty$ is said to be
Is it wrong to say that a Riemann sum is an unbiased estimate of an integral? It seems that you are swapping two different concepts here. The concepts are unbiased and consistent, which are properties of an estimator. A sequence of estimators $(T_n)_{n=1}^\infty$ is said to be unbiased for a quantity $\theta$ if, for all $n\,\in\mathbb{N}$, $$ E[T_n] = \theta \quad.$$ It is said to be consistent if it converges in probability to $\theta$. These are different concepts: the first says that, for every finite sample size, the average of your estimator is $\theta$. The other states that, as the sample sizes grow, the estimator getting arbitrarily close to $\theta$ with increasing probability. Let $I = \int_a^bf(x)dx$ be your quantity of interest (assume it exists). What the most basic Monte Carlo method does is to observe that $$I = \int_a^bf(x)dx = (b-a)\int_a^bf(x)\frac{1}{b-a}dx = (b-a)E[f(X)] \quad.$$ In the last line, we wrote the integral as being the expectation of $f(X)$, where $X$ has a uniform distribution in $(a,b)$. Hence, if we sample i.i.d. random variables $(X_i)_{i=1}^n$ with $X_1 \sim U((a,b))$, then the estimator $$T_n = \frac{(b-a)}{n}\sum_{i=1}^nf(X_i) \quad,$$ is easily shown to be unbiased for $I$. When you think of Riemann sums, it is usual to take a deterministic partition. If it is deterministic, then the expected value for any fixed sample size is the value of the summation it self, which in general is not the value of the integral.
Is it wrong to say that a Riemann sum is an unbiased estimate of an integral? It seems that you are swapping two different concepts here. The concepts are unbiased and consistent, which are properties of an estimator. A sequence of estimators $(T_n)_{n=1}^\infty$ is said to be
30,356
Is it wrong to say that a Riemann sum is an unbiased estimate of an integral?
Any constant is a biased estimator of any different constant Since you are using a deterministic procedure here, your Riemann sum depends only on $n$, so it is a sequence of constants. Applying the concept of statistical bias to constants is simple --- any constant is a biased estimator of any different constant and an unbiased estimator of itself. So, for example, $3$ is a biased estimator of $2$, but it is an unbiased estimator of $3$. Your Riemann sum is generally going to be a biased estimator for the corresponding integral because you are selecting the points $t_k^*$ deterministically within the interval and so your estimator is a constant. There are exceptions, for functions where the Riemann sum happens to be exactly equal to the integral (e.g., piecewise linear functions). When the Riemann sum gives a different value to the integral it is biased (in the same way that $3$ is a biased estimator of $2$). When the Riemann sum gives the same value as the integral it is unbiased (in the same way that $3$ is an unbiased estimator of $3$). Irrespective of whether the Riemann sum is a biased estimator or not, it will still be a consistent estimator, since it converges to the true integral as $n \rightarrow \infty$; indeed, this is the essence of the Riemann integral. Now, if you were to select the $t$ point uniformly at random within the interval, the resulting Riemann sum would be an unbiased estimator of the integral. This would be a variation of estimation by importance sampling, where you are varying things by generating your points conditionally within segments of a partition.
Is it wrong to say that a Riemann sum is an unbiased estimate of an integral?
Any constant is a biased estimator of any different constant Since you are using a deterministic procedure here, your Riemann sum depends only on $n$, so it is a sequence of constants. Applying the c
Is it wrong to say that a Riemann sum is an unbiased estimate of an integral? Any constant is a biased estimator of any different constant Since you are using a deterministic procedure here, your Riemann sum depends only on $n$, so it is a sequence of constants. Applying the concept of statistical bias to constants is simple --- any constant is a biased estimator of any different constant and an unbiased estimator of itself. So, for example, $3$ is a biased estimator of $2$, but it is an unbiased estimator of $3$. Your Riemann sum is generally going to be a biased estimator for the corresponding integral because you are selecting the points $t_k^*$ deterministically within the interval and so your estimator is a constant. There are exceptions, for functions where the Riemann sum happens to be exactly equal to the integral (e.g., piecewise linear functions). When the Riemann sum gives a different value to the integral it is biased (in the same way that $3$ is a biased estimator of $2$). When the Riemann sum gives the same value as the integral it is unbiased (in the same way that $3$ is an unbiased estimator of $3$). Irrespective of whether the Riemann sum is a biased estimator or not, it will still be a consistent estimator, since it converges to the true integral as $n \rightarrow \infty$; indeed, this is the essence of the Riemann integral. Now, if you were to select the $t$ point uniformly at random within the interval, the resulting Riemann sum would be an unbiased estimator of the integral. This would be a variation of estimation by importance sampling, where you are varying things by generating your points conditionally within segments of a partition.
Is it wrong to say that a Riemann sum is an unbiased estimate of an integral? Any constant is a biased estimator of any different constant Since you are using a deterministic procedure here, your Riemann sum depends only on $n$, so it is a sequence of constants. Applying the c
30,357
Are optimal hyperparameters still optimal for a deeper neural net architecture?
Unfortunately, it doesn't work that way. Hyperparameters cooperate in hard-to-predict ways. For example, a bit extreme to make the point. You have no hidden layers, in other words, you are fitting a logistic regression. A logistic regression will usually not really overfit. So you use a relatively big learning rate and a lot of epochs, and find that that works fine, at least, not worse than other hyperparameter configurations. Then you increase the number of layers. You get a complex model, that is now suddenly prone to overfitting. Then the big learning rate and the many epochs that worked fine earlier are no longer optimal. Small thing, I would say the number of hidden nodes, or more generally, the whole architecture of the neural network, is also part of the hyperparameters. So your question I read more like, will the same learning rate be optimal if I increase the complexity of the network.
Are optimal hyperparameters still optimal for a deeper neural net architecture?
Unfortunately, it doesn't work that way. Hyperparameters cooperate in hard-to-predict ways. For example, a bit extreme to make the point. You have no hidden layers, in other words, you are fitting a
Are optimal hyperparameters still optimal for a deeper neural net architecture? Unfortunately, it doesn't work that way. Hyperparameters cooperate in hard-to-predict ways. For example, a bit extreme to make the point. You have no hidden layers, in other words, you are fitting a logistic regression. A logistic regression will usually not really overfit. So you use a relatively big learning rate and a lot of epochs, and find that that works fine, at least, not worse than other hyperparameter configurations. Then you increase the number of layers. You get a complex model, that is now suddenly prone to overfitting. Then the big learning rate and the many epochs that worked fine earlier are no longer optimal. Small thing, I would say the number of hidden nodes, or more generally, the whole architecture of the neural network, is also part of the hyperparameters. So your question I read more like, will the same learning rate be optimal if I increase the complexity of the network.
Are optimal hyperparameters still optimal for a deeper neural net architecture? Unfortunately, it doesn't work that way. Hyperparameters cooperate in hard-to-predict ways. For example, a bit extreme to make the point. You have no hidden layers, in other words, you are fitting a
30,358
Does the universal approximation theorem for neural networks hold for any activation function?
The wikipedia article has a formal statement. Let $\varphi$ be a nonconstant, bounded, and continuous function.
Does the universal approximation theorem for neural networks hold for any activation function?
The wikipedia article has a formal statement. Let $\varphi$ be a nonconstant, bounded, and continuous function.
Does the universal approximation theorem for neural networks hold for any activation function? The wikipedia article has a formal statement. Let $\varphi$ be a nonconstant, bounded, and continuous function.
Does the universal approximation theorem for neural networks hold for any activation function? The wikipedia article has a formal statement. Let $\varphi$ be a nonconstant, bounded, and continuous function.
30,359
Does the universal approximation theorem for neural networks hold for any activation function?
Multilayer feedforward networks is a published reference that address the issue. Polynomial activation functions do not have the universla approximation property. The preprint NN with unbounded activation functions covers many activation functions. It looks only at single hidden layer NN. It is heavy on Fourier analysis. I emphasize that the second reference is a pre-print because I cannot vouch for its accuracy. Leshno et alt 1993 is a reviewed publication.
Does the universal approximation theorem for neural networks hold for any activation function?
Multilayer feedforward networks is a published reference that address the issue. Polynomial activation functions do not have the universla approximation property. The preprint NN with unbounded activa
Does the universal approximation theorem for neural networks hold for any activation function? Multilayer feedforward networks is a published reference that address the issue. Polynomial activation functions do not have the universla approximation property. The preprint NN with unbounded activation functions covers many activation functions. It looks only at single hidden layer NN. It is heavy on Fourier analysis. I emphasize that the second reference is a pre-print because I cannot vouch for its accuracy. Leshno et alt 1993 is a reviewed publication.
Does the universal approximation theorem for neural networks hold for any activation function? Multilayer feedforward networks is a published reference that address the issue. Polynomial activation functions do not have the universla approximation property. The preprint NN with unbounded activa
30,360
Does the universal approximation theorem for neural networks hold for any activation function?
Kurt Hornik's 1991 paper "Approximation Capabilities of Multilayer Feedforward Networks" proves that "standard multilayer feedforward networks with as few as a single hidden layer and arbitrary bounded and nonconstant activation function are universal approximators with respect to $L^P(\mu)$ performance criteria, for arbitrary finite input environment measures $\mu$, provided only that sufficiently many hidden units are available." In other words, the hypothesis that the activation function is bounded and nonconstant is sufficient to approximate nearly any function given we can use as many hidden units as we like in the neural network. The paper should be available here: http://zmjones.com/static/statistical-learning/hornik-nn-1991.pdf
Does the universal approximation theorem for neural networks hold for any activation function?
Kurt Hornik's 1991 paper "Approximation Capabilities of Multilayer Feedforward Networks" proves that "standard multilayer feedforward networks with as few as a single hidden layer and arbitrary bound
Does the universal approximation theorem for neural networks hold for any activation function? Kurt Hornik's 1991 paper "Approximation Capabilities of Multilayer Feedforward Networks" proves that "standard multilayer feedforward networks with as few as a single hidden layer and arbitrary bounded and nonconstant activation function are universal approximators with respect to $L^P(\mu)$ performance criteria, for arbitrary finite input environment measures $\mu$, provided only that sufficiently many hidden units are available." In other words, the hypothesis that the activation function is bounded and nonconstant is sufficient to approximate nearly any function given we can use as many hidden units as we like in the neural network. The paper should be available here: http://zmjones.com/static/statistical-learning/hornik-nn-1991.pdf
Does the universal approximation theorem for neural networks hold for any activation function? Kurt Hornik's 1991 paper "Approximation Capabilities of Multilayer Feedforward Networks" proves that "standard multilayer feedforward networks with as few as a single hidden layer and arbitrary bound
30,361
Does the universal approximation theorem for neural networks hold for any activation function?
We have to distinguish between Shallow Neural Networks (one hidden layer) and Deep Neural Networks (more than one hidden layer) since there is a difference. What I write below can also be found on the Wikipedia page Universal Approximation Theorem. Shallow Neural Networks: Pinkus showed in 1999 that Shallow Neural Networks with a continuous activation function have the universal approximation property on a compact set $K\subseteq \mathbb{R}$ if and only if the activation function is non-polynomial. The same article mentions that some discontinuous functions can also be used as activation function while preserving the universal approximation property for the networks. Deep Neural Networks: There are multiple different results. One of them is by Kidger and Lyon and is from 2020. Here they show that Deep Neural Networks have the universal approximation property on a compact set $K\subseteq\mathbb{R}$ when their activation function is: Continuous Nonaffine (i.e. not a multivariate polynomial of degree less than 2) Differentiable with a continuous derivative which is different from 0 at at least one point (the exact technical formulation is slightly more strict). This shows one of the differences between Deep and Shallow Neural Networks, namely that Deep Neural Networks still have the universal approximation property when their activation function is a (nonaffine) polynomial. In the article, Kidger and Lyon extend the result in multiple ways. For instance, they show that the result still holds for some activation functions which are continuous but nowhere differentiable.
Does the universal approximation theorem for neural networks hold for any activation function?
We have to distinguish between Shallow Neural Networks (one hidden layer) and Deep Neural Networks (more than one hidden layer) since there is a difference. What I write below can also be found on the
Does the universal approximation theorem for neural networks hold for any activation function? We have to distinguish between Shallow Neural Networks (one hidden layer) and Deep Neural Networks (more than one hidden layer) since there is a difference. What I write below can also be found on the Wikipedia page Universal Approximation Theorem. Shallow Neural Networks: Pinkus showed in 1999 that Shallow Neural Networks with a continuous activation function have the universal approximation property on a compact set $K\subseteq \mathbb{R}$ if and only if the activation function is non-polynomial. The same article mentions that some discontinuous functions can also be used as activation function while preserving the universal approximation property for the networks. Deep Neural Networks: There are multiple different results. One of them is by Kidger and Lyon and is from 2020. Here they show that Deep Neural Networks have the universal approximation property on a compact set $K\subseteq\mathbb{R}$ when their activation function is: Continuous Nonaffine (i.e. not a multivariate polynomial of degree less than 2) Differentiable with a continuous derivative which is different from 0 at at least one point (the exact technical formulation is slightly more strict). This shows one of the differences between Deep and Shallow Neural Networks, namely that Deep Neural Networks still have the universal approximation property when their activation function is a (nonaffine) polynomial. In the article, Kidger and Lyon extend the result in multiple ways. For instance, they show that the result still holds for some activation functions which are continuous but nowhere differentiable.
Does the universal approximation theorem for neural networks hold for any activation function? We have to distinguish between Shallow Neural Networks (one hidden layer) and Deep Neural Networks (more than one hidden layer) since there is a difference. What I write below can also be found on the
30,362
Proof that joint probability density of independent random variables is equal to the product of marginal densities
By definition, the random variables $X_1,\dots,X_n$ are independent iff $$ \Pr(X_1\in B_1,\dots,X_n\in B_n) = \Pr(X_1\in B_1)\dots\Pr(X_n\in B_n) $$ for every choice of Borel sets $B_1,\dots,B_n$. Hence, picking $B_i=(-\infty,t_i]$, we have $$ \Pr(X_1\leq t_1,\dots,X_n\leq t_n) = \Pr(X_1\leq t_1)\dots\Pr(X_n\leq t_n). \qquad (*) $$ If each $X_i$ has a density $f_{X_i}$, then the RHS of $(*)$ is equal to $$ \left(\int_{-\infty}^{t_1} f_{X_1}(x_1)\,dx_1\right) \dots \left(\int_{-\infty}^{t_n} f_{X_n}(x_n)\,dx_n\right). $$ By Fubini's theorem, this is equal to $$ \int_{-\infty}^{t_n}\dots\int_{-\infty}^{t_1} f_{X_1}(x_1)\dots f_{X_n}(x_n)\,dx_1\dots dx_n. $$ Hence, it follows that the random vector $(X_1,\dots,X_n)$ has density $$ f_{X_1,\dots X_n}(x_1,\dots,x_n) = f_{X_1}(x_1)\dots f_{X_n}(x_n). $$
Proof that joint probability density of independent random variables is equal to the product of marg
By definition, the random variables $X_1,\dots,X_n$ are independent iff $$ \Pr(X_1\in B_1,\dots,X_n\in B_n) = \Pr(X_1\in B_1)\dots\Pr(X_n\in B_n) $$ for every choice of Borel sets $B_1,\dots,B_n$. H
Proof that joint probability density of independent random variables is equal to the product of marginal densities By definition, the random variables $X_1,\dots,X_n$ are independent iff $$ \Pr(X_1\in B_1,\dots,X_n\in B_n) = \Pr(X_1\in B_1)\dots\Pr(X_n\in B_n) $$ for every choice of Borel sets $B_1,\dots,B_n$. Hence, picking $B_i=(-\infty,t_i]$, we have $$ \Pr(X_1\leq t_1,\dots,X_n\leq t_n) = \Pr(X_1\leq t_1)\dots\Pr(X_n\leq t_n). \qquad (*) $$ If each $X_i$ has a density $f_{X_i}$, then the RHS of $(*)$ is equal to $$ \left(\int_{-\infty}^{t_1} f_{X_1}(x_1)\,dx_1\right) \dots \left(\int_{-\infty}^{t_n} f_{X_n}(x_n)\,dx_n\right). $$ By Fubini's theorem, this is equal to $$ \int_{-\infty}^{t_n}\dots\int_{-\infty}^{t_1} f_{X_1}(x_1)\dots f_{X_n}(x_n)\,dx_1\dots dx_n. $$ Hence, it follows that the random vector $(X_1,\dots,X_n)$ has density $$ f_{X_1,\dots X_n}(x_1,\dots,x_n) = f_{X_1}(x_1)\dots f_{X_n}(x_n). $$
Proof that joint probability density of independent random variables is equal to the product of marg By definition, the random variables $X_1,\dots,X_n$ are independent iff $$ \Pr(X_1\in B_1,\dots,X_n\in B_n) = \Pr(X_1\in B_1)\dots\Pr(X_n\in B_n) $$ for every choice of Borel sets $B_1,\dots,B_n$. H
30,363
Proof that joint probability density of independent random variables is equal to the product of marginal densities
Informally: $$ \Pr(X \in \mathrm{d}x, Y \in \mathrm{d}y) = \Pr(X \in \mathrm{d}x) \Pr(Y \in \mathrm{d}y) = \bigl(f_X(x)\mathrm{d}x\bigr)\bigl(f_Y(y)\mathrm{d}y\bigr) = f_X(x)f_Y(y)\mathrm{d}x\mathrm{d}y. $$
Proof that joint probability density of independent random variables is equal to the product of marg
Informally: $$ \Pr(X \in \mathrm{d}x, Y \in \mathrm{d}y) = \Pr(X \in \mathrm{d}x) \Pr(Y \in \mathrm{d}y) = \bigl(f_X(x)\mathrm{d}x\bigr)\bigl(f_Y(y)\mathrm{d}y\bigr) = f_X(x)f_Y(y)\mathrm{d}x\mathrm{d
Proof that joint probability density of independent random variables is equal to the product of marginal densities Informally: $$ \Pr(X \in \mathrm{d}x, Y \in \mathrm{d}y) = \Pr(X \in \mathrm{d}x) \Pr(Y \in \mathrm{d}y) = \bigl(f_X(x)\mathrm{d}x\bigr)\bigl(f_Y(y)\mathrm{d}y\bigr) = f_X(x)f_Y(y)\mathrm{d}x\mathrm{d}y. $$
Proof that joint probability density of independent random variables is equal to the product of marg Informally: $$ \Pr(X \in \mathrm{d}x, Y \in \mathrm{d}y) = \Pr(X \in \mathrm{d}x) \Pr(Y \in \mathrm{d}y) = \bigl(f_X(x)\mathrm{d}x\bigr)\bigl(f_Y(y)\mathrm{d}y\bigr) = f_X(x)f_Y(y)\mathrm{d}x\mathrm{d
30,364
Proof that joint probability density of independent random variables is equal to the product of marginal densities
By definition: $f_{X,Y}(x,y) = f_{X\mid Y}(x\mid y)f_Y(y)$ If $X$ and $Y$ are independent: $f_{X\mid Y}(x\mid y) = f_X(x)$ Therefore $f_{X,Y}(x,y) = f_X(x)f_Y(y)$ Or more generally for the multinomial case: $\begin{align} f(x_1, \dots, x_n) & = f(x_1, \dots, x_n) \\ & = f(x_1 \mid x_2, \dots, x_n) p(x_2, \dots, x_n) \\ & = f(x_1 \mid x_2, \dots, x_n) f(x_2 \mid x_3, \dots, x_n) f(x_3, \dots, x_n) \\ & = \dots \\ & = f(x_1 \mid x_2, \dots, x_n) f(x_2 \mid x_3, \dots, x_n) \dots f(x_{n-1} \mid x_n) f(x_n) \\ & = f(x_1)...f(x_n) \text{ (By Independence)}\\ \end{align}$
Proof that joint probability density of independent random variables is equal to the product of marg
By definition: $f_{X,Y}(x,y) = f_{X\mid Y}(x\mid y)f_Y(y)$ If $X$ and $Y$ are independent: $f_{X\mid Y}(x\mid y) = f_X(x)$ Therefore $f_{X,Y}(x,y) = f_X(x)f_Y(y)$ Or more generally for the multinomial
Proof that joint probability density of independent random variables is equal to the product of marginal densities By definition: $f_{X,Y}(x,y) = f_{X\mid Y}(x\mid y)f_Y(y)$ If $X$ and $Y$ are independent: $f_{X\mid Y}(x\mid y) = f_X(x)$ Therefore $f_{X,Y}(x,y) = f_X(x)f_Y(y)$ Or more generally for the multinomial case: $\begin{align} f(x_1, \dots, x_n) & = f(x_1, \dots, x_n) \\ & = f(x_1 \mid x_2, \dots, x_n) p(x_2, \dots, x_n) \\ & = f(x_1 \mid x_2, \dots, x_n) f(x_2 \mid x_3, \dots, x_n) f(x_3, \dots, x_n) \\ & = \dots \\ & = f(x_1 \mid x_2, \dots, x_n) f(x_2 \mid x_3, \dots, x_n) \dots f(x_{n-1} \mid x_n) f(x_n) \\ & = f(x_1)...f(x_n) \text{ (By Independence)}\\ \end{align}$
Proof that joint probability density of independent random variables is equal to the product of marg By definition: $f_{X,Y}(x,y) = f_{X\mid Y}(x\mid y)f_Y(y)$ If $X$ and $Y$ are independent: $f_{X\mid Y}(x\mid y) = f_X(x)$ Therefore $f_{X,Y}(x,y) = f_X(x)f_Y(y)$ Or more generally for the multinomial
30,365
Deriving the normalizing constant for the multivariate Gaussian
The reason that $\int_{\mathcal{R}^d} e^{-\frac{1}{2} \sum_i \lambda_i y_i^2} dy$ is easier to integrate is that it can be expressed as a product of univariate integrals: \begin{align} \int_{\mathcal{R}^d} e^{-\frac{1}{2} \sum_i \lambda_i y_i^2} dy &= \int_{\mathcal{R}^d}\Pi_{i=1}^d e^{-\frac{1}{2} \lambda_i y_i^2} dy \\ &= \Pi_{i=1}^d \int_{-\infty}^{\infty} e^{\frac{-1}{2} \lambda_i y_i^2} dy_i \end{align} Now we can apply the formula for integrating under a univariate normal distribution: \begin{align} \Pi_{i=1}^d \int_{-\infty}^{\infty} e^{\frac{-1}{2} \lambda_i y_i^2} dy_i &= \Pi_{i=1}^d \left(2 \pi \lambda_i \right) ^{-\frac{1}{2}} \\ &= \sqrt{ (2 \pi)^d \Pi_{i=1}^d \lambda_i } \end{align} To finish this integral, note that the when you take the eigendecomposition $\Sigma = Q^T \Lambda Q$, the diagonal values of $\Lambda$ ($\lambda_i$) are the eigenvalues of $\Sigma$, and the product of the eigenvalues of $\Sigma$ is the determinant of $\Sigma$. That is, $\Pi_{i=1}^d \lambda_i = \mathrm{det}(\Sigma)$. This finally gives us $\int_{\mathcal{R}^d} e^{-\frac{1}{2} \sum_i \lambda_i y_i^2} dy = \sqrt{ (2 \pi)^d \left| \Sigma \right| }$. But wait! How did we get the right answer already? Shouldn't there have been a Jacobian involved when we transformed from $x$ to $y$? We needed to prove that $\int_{\mathcal{R^d}} e^{-\frac{1}{2} (x - \mu)^T Q^T \Lambda^{-1} Q (x-\mu)} dx = \int_{\mathcal{R^d}} e^{-\frac{1}{2} y^T \Lambda^{-1} y} \left| \frac{\partial x}{\partial y} \right| dy = \sqrt{ (2 \pi)^d \left| \Sigma \right| }$, but we've only shown that $\int_{\mathcal{R^d}} e^{-\frac{1}{2} y^T \Lambda^{-1} y} dy = \sqrt{ (2 \pi)^d \left| \Sigma \right| }$. To finish the proof, we need to show that $\left| J \right| = \left| \frac{\partial x}{\partial y} \right| = 1$. Let's look more carefully at that diagonalization. Since $\Sigma$ is a covariance matrix, it should be symmetric positive definite. Therefore, there is an eigendecomposition where $Q$ is orthonormal, so $\Sigma = Q^{-1} \Lambda Q$, where $\Lambda$ is diagonal and $Q^{-1} = Q^T$. So we have $y = Q(x - \mu)$, or $x = Q^T y + \mu$. Therefore, $\left| \frac{\partial x}{\partial y} \right| = |Q^T| = 1$, since $Q$ is orthonormal.
Deriving the normalizing constant for the multivariate Gaussian
The reason that $\int_{\mathcal{R}^d} e^{-\frac{1}{2} \sum_i \lambda_i y_i^2} dy$ is easier to integrate is that it can be expressed as a product of univariate integrals: \begin{align} \int_{\mathcal
Deriving the normalizing constant for the multivariate Gaussian The reason that $\int_{\mathcal{R}^d} e^{-\frac{1}{2} \sum_i \lambda_i y_i^2} dy$ is easier to integrate is that it can be expressed as a product of univariate integrals: \begin{align} \int_{\mathcal{R}^d} e^{-\frac{1}{2} \sum_i \lambda_i y_i^2} dy &= \int_{\mathcal{R}^d}\Pi_{i=1}^d e^{-\frac{1}{2} \lambda_i y_i^2} dy \\ &= \Pi_{i=1}^d \int_{-\infty}^{\infty} e^{\frac{-1}{2} \lambda_i y_i^2} dy_i \end{align} Now we can apply the formula for integrating under a univariate normal distribution: \begin{align} \Pi_{i=1}^d \int_{-\infty}^{\infty} e^{\frac{-1}{2} \lambda_i y_i^2} dy_i &= \Pi_{i=1}^d \left(2 \pi \lambda_i \right) ^{-\frac{1}{2}} \\ &= \sqrt{ (2 \pi)^d \Pi_{i=1}^d \lambda_i } \end{align} To finish this integral, note that the when you take the eigendecomposition $\Sigma = Q^T \Lambda Q$, the diagonal values of $\Lambda$ ($\lambda_i$) are the eigenvalues of $\Sigma$, and the product of the eigenvalues of $\Sigma$ is the determinant of $\Sigma$. That is, $\Pi_{i=1}^d \lambda_i = \mathrm{det}(\Sigma)$. This finally gives us $\int_{\mathcal{R}^d} e^{-\frac{1}{2} \sum_i \lambda_i y_i^2} dy = \sqrt{ (2 \pi)^d \left| \Sigma \right| }$. But wait! How did we get the right answer already? Shouldn't there have been a Jacobian involved when we transformed from $x$ to $y$? We needed to prove that $\int_{\mathcal{R^d}} e^{-\frac{1}{2} (x - \mu)^T Q^T \Lambda^{-1} Q (x-\mu)} dx = \int_{\mathcal{R^d}} e^{-\frac{1}{2} y^T \Lambda^{-1} y} \left| \frac{\partial x}{\partial y} \right| dy = \sqrt{ (2 \pi)^d \left| \Sigma \right| }$, but we've only shown that $\int_{\mathcal{R^d}} e^{-\frac{1}{2} y^T \Lambda^{-1} y} dy = \sqrt{ (2 \pi)^d \left| \Sigma \right| }$. To finish the proof, we need to show that $\left| J \right| = \left| \frac{\partial x}{\partial y} \right| = 1$. Let's look more carefully at that diagonalization. Since $\Sigma$ is a covariance matrix, it should be symmetric positive definite. Therefore, there is an eigendecomposition where $Q$ is orthonormal, so $\Sigma = Q^{-1} \Lambda Q$, where $\Lambda$ is diagonal and $Q^{-1} = Q^T$. So we have $y = Q(x - \mu)$, or $x = Q^T y + \mu$. Therefore, $\left| \frac{\partial x}{\partial y} \right| = |Q^T| = 1$, since $Q$ is orthonormal.
Deriving the normalizing constant for the multivariate Gaussian The reason that $\int_{\mathcal{R}^d} e^{-\frac{1}{2} \sum_i \lambda_i y_i^2} dy$ is easier to integrate is that it can be expressed as a product of univariate integrals: \begin{align} \int_{\mathcal
30,366
Deriving the normalizing constant for the multivariate Gaussian
Trying to put it all together for convenience. The probability density of multivariate normal distribution is $$p(\mathbf{x}) = \frac{1}{Z} e^{- \frac{1}{2} (\mathbf{x} - \boldsymbol{\mu})^T \Sigma^{-1} (\mathbf{x} - \boldsymbol{\mu})}$$ where $\Sigma$ is the covariance matrix, and can be eigen-decomposed into $$\Sigma = Q \Lambda Q^T$$ with $Q$ being an orthonormal matrix, and $\Lambda$ being a diagonal matrix filled with eigenvalues. so $$\Sigma^{-1} = Q \Lambda^{-1} Q^T$$ Then, $p(\mathbf{x})$ can be rewritten as \begin{align*} p(x) &= \frac{1}{Z} e^{- \frac{1}{2} (\mathbf{x} - \mathbf{\mu})^T Q \Lambda^{-1} Q^T (\mathbf{x} - \mathbf{\mu})} \\ &= \frac{1}{Z} e^{- \frac{1}{2} \mathbf{y}^T \Lambda^{-1} \mathbf{y}} \\ &= \frac{1}{Z} e^{- \frac{1}{2} \sum_i^d \frac{y_i^2}{\lambda_i}} \\ &= \frac{1}{Z} \prod_i^d e^{- \frac{y_i^2}{2\lambda_i}} \end{align*} where $\mathbf{y} = Q^T (\mathbf{x} - \mathbf{\mu})$, $y_i$ is the ith element of $\mathbf{y}$, and $\lambda_i$ is the ith element along the diagonal of $\Lambda$ \begin{align*} Z &= \int_{\mathcal{R}^d} \prod_i^d e^{- \frac{y_i^2}{2\lambda_i}} d\mathbf{y} \\ &= \int_{y_d} e^{- \frac{y_d^2}{2\lambda_d}} \cdots \int_{y_1} e^{- \frac{y_1^2}{2\lambda_1}} dy_1 \cdots dy_d \\ &= \int_{y_d} e^{- \frac{y_d^2}{2\lambda_d}} \cdots \int_{y_2} e^{- \frac{y_2^2}{2\lambda_2}} \sqrt{2 \pi \lambda_1} dy_2 \cdots dy_d \\ &= \prod_{i=1}^d \sqrt{2 \pi \lambda_i} \\ &= (2 \pi)^{\frac{d}{2}} \prod_{i=1}^d (\lambda_i)^{\frac{1}{2}} \\ &= (2 \pi)^{\frac{d}{2}} \left|\Sigma\right|^{\frac{1}{2}} \\ \end{align*} The 3rd equality used the calculation of normalization constant in the case of centered univariate normal distribution ($\int_{-\infty}^{\infty} e^{- \frac{x^2}{2 \sigma^2}} dx = \sigma \sqrt{2\pi}$). The 6th equality uses the fact that the product of eigenvalues of $\Sigma$ is equal to its determinant ($\prod_i^d \lambda_i = \left| \Sigma \right|$)
Deriving the normalizing constant for the multivariate Gaussian
Trying to put it all together for convenience. The probability density of multivariate normal distribution is $$p(\mathbf{x}) = \frac{1}{Z} e^{- \frac{1}{2} (\mathbf{x} - \boldsymbol{\mu})^T \Sigma^{
Deriving the normalizing constant for the multivariate Gaussian Trying to put it all together for convenience. The probability density of multivariate normal distribution is $$p(\mathbf{x}) = \frac{1}{Z} e^{- \frac{1}{2} (\mathbf{x} - \boldsymbol{\mu})^T \Sigma^{-1} (\mathbf{x} - \boldsymbol{\mu})}$$ where $\Sigma$ is the covariance matrix, and can be eigen-decomposed into $$\Sigma = Q \Lambda Q^T$$ with $Q$ being an orthonormal matrix, and $\Lambda$ being a diagonal matrix filled with eigenvalues. so $$\Sigma^{-1} = Q \Lambda^{-1} Q^T$$ Then, $p(\mathbf{x})$ can be rewritten as \begin{align*} p(x) &= \frac{1}{Z} e^{- \frac{1}{2} (\mathbf{x} - \mathbf{\mu})^T Q \Lambda^{-1} Q^T (\mathbf{x} - \mathbf{\mu})} \\ &= \frac{1}{Z} e^{- \frac{1}{2} \mathbf{y}^T \Lambda^{-1} \mathbf{y}} \\ &= \frac{1}{Z} e^{- \frac{1}{2} \sum_i^d \frac{y_i^2}{\lambda_i}} \\ &= \frac{1}{Z} \prod_i^d e^{- \frac{y_i^2}{2\lambda_i}} \end{align*} where $\mathbf{y} = Q^T (\mathbf{x} - \mathbf{\mu})$, $y_i$ is the ith element of $\mathbf{y}$, and $\lambda_i$ is the ith element along the diagonal of $\Lambda$ \begin{align*} Z &= \int_{\mathcal{R}^d} \prod_i^d e^{- \frac{y_i^2}{2\lambda_i}} d\mathbf{y} \\ &= \int_{y_d} e^{- \frac{y_d^2}{2\lambda_d}} \cdots \int_{y_1} e^{- \frac{y_1^2}{2\lambda_1}} dy_1 \cdots dy_d \\ &= \int_{y_d} e^{- \frac{y_d^2}{2\lambda_d}} \cdots \int_{y_2} e^{- \frac{y_2^2}{2\lambda_2}} \sqrt{2 \pi \lambda_1} dy_2 \cdots dy_d \\ &= \prod_{i=1}^d \sqrt{2 \pi \lambda_i} \\ &= (2 \pi)^{\frac{d}{2}} \prod_{i=1}^d (\lambda_i)^{\frac{1}{2}} \\ &= (2 \pi)^{\frac{d}{2}} \left|\Sigma\right|^{\frac{1}{2}} \\ \end{align*} The 3rd equality used the calculation of normalization constant in the case of centered univariate normal distribution ($\int_{-\infty}^{\infty} e^{- \frac{x^2}{2 \sigma^2}} dx = \sigma \sqrt{2\pi}$). The 6th equality uses the fact that the product of eigenvalues of $\Sigma$ is equal to its determinant ($\prod_i^d \lambda_i = \left| \Sigma \right|$)
Deriving the normalizing constant for the multivariate Gaussian Trying to put it all together for convenience. The probability density of multivariate normal distribution is $$p(\mathbf{x}) = \frac{1}{Z} e^{- \frac{1}{2} (\mathbf{x} - \boldsymbol{\mu})^T \Sigma^{
30,367
Estimate of parameter of exponential distribution with binned data
I would not use the midpoint for any of those intervals (expect perhaps as an initial guess for some iterative procedure). If the data were really from an exponential distribution, the values within each bin should be right skew; the mean would be expected to be left of the average of the bin boundaries. Note that the equation $\hat{\lambda}=\frac{1}{\bar{X}}$ is suitable if you have all the data. With binned data you need to maximize the likelihood for a binned (i.e. interval-censored) exponential. [The contribution to log-likelihood of the $n_i$ observations in bin $i$ -- those between $l_i$ and $u_i$ -- is $n_i \log(F(l_i)-F(u_i))$ (where the two terms in $F$ are functions of the parameter(s) of the distribution).] Because of the lack of memory property of the exponential, if you have a good approximation for the mean of the exponential you also have a good approximation of the amount by which the mean of the distribution above some value $x_0$ exceeds $x_0$. So (assuming you don't directly maximize the likelihood* on the interval censored data as I suggested), you could begin with some approximate estimate of the mean ($m^{(0)}$ say) and use $120+m^{(0)}$ as a "centre" of the upper tail. This might then be used to get a better estimate of the parameter (and hence of the mean) and so obtain an improved estimate of the conditional mean in each bin including the top one. [If you want such an approach I would perhaps lean toward doing EM directly.] Several simple estimates of the mean can be obtained quickly. For example, since 41% of the values occur below 20, $\exp(-\frac{20}{\hat{\lambda}^{(0)}})=1-0.41$ which corresponds to an estimate of the mean close to $38$. Alternatively, one can get a quick eyeball estimate of the median (something less than 30, perhaps about 28), so the mean should be somewhere near $28/\log(2)$, or around $40$. Either of these would be reasonable to use as an initial guess at how far above 120 to place an estimate for the conditional mean for the last bin. * An alternative to maximizing the likelihood would be to minimize the chi-square statistic; the same adjustment to d.f. would be used in that instance. The chi-square statistic is relatively easy to calculate, and pretty simple to optimize for a single parameter:
Estimate of parameter of exponential distribution with binned data
I would not use the midpoint for any of those intervals (expect perhaps as an initial guess for some iterative procedure). If the data were really from an exponential distribution, the values within
Estimate of parameter of exponential distribution with binned data I would not use the midpoint for any of those intervals (expect perhaps as an initial guess for some iterative procedure). If the data were really from an exponential distribution, the values within each bin should be right skew; the mean would be expected to be left of the average of the bin boundaries. Note that the equation $\hat{\lambda}=\frac{1}{\bar{X}}$ is suitable if you have all the data. With binned data you need to maximize the likelihood for a binned (i.e. interval-censored) exponential. [The contribution to log-likelihood of the $n_i$ observations in bin $i$ -- those between $l_i$ and $u_i$ -- is $n_i \log(F(l_i)-F(u_i))$ (where the two terms in $F$ are functions of the parameter(s) of the distribution).] Because of the lack of memory property of the exponential, if you have a good approximation for the mean of the exponential you also have a good approximation of the amount by which the mean of the distribution above some value $x_0$ exceeds $x_0$. So (assuming you don't directly maximize the likelihood* on the interval censored data as I suggested), you could begin with some approximate estimate of the mean ($m^{(0)}$ say) and use $120+m^{(0)}$ as a "centre" of the upper tail. This might then be used to get a better estimate of the parameter (and hence of the mean) and so obtain an improved estimate of the conditional mean in each bin including the top one. [If you want such an approach I would perhaps lean toward doing EM directly.] Several simple estimates of the mean can be obtained quickly. For example, since 41% of the values occur below 20, $\exp(-\frac{20}{\hat{\lambda}^{(0)}})=1-0.41$ which corresponds to an estimate of the mean close to $38$. Alternatively, one can get a quick eyeball estimate of the median (something less than 30, perhaps about 28), so the mean should be somewhere near $28/\log(2)$, or around $40$. Either of these would be reasonable to use as an initial guess at how far above 120 to place an estimate for the conditional mean for the last bin. * An alternative to maximizing the likelihood would be to minimize the chi-square statistic; the same adjustment to d.f. would be used in that instance. The chi-square statistic is relatively easy to calculate, and pretty simple to optimize for a single parameter:
Estimate of parameter of exponential distribution with binned data I would not use the midpoint for any of those intervals (expect perhaps as an initial guess for some iterative procedure). If the data were really from an exponential distribution, the values within
30,368
Estimate of parameter of exponential distribution with binned data
From a theoretical standpoint, the likelihood of the sample that you obtained would be written as $$\mathcal L(\lambda \mid \boldsymbol x) = \prod_{j=1}^m (e^{-\lambda x_{j-1}} - e^{-\lambda x_{j}})^{n_j},$$ where $(x_0, x_1, \ldots, x_m)$ are the bin boundaries (assuming that each bin represents the probability of observing $x_{j-1} < X \le x_j$), and $n_j$ is the number of observations in bin $j$. Here, you have $m = 6$ bins, with $(x_0, x_1, \ldots, x_m) = (0, 20, 40, 60, 90, 120, \infty)$, and $(n_1, \ldots, n_m) = (41, 19, 16, 13, 9, 2)$. In general, maximizing the log-likelihood of this expression will need a numerical approach. Using Mathematica, I obtained the derivative of the log-likelihood as $$\frac{\partial \ell}{\partial \lambda} = \frac{760}{\sinh 10 \lambda +\sinh 20 \lambda} + 1090 \coth 15 \lambda - 3940.$$ This yields the numeric solution $$\hat\lambda \approx 0.025562426096803193.$$
Estimate of parameter of exponential distribution with binned data
From a theoretical standpoint, the likelihood of the sample that you obtained would be written as $$\mathcal L(\lambda \mid \boldsymbol x) = \prod_{j=1}^m (e^{-\lambda x_{j-1}} - e^{-\lambda x_{j}})^{
Estimate of parameter of exponential distribution with binned data From a theoretical standpoint, the likelihood of the sample that you obtained would be written as $$\mathcal L(\lambda \mid \boldsymbol x) = \prod_{j=1}^m (e^{-\lambda x_{j-1}} - e^{-\lambda x_{j}})^{n_j},$$ where $(x_0, x_1, \ldots, x_m)$ are the bin boundaries (assuming that each bin represents the probability of observing $x_{j-1} < X \le x_j$), and $n_j$ is the number of observations in bin $j$. Here, you have $m = 6$ bins, with $(x_0, x_1, \ldots, x_m) = (0, 20, 40, 60, 90, 120, \infty)$, and $(n_1, \ldots, n_m) = (41, 19, 16, 13, 9, 2)$. In general, maximizing the log-likelihood of this expression will need a numerical approach. Using Mathematica, I obtained the derivative of the log-likelihood as $$\frac{\partial \ell}{\partial \lambda} = \frac{760}{\sinh 10 \lambda +\sinh 20 \lambda} + 1090 \coth 15 \lambda - 3940.$$ This yields the numeric solution $$\hat\lambda \approx 0.025562426096803193.$$
Estimate of parameter of exponential distribution with binned data From a theoretical standpoint, the likelihood of the sample that you obtained would be written as $$\mathcal L(\lambda \mid \boldsymbol x) = \prod_{j=1}^m (e^{-\lambda x_{j-1}} - e^{-\lambda x_{j}})^{
30,369
Estimate of parameter of exponential distribution with binned data
If you are interested in a closed form, simple estimate, the UWSE (Unique Weight Space Estimator) can be helpful. In particular, if $ \ \hat{w_{[0,20]}}\ $ is the relative frequency of observations in the interval $ \ [0,20] \ $, then: $$ \ \hat{\lambda_{UWSE}} = -\frac{ln(1-\hat{w_{[0,20]}})}{20} \ $$ In this case, $ \ \hat{w_{[0,20]}} = 0.41\ $ , and hence, $$ \ \hat{\lambda_{UWSE}} = 0.02638164 \ $$ Though, all that can be said of the UWSE is that it is a consistent estimate. Here is a link to the full explanation of the estimator:https://paradsp.wordpress.com/ - scroll all the way to the bottom.
Estimate of parameter of exponential distribution with binned data
If you are interested in a closed form, simple estimate, the UWSE (Unique Weight Space Estimator) can be helpful. In particular, if $ \ \hat{w_{[0,20]}}\ $ is the relative frequency of observations in
Estimate of parameter of exponential distribution with binned data If you are interested in a closed form, simple estimate, the UWSE (Unique Weight Space Estimator) can be helpful. In particular, if $ \ \hat{w_{[0,20]}}\ $ is the relative frequency of observations in the interval $ \ [0,20] \ $, then: $$ \ \hat{\lambda_{UWSE}} = -\frac{ln(1-\hat{w_{[0,20]}})}{20} \ $$ In this case, $ \ \hat{w_{[0,20]}} = 0.41\ $ , and hence, $$ \ \hat{\lambda_{UWSE}} = 0.02638164 \ $$ Though, all that can be said of the UWSE is that it is a consistent estimate. Here is a link to the full explanation of the estimator:https://paradsp.wordpress.com/ - scroll all the way to the bottom.
Estimate of parameter of exponential distribution with binned data If you are interested in a closed form, simple estimate, the UWSE (Unique Weight Space Estimator) can be helpful. In particular, if $ \ \hat{w_{[0,20]}}\ $ is the relative frequency of observations in
30,370
How is the Box-Cox transformation valid?
One statement and six questions here. But first on behalf of namesakes everywhere and the continuing history of statistics, please note that the proper-cased name "Box-Cox" is standard. The Box-Cox transformation transforms our data into a normal distribution. At most, that's the goal. It can't always be achieved, even approximately. For example, a distribution that is in essence a series of spikes can't be transformed into anything but another series of spikes. How is that even a proper technique? Conversely, in what sense is it improper? The general idea of transformation is that it can be easier to see and analyze what is happening on a transformed scale, while specifically there are many techniques for which some approximation to normal distribution(s) provides, if not conditions that are assumed to be true, as so often stated, then at least relatively ideal conditions for summary and inference. Note that generalized linear models borrow the idea of fitting on a transformed scale without actually obliging transformation of the response variable. What if our data didn't come from a normal distribution? It's not clear what the puzzle is here. It's precisely when data are not normally distributed that the question of whether there is a simple transformation to normality arises. How could someone just blindly apply the Box-Cox transformation? As above. Some people blindly apply every statistical technique they use and statistical people tend to disapprove of that rather than approve. At the same time, life is short and there is an element of trust in most technique use, as no-one can derive and justify everything they do. The other questions look like the same questions rephrased, or else I am missing nuances. But in turn I'll repeat what seems to me a simple key: normal distributions are often an ideal, yet many techniques work well even if that ideal is not satisfied. At this distance, the main contributions of the Box-Cox formulation from 1964 appear to me to be The idea that the data themselves will tell you which transformation is most nearly appropriate. (We should add that sometimes no transformation will help enough to be worth applying.) Box and Cox formalised that data-guided choice of transformation in various ways, but the important point is implicitly or explicitly to try out various transformations systematically. (All too often, search for transformation appears to be stabbing in the dark, as when people tell you that they have tried logarithms and squaring, but nothing works.) The idea that most of the transformations in use, especially for positive measured variables or counted variables, belong to a family including not only the powers but also logarithms. This idea was also widely emphasised earlier, notably by Tukey (1957), whose paper was rather oddly not cited by Box and Cox, but the Box and Cox formulation, followed by Tukey's later work, seems to have been more successful in popularising the idea of a family. As just stated, emphasis on choice from a family makes the idea of transformation choice more systematic, and less ad hoc. Note that Box-Cox is indicative, not commanding, on what the decision should be. In their own worked examples they choose logarithms and reciprocal transformations, thus rounding off the powers given by their estimation procedure. Indeed both examples were of the kind where experienced analysts would have chosen the same transformation any way before their paper. Box, G.E.P. and Cox, D.R. 1964. An analysis of transformations. Journal of the Royal Statistical Society Series B 26: 211–252. Tukey, J.W. 1957. On the comparative anatomy of transformations. Annals of Mathematical Statistics 28, 602-632. doi:10.1214/aoms/1177706875. http://projecteuclid.org/euclid.aoms/1177706875.
How is the Box-Cox transformation valid?
One statement and six questions here. But first on behalf of namesakes everywhere and the continuing history of statistics, please note that the proper-cased name "Box-Cox" is standard. The Box-Cox
How is the Box-Cox transformation valid? One statement and six questions here. But first on behalf of namesakes everywhere and the continuing history of statistics, please note that the proper-cased name "Box-Cox" is standard. The Box-Cox transformation transforms our data into a normal distribution. At most, that's the goal. It can't always be achieved, even approximately. For example, a distribution that is in essence a series of spikes can't be transformed into anything but another series of spikes. How is that even a proper technique? Conversely, in what sense is it improper? The general idea of transformation is that it can be easier to see and analyze what is happening on a transformed scale, while specifically there are many techniques for which some approximation to normal distribution(s) provides, if not conditions that are assumed to be true, as so often stated, then at least relatively ideal conditions for summary and inference. Note that generalized linear models borrow the idea of fitting on a transformed scale without actually obliging transformation of the response variable. What if our data didn't come from a normal distribution? It's not clear what the puzzle is here. It's precisely when data are not normally distributed that the question of whether there is a simple transformation to normality arises. How could someone just blindly apply the Box-Cox transformation? As above. Some people blindly apply every statistical technique they use and statistical people tend to disapprove of that rather than approve. At the same time, life is short and there is an element of trust in most technique use, as no-one can derive and justify everything they do. The other questions look like the same questions rephrased, or else I am missing nuances. But in turn I'll repeat what seems to me a simple key: normal distributions are often an ideal, yet many techniques work well even if that ideal is not satisfied. At this distance, the main contributions of the Box-Cox formulation from 1964 appear to me to be The idea that the data themselves will tell you which transformation is most nearly appropriate. (We should add that sometimes no transformation will help enough to be worth applying.) Box and Cox formalised that data-guided choice of transformation in various ways, but the important point is implicitly or explicitly to try out various transformations systematically. (All too often, search for transformation appears to be stabbing in the dark, as when people tell you that they have tried logarithms and squaring, but nothing works.) The idea that most of the transformations in use, especially for positive measured variables or counted variables, belong to a family including not only the powers but also logarithms. This idea was also widely emphasised earlier, notably by Tukey (1957), whose paper was rather oddly not cited by Box and Cox, but the Box and Cox formulation, followed by Tukey's later work, seems to have been more successful in popularising the idea of a family. As just stated, emphasis on choice from a family makes the idea of transformation choice more systematic, and less ad hoc. Note that Box-Cox is indicative, not commanding, on what the decision should be. In their own worked examples they choose logarithms and reciprocal transformations, thus rounding off the powers given by their estimation procedure. Indeed both examples were of the kind where experienced analysts would have chosen the same transformation any way before their paper. Box, G.E.P. and Cox, D.R. 1964. An analysis of transformations. Journal of the Royal Statistical Society Series B 26: 211–252. Tukey, J.W. 1957. On the comparative anatomy of transformations. Annals of Mathematical Statistics 28, 602-632. doi:10.1214/aoms/1177706875. http://projecteuclid.org/euclid.aoms/1177706875.
How is the Box-Cox transformation valid? One statement and six questions here. But first on behalf of namesakes everywhere and the continuing history of statistics, please note that the proper-cased name "Box-Cox" is standard. The Box-Cox
30,371
Explicit solution for linear regression with two predictors
Elsewhere on this site, explicit solutions to the ordinary least squares regression $$\mathbb{E}(z_i) = A x_i + B y_i + C$$ are available in matrix form as $$(C,A,B)^\prime = (X^\prime X)^{-1} X^\prime z\tag{1}$$ where $X$ is the "model matrix" $$X = \pmatrix{1 & x_1 & y_1 \\ 1 & x_2 & y_2 \\ \vdots & \vdots & \vdots \\ 1 & x_n & y_n}$$ and $z$ is the response vector $$z = (z_1, z_2, \ldots, z_n)^\prime.$$ That's a perfectly fine, explicit, computable answer. But maybe there is some additional understanding that can be wrung out of it by inspecting the coefficients. This can be achieved by choosing appropriate units in which to express the variables. The best units for this purpose center each variable at its mean and use its standard deviation as the unit of measurement. Explicitly, let the three means be $m_x, m_y,$ and $m_z$ and the three standard deviations be $s_x, s_y,$ and $s_z$. (It turns out not to matter whether you divide by $n$ or $n-1$ in computing the standard deviations. Just make sure you use a consistent convention when you compute any second moment of the data.) The values of the variables in these new units of measurement are $$\xi_i = \frac{x_i - m_x}{s_x},\ \eta_i = \frac{y_i - m_y}{s_y},\ \zeta_i = \frac{z_i - m_z}{s_z}.$$ This process is known as standardizing the data. The variables $\xi$, $\eta$, and $\zeta$ are the standardized versions of the original variables $x$, $y$, and $z$. These relationships are invertible: $$x_i = s_x \xi_i + m_x,\ y_i = s_y \eta_i + m_y,\ z_i = s_z \zeta_i + m_z.$$ Plugging these into the defining relationship $$\mathbb{E}(z_i) = C + Ax_i + By_i$$ and simplifying yields $$\mathbb{E}(s_z \zeta_i + m_z) = C + A(s_x \xi_i + m_x) + B(s_y \eta_i + m_y).$$ Solving for the expectation of the dependent variable $\zeta_i$ yields $$\mathbb{E}(\zeta_i) = \left(\frac{C + Am_x + Bm_y - m_z}{s_z}\right) + \left(\frac{A s_x}{s_z}\right) \xi_i + \left(\frac{B s_y}{s_z}\right) \eta_i.$$ If we write these coefficients as $\beta_0, \beta_1, \beta_2$ respectively, then we can recover $A, B, C$ by comparing and solving. For the record this gives $$A = \frac{s_z \beta_1}{s_x},\ B = \frac{s_z \beta_2}{s_y},\text{ and }C = s_z \beta_0 + m_z - A m_x - B m_y.\tag{2}$$ The point of this becomes apparent when we consider the new model matrix $$\Xi = \pmatrix{1 & \xi_1 & \eta_i \\ 1 & \xi_2 & \eta_2 \\ \vdots & \vdots & \vdots \\ 1 & \xi_n & \eta_n}$$ and the new response matrix $\zeta = (\zeta_1, \zeta_2, \ldots, \zeta_n)$, because now $$\Xi^\prime \Xi = \pmatrix{n & 0 & 0 \\ 0 & n & n\rho \\ 0 & n\rho & n}$$ and $$\Xi^\prime \zeta = (0, n\tau, n\upsilon)^\prime$$ where $\rho$ is the correlation coefficient $\frac{1}{n}\sum_{i=1}^n \xi_i \eta_i$, $\tau$ is the correlation coefficient $\frac{1}{n}\sum_{i=1}^n \xi_i \zeta_i$, and $\upsilon$ is the correlation coefficient $\frac{1}{n}\sum_{i=1}^n \eta_i \zeta_i$. To solve the normal equations $(1)$ we may divide both sides by $n$, giving $$\pmatrix{1 & 0 & 0 \\ 0 & 1 & \rho \\ 0 & \rho & 1}\pmatrix{\beta_0 \\ \beta_1 \\ \beta_2} = \pmatrix{0 \\ \tau \\ \upsilon} .$$ What originally looked like a formidable matrix formula has been reduced to a truly elementary set of three simultaneous equations. Provided $|\rho| \lt 1$, its solution is easily found to be $$\pmatrix{\hat\beta_0 \\ \hat\beta_1 \\ \hat\beta_2} = \frac{1}{1-\rho^2}\pmatrix{0 \\ \tau-\rho\upsilon \\ \upsilon-\rho\tau}.$$ Plugging these into the coefficients in $(2)$ produces the estimates $\hat A, \hat B,$ and $\hat C$. In fact, even more has been achieved: It is now evident why the cases $|\rho|=1$ are problematic: they introduce a divide-by-zero condition in the solution. It is equally evident how to determine whether a solution exists when $|\rho=1|$ and how to obtain it. It will exist when the second and third normal equations in $\Xi$ are redundant and it will be obtained simply by ignoring one of the variables $x$ and $y$ in the first place. We can derive some insight into the solution generally. For instance, from $\hat\beta_0=0$ in all cases, we may conclude that the fitted plane must pass through the point of averages $(m_x, m_y, m_z)$. It is now evident that the solution can be found in terms of the first two moments of the trivariate dataset $(x, y, z)$. This sheds further light on the fact that coefficient estimates can be found from means and covariance matrices alone. Furthermore, equation $(2)$ shows that the means are needed only to estimate the intercept term $C$. Estimates of the two slopes $A$ and $B$ require only the second moments. When the regressors are uncorrelated, $\rho=0$ and the solution is that the intercept is zero and the slopes are the correlation coefficients between the response $z$ and the regressors $x$ and $y$ when we standardize the data. This is both easy to remember and provides insight into how regression coefficients are related to correlation coefficients. Putting this all together, we find that (except in the degenerate cases $|\rho|=1$) the estimates can be written $$\eqalign{ \hat A &= \frac{\tau - \rho\upsilon}{1-\rho^2} \frac{s_z}{s_x} \\ \hat B &= \frac{\upsilon - \rho\tau}{1-\rho^2} \frac{s_z}{s_y} \\ \hat C &= m_z -m_x \hat A - m_y \hat B. }$$ In these formulae, the $m_{*}$ are the sample means, the $s_{*}$ are the sample standard deviations, and the greek letters $\rho, \tau,$ and $\upsilon$ represent the three correlation coefficients (between $x$ and $y$, $x$ and $z$, and $y$ and $z$, respectively). Please note that these formulas are not the best way to carry out the calculations. They all involve subtracting quantities that might be of comparable size, such as $\tau-\rho\upsilon$, $\upsilon-\rho\tau$, and $m_z - (-m_x \hat A - m_y \hat B)$. Such subtraction involves loss of precision. The matrix formulation allows numerical analysts to obtain more stable solutions that preserve as much precision as possible. This is why people rarely have any interest in term-by-term formulas. The other reason there is little interest is that as the number of regressors increases, the complexity of the formulas grows exponentially, quickly becoming too unwieldy. As further evidence of the correctness of these formulas, we may compare their answers to those of a standard least-squares solver, the lm function in R. # # Generate trivariate data. # library(MASS) set.seed(17) n <- 20 mu <- 1:3 Sigma <- matrix(1, 3, 3) Sigma[lower.tri(Sigma)] <- Sigma[upper.tri(Sigma)] <- c(.8, .5, .6) xyz <- data.frame(mvrnorm(n, mu, Sigma)) names(xyz) <- c("x", "y", "z") # # Obtain the least squares coefficients. # beta.hat <- coef(lm(z ~ x + y, xyz)) # # Compute the first two moments via `colMeans` and `cov`. # m <- colMeans(xyz) sigma <- cov(xyz) s <- sqrt(diag(sigma)) rho <- t(t(sigma/s)/s); rho <- as.vector(rho[lower.tri(rho)]) # # Here are the least squares coefficient estimates in terms of the moments. # A.hat <- (rho[2] - rho[1]*rho[3]) / (1 - rho[1]^2) * s[3] / s[1] B.hat <- (rho[3] - rho[1]*rho[2]) / (1 - rho[1]^2) * s[3] / s[2] C.hat <- m[3] - m[1]*A.hat - m[2]*B.hat # # Compare the two solutions. # rbind(beta.hat, formulae=c(C.hat, A.hat, B.hat)) The output exhibits two identical rows of estimates, as expected: (Intercept) x y beta.hat 1.522571 0.3013662 0.403636 formulae 1.522571 0.3013662 0.403636
Explicit solution for linear regression with two predictors
Elsewhere on this site, explicit solutions to the ordinary least squares regression $$\mathbb{E}(z_i) = A x_i + B y_i + C$$ are available in matrix form as $$(C,A,B)^\prime = (X^\prime X)^{-1} X^\prim
Explicit solution for linear regression with two predictors Elsewhere on this site, explicit solutions to the ordinary least squares regression $$\mathbb{E}(z_i) = A x_i + B y_i + C$$ are available in matrix form as $$(C,A,B)^\prime = (X^\prime X)^{-1} X^\prime z\tag{1}$$ where $X$ is the "model matrix" $$X = \pmatrix{1 & x_1 & y_1 \\ 1 & x_2 & y_2 \\ \vdots & \vdots & \vdots \\ 1 & x_n & y_n}$$ and $z$ is the response vector $$z = (z_1, z_2, \ldots, z_n)^\prime.$$ That's a perfectly fine, explicit, computable answer. But maybe there is some additional understanding that can be wrung out of it by inspecting the coefficients. This can be achieved by choosing appropriate units in which to express the variables. The best units for this purpose center each variable at its mean and use its standard deviation as the unit of measurement. Explicitly, let the three means be $m_x, m_y,$ and $m_z$ and the three standard deviations be $s_x, s_y,$ and $s_z$. (It turns out not to matter whether you divide by $n$ or $n-1$ in computing the standard deviations. Just make sure you use a consistent convention when you compute any second moment of the data.) The values of the variables in these new units of measurement are $$\xi_i = \frac{x_i - m_x}{s_x},\ \eta_i = \frac{y_i - m_y}{s_y},\ \zeta_i = \frac{z_i - m_z}{s_z}.$$ This process is known as standardizing the data. The variables $\xi$, $\eta$, and $\zeta$ are the standardized versions of the original variables $x$, $y$, and $z$. These relationships are invertible: $$x_i = s_x \xi_i + m_x,\ y_i = s_y \eta_i + m_y,\ z_i = s_z \zeta_i + m_z.$$ Plugging these into the defining relationship $$\mathbb{E}(z_i) = C + Ax_i + By_i$$ and simplifying yields $$\mathbb{E}(s_z \zeta_i + m_z) = C + A(s_x \xi_i + m_x) + B(s_y \eta_i + m_y).$$ Solving for the expectation of the dependent variable $\zeta_i$ yields $$\mathbb{E}(\zeta_i) = \left(\frac{C + Am_x + Bm_y - m_z}{s_z}\right) + \left(\frac{A s_x}{s_z}\right) \xi_i + \left(\frac{B s_y}{s_z}\right) \eta_i.$$ If we write these coefficients as $\beta_0, \beta_1, \beta_2$ respectively, then we can recover $A, B, C$ by comparing and solving. For the record this gives $$A = \frac{s_z \beta_1}{s_x},\ B = \frac{s_z \beta_2}{s_y},\text{ and }C = s_z \beta_0 + m_z - A m_x - B m_y.\tag{2}$$ The point of this becomes apparent when we consider the new model matrix $$\Xi = \pmatrix{1 & \xi_1 & \eta_i \\ 1 & \xi_2 & \eta_2 \\ \vdots & \vdots & \vdots \\ 1 & \xi_n & \eta_n}$$ and the new response matrix $\zeta = (\zeta_1, \zeta_2, \ldots, \zeta_n)$, because now $$\Xi^\prime \Xi = \pmatrix{n & 0 & 0 \\ 0 & n & n\rho \\ 0 & n\rho & n}$$ and $$\Xi^\prime \zeta = (0, n\tau, n\upsilon)^\prime$$ where $\rho$ is the correlation coefficient $\frac{1}{n}\sum_{i=1}^n \xi_i \eta_i$, $\tau$ is the correlation coefficient $\frac{1}{n}\sum_{i=1}^n \xi_i \zeta_i$, and $\upsilon$ is the correlation coefficient $\frac{1}{n}\sum_{i=1}^n \eta_i \zeta_i$. To solve the normal equations $(1)$ we may divide both sides by $n$, giving $$\pmatrix{1 & 0 & 0 \\ 0 & 1 & \rho \\ 0 & \rho & 1}\pmatrix{\beta_0 \\ \beta_1 \\ \beta_2} = \pmatrix{0 \\ \tau \\ \upsilon} .$$ What originally looked like a formidable matrix formula has been reduced to a truly elementary set of three simultaneous equations. Provided $|\rho| \lt 1$, its solution is easily found to be $$\pmatrix{\hat\beta_0 \\ \hat\beta_1 \\ \hat\beta_2} = \frac{1}{1-\rho^2}\pmatrix{0 \\ \tau-\rho\upsilon \\ \upsilon-\rho\tau}.$$ Plugging these into the coefficients in $(2)$ produces the estimates $\hat A, \hat B,$ and $\hat C$. In fact, even more has been achieved: It is now evident why the cases $|\rho|=1$ are problematic: they introduce a divide-by-zero condition in the solution. It is equally evident how to determine whether a solution exists when $|\rho=1|$ and how to obtain it. It will exist when the second and third normal equations in $\Xi$ are redundant and it will be obtained simply by ignoring one of the variables $x$ and $y$ in the first place. We can derive some insight into the solution generally. For instance, from $\hat\beta_0=0$ in all cases, we may conclude that the fitted plane must pass through the point of averages $(m_x, m_y, m_z)$. It is now evident that the solution can be found in terms of the first two moments of the trivariate dataset $(x, y, z)$. This sheds further light on the fact that coefficient estimates can be found from means and covariance matrices alone. Furthermore, equation $(2)$ shows that the means are needed only to estimate the intercept term $C$. Estimates of the two slopes $A$ and $B$ require only the second moments. When the regressors are uncorrelated, $\rho=0$ and the solution is that the intercept is zero and the slopes are the correlation coefficients between the response $z$ and the regressors $x$ and $y$ when we standardize the data. This is both easy to remember and provides insight into how regression coefficients are related to correlation coefficients. Putting this all together, we find that (except in the degenerate cases $|\rho|=1$) the estimates can be written $$\eqalign{ \hat A &= \frac{\tau - \rho\upsilon}{1-\rho^2} \frac{s_z}{s_x} \\ \hat B &= \frac{\upsilon - \rho\tau}{1-\rho^2} \frac{s_z}{s_y} \\ \hat C &= m_z -m_x \hat A - m_y \hat B. }$$ In these formulae, the $m_{*}$ are the sample means, the $s_{*}$ are the sample standard deviations, and the greek letters $\rho, \tau,$ and $\upsilon$ represent the three correlation coefficients (between $x$ and $y$, $x$ and $z$, and $y$ and $z$, respectively). Please note that these formulas are not the best way to carry out the calculations. They all involve subtracting quantities that might be of comparable size, such as $\tau-\rho\upsilon$, $\upsilon-\rho\tau$, and $m_z - (-m_x \hat A - m_y \hat B)$. Such subtraction involves loss of precision. The matrix formulation allows numerical analysts to obtain more stable solutions that preserve as much precision as possible. This is why people rarely have any interest in term-by-term formulas. The other reason there is little interest is that as the number of regressors increases, the complexity of the formulas grows exponentially, quickly becoming too unwieldy. As further evidence of the correctness of these formulas, we may compare their answers to those of a standard least-squares solver, the lm function in R. # # Generate trivariate data. # library(MASS) set.seed(17) n <- 20 mu <- 1:3 Sigma <- matrix(1, 3, 3) Sigma[lower.tri(Sigma)] <- Sigma[upper.tri(Sigma)] <- c(.8, .5, .6) xyz <- data.frame(mvrnorm(n, mu, Sigma)) names(xyz) <- c("x", "y", "z") # # Obtain the least squares coefficients. # beta.hat <- coef(lm(z ~ x + y, xyz)) # # Compute the first two moments via `colMeans` and `cov`. # m <- colMeans(xyz) sigma <- cov(xyz) s <- sqrt(diag(sigma)) rho <- t(t(sigma/s)/s); rho <- as.vector(rho[lower.tri(rho)]) # # Here are the least squares coefficient estimates in terms of the moments. # A.hat <- (rho[2] - rho[1]*rho[3]) / (1 - rho[1]^2) * s[3] / s[1] B.hat <- (rho[3] - rho[1]*rho[2]) / (1 - rho[1]^2) * s[3] / s[2] C.hat <- m[3] - m[1]*A.hat - m[2]*B.hat # # Compare the two solutions. # rbind(beta.hat, formulae=c(C.hat, A.hat, B.hat)) The output exhibits two identical rows of estimates, as expected: (Intercept) x y beta.hat 1.522571 0.3013662 0.403636 formulae 1.522571 0.3013662 0.403636
Explicit solution for linear regression with two predictors Elsewhere on this site, explicit solutions to the ordinary least squares regression $$\mathbb{E}(z_i) = A x_i + B y_i + C$$ are available in matrix form as $$(C,A,B)^\prime = (X^\prime X)^{-1} X^\prim
30,372
Explicit solution for linear regression with two predictors
Found it... $$\begin{align}A&=\frac{(\overline{zx}-\bar z\bar x)(\overline{y^2}-\bar y^2)-(\overline{zy}-\bar z\bar y)(\overline{xy}-\bar x\bar y)}{(\overline{x^2}-\bar x^2)(\overline{y^2}-\bar y^2)-(\overline{xy}-\bar x\bar y)^2}\\ B&=\frac{(\overline{x^2}-\bar x^2)(\overline{zy}-\bar z\bar y)-(\overline{zx}-\bar z\bar x)(\overline{xy}-\bar x\bar y)}{(\overline{x^2}-\bar x^2)(\overline{y^2}-\bar y^2)-(\overline{xy}-\bar x\bar y)^2}\\ C&=\bar z-A\bar x-B\bar y.\end{align}$$
Explicit solution for linear regression with two predictors
Found it... $$\begin{align}A&=\frac{(\overline{zx}-\bar z\bar x)(\overline{y^2}-\bar y^2)-(\overline{zy}-\bar z\bar y)(\overline{xy}-\bar x\bar y)}{(\overline{x^2}-\bar x^2)(\overline{y^2}-\bar y^2)-(
Explicit solution for linear regression with two predictors Found it... $$\begin{align}A&=\frac{(\overline{zx}-\bar z\bar x)(\overline{y^2}-\bar y^2)-(\overline{zy}-\bar z\bar y)(\overline{xy}-\bar x\bar y)}{(\overline{x^2}-\bar x^2)(\overline{y^2}-\bar y^2)-(\overline{xy}-\bar x\bar y)^2}\\ B&=\frac{(\overline{x^2}-\bar x^2)(\overline{zy}-\bar z\bar y)-(\overline{zx}-\bar z\bar x)(\overline{xy}-\bar x\bar y)}{(\overline{x^2}-\bar x^2)(\overline{y^2}-\bar y^2)-(\overline{xy}-\bar x\bar y)^2}\\ C&=\bar z-A\bar x-B\bar y.\end{align}$$
Explicit solution for linear regression with two predictors Found it... $$\begin{align}A&=\frac{(\overline{zx}-\bar z\bar x)(\overline{y^2}-\bar y^2)-(\overline{zy}-\bar z\bar y)(\overline{xy}-\bar x\bar y)}{(\overline{x^2}-\bar x^2)(\overline{y^2}-\bar y^2)-(
30,373
Explicit solution for linear regression with two predictors
I was happy to find the @Mick's answer here but I was not happy that it is without derivation. It is difficult to believe a formula without derivation, so I decided to re-derive it in order to check if it is correct (e.g. if all signs are OK). In case, other people have the same feeling, this is my derivation. We need to find $A$, $B$, $C$ that minimize the sum of squared distances between the observed $z_i$ and $\hat z_i = Ax+By+C$. $$\min \sum_{i=1}^n \left(z_i-Ax_i-By_i-C\right)^2$$ $$\frac{\partial}{\partial C} \sum_{i=1}^n \left(z_i-Ax_i-By_i-C\right)^2 = 0 \Rightarrow C=\bar z - A \bar x - B \bar y$$ $$\frac{\partial}{\partial A} \sum_{i=1}^n \left(z_i-Ax_i-By_i-C\right)^2 = 0 \Rightarrow \overline{xz}-A\overline{x^2}-B\overline{xy}-C\bar x=0$$ $$\frac{\partial}{\partial B} \sum_{i=1}^n \left(z_i-Ax_i-By_i-C\right)^2 = 0 \Rightarrow \overline{zy}-A\overline{xy}-B\overline{y^2}-C\bar y=0$$ So, we have a system of linear equations for $A$, $B$, $C$: \begin{aligned} A \bar x + B \bar y + C &= \bar z\\ A\overline{x^2} + B\overline{xy} + C\bar x &= \overline{xz} \\ A\overline{xy} + B\overline{y^2} + C\bar y &= \overline{yz} \end{aligned} Its solution (Cramer's rule) is $A = \Delta_A/\Delta$, $B = \Delta_B/\Delta$, $C=\bar z - A \bar x - B \bar y$, where $$\Delta=\begin{vmatrix} \bar x & \bar y & 1 \\ \overline{x^2} & \overline{xy} & \bar x \\ \overline{xy} & \overline{y^2} & \bar y \notag \end{vmatrix}=(\overline{x^2}-\bar x^2)(\overline{y^2}-\bar y^2)-(\overline{xy}-\bar x \bar y)^2$$ $$\Delta_A=\begin{vmatrix} \bar z & \bar y & 1 \\ \overline{xz} & \overline{xy} & \bar x \\ \overline{yz} & \overline{y^2} & \bar y \notag \end{vmatrix}=(\overline{xz}-\bar x \bar z)(\overline{y^2}-\bar y^2)-(\overline{yz}-\bar y \bar z)(\overline{xy}-\bar x \bar y)$$ $$\Delta_B=\begin{vmatrix} \bar x & \bar z & 1 \\ \overline{x^2} & \overline{xz} & \bar x \\ \overline{xy} & \overline{yz} & \bar y \notag \end{vmatrix}=(\overline{yz}-\bar y \bar z)(\overline{x^2}-\bar x^2)-(\overline{xz}-\bar x \bar z)(\overline{xy}-\bar x \bar y)$$
Explicit solution for linear regression with two predictors
I was happy to find the @Mick's answer here but I was not happy that it is without derivation. It is difficult to believe a formula without derivation, so I decided to re-derive it in order to check i
Explicit solution for linear regression with two predictors I was happy to find the @Mick's answer here but I was not happy that it is without derivation. It is difficult to believe a formula without derivation, so I decided to re-derive it in order to check if it is correct (e.g. if all signs are OK). In case, other people have the same feeling, this is my derivation. We need to find $A$, $B$, $C$ that minimize the sum of squared distances between the observed $z_i$ and $\hat z_i = Ax+By+C$. $$\min \sum_{i=1}^n \left(z_i-Ax_i-By_i-C\right)^2$$ $$\frac{\partial}{\partial C} \sum_{i=1}^n \left(z_i-Ax_i-By_i-C\right)^2 = 0 \Rightarrow C=\bar z - A \bar x - B \bar y$$ $$\frac{\partial}{\partial A} \sum_{i=1}^n \left(z_i-Ax_i-By_i-C\right)^2 = 0 \Rightarrow \overline{xz}-A\overline{x^2}-B\overline{xy}-C\bar x=0$$ $$\frac{\partial}{\partial B} \sum_{i=1}^n \left(z_i-Ax_i-By_i-C\right)^2 = 0 \Rightarrow \overline{zy}-A\overline{xy}-B\overline{y^2}-C\bar y=0$$ So, we have a system of linear equations for $A$, $B$, $C$: \begin{aligned} A \bar x + B \bar y + C &= \bar z\\ A\overline{x^2} + B\overline{xy} + C\bar x &= \overline{xz} \\ A\overline{xy} + B\overline{y^2} + C\bar y &= \overline{yz} \end{aligned} Its solution (Cramer's rule) is $A = \Delta_A/\Delta$, $B = \Delta_B/\Delta$, $C=\bar z - A \bar x - B \bar y$, where $$\Delta=\begin{vmatrix} \bar x & \bar y & 1 \\ \overline{x^2} & \overline{xy} & \bar x \\ \overline{xy} & \overline{y^2} & \bar y \notag \end{vmatrix}=(\overline{x^2}-\bar x^2)(\overline{y^2}-\bar y^2)-(\overline{xy}-\bar x \bar y)^2$$ $$\Delta_A=\begin{vmatrix} \bar z & \bar y & 1 \\ \overline{xz} & \overline{xy} & \bar x \\ \overline{yz} & \overline{y^2} & \bar y \notag \end{vmatrix}=(\overline{xz}-\bar x \bar z)(\overline{y^2}-\bar y^2)-(\overline{yz}-\bar y \bar z)(\overline{xy}-\bar x \bar y)$$ $$\Delta_B=\begin{vmatrix} \bar x & \bar z & 1 \\ \overline{x^2} & \overline{xz} & \bar x \\ \overline{xy} & \overline{yz} & \bar y \notag \end{vmatrix}=(\overline{yz}-\bar y \bar z)(\overline{x^2}-\bar x^2)-(\overline{xz}-\bar x \bar z)(\overline{xy}-\bar x \bar y)$$
Explicit solution for linear regression with two predictors I was happy to find the @Mick's answer here but I was not happy that it is without derivation. It is difficult to believe a formula without derivation, so I decided to re-derive it in order to check i
30,374
Explicit solution for linear regression with two predictors
But you should have understood it! Take a look at your design matrix again (first equation page 4). Elements are written as (x,y). Element (3,1) = Element (1,3) Element (2,1) = Element (1,2) Element (3,2) = Element (2,3) and Element (3,3) is m. Your regular design matrix resolves to (all sums substituted) $$\left( {\begin{array}{*{20}{c}} K&L&M\\ L&R&S\\ M&S&m \end{array}} \right) $$ This actually makes solving mach easier, especially if you think a few more steps ahead. In case you have done that, bravo! In case you havent, you did not stare at the design matrix long enough.
Explicit solution for linear regression with two predictors
But you should have understood it! Take a look at your design matrix again (first equation page 4). Elements are written as (x,y). Element (3,1) = Element (1,3) Element (2,1) = Element (1,2) Element
Explicit solution for linear regression with two predictors But you should have understood it! Take a look at your design matrix again (first equation page 4). Elements are written as (x,y). Element (3,1) = Element (1,3) Element (2,1) = Element (1,2) Element (3,2) = Element (2,3) and Element (3,3) is m. Your regular design matrix resolves to (all sums substituted) $$\left( {\begin{array}{*{20}{c}} K&L&M\\ L&R&S\\ M&S&m \end{array}} \right) $$ This actually makes solving mach easier, especially if you think a few more steps ahead. In case you have done that, bravo! In case you havent, you did not stare at the design matrix long enough.
Explicit solution for linear regression with two predictors But you should have understood it! Take a look at your design matrix again (first equation page 4). Elements are written as (x,y). Element (3,1) = Element (1,3) Element (2,1) = Element (1,2) Element
30,375
Problem with proof - why exponentially smoothed time series is biased
Because this is a statistics site, let's develop a purely statistical solution. The first formula in the question correctly observes that $$\lambda + \lambda(1-\lambda)^1 + \lambda(1-\lambda)^2 + \lambda(1-\lambda)^3 + \cdots = 1,$$ implicitly assuming $|1-\lambda|\lt 1$. For real numbers $0 \lt \lambda \lt 1$, this exhibits $1$ as the sum of a series of non-negative values. That allows us to view these values as probabilities. (This particular set of numbers is a Geometric Distribution.) What could they be the probabilities of? Consider a long, wide rectangular dartboard. The $\lambda$eft portion, covering $\lambda$ of it, is colored red--this is what you would like to hit--while the right portion, covering the remaining $1-\lambda$ portion, is colored blue. You plan to throw darts at this board until one hits in the red. Suppose you are a poor dart shooter, just barely good enough to ensure the darts hit the board, but otherwise you have no control over where on the board they land. Let "$t$" stand for the number of tosses you make in toto. According to the axioms of probability, any sequence of $t\ge 1$ independent random dart tosses (each having an equal probability of hitting any part of the dartboard) that lands $t-1$ times in the blue and finally in the red has a chance of $$(1-\lambda)\cdots(1-\lambda)\lambda = (1-\lambda)^{t-1}\lambda$$ of occurring: this simply is the product of the individual chances, $1-\lambda$ for blue and $\lambda$ for red. These are the same probabilities as above. By definition, the expectation of the number of blue hits in such a sequence is the sum of the probability-weighted counts of blue hits; to wit, $$\lambda(1-\lambda)^0(0) + \lambda(1-\lambda)^1(1) + \lambda(1-\lambda)^2(2) + \cdots = \lambda\sum_{t=0}^\infty (1-\lambda)^t t.$$ Up to a factor of $\lambda$, this is what we would like to compute. The Weak Law of Large Numbers (which is intuitively obvious and first proved by Jakob Bernoulli in the late 17th century) tells us that the expectation can be achieved arbitrarily closely by conducting this experiment repeatedly, so let's do so. Throw the darts until one lands in the red. Let $b_1$ be the number that land in the blue. Let $b_2$ be the number in the blue during the second trial, and so on, up through $b_n$. In the figure, which shows the holes left when the darts were pulled out, $n=25$ trials have resulted in $100$ darts being thrown, of which $75$ landed in the blue. The mean number of blue hits in these trials is, by definition, $$\frac{1}{n}(b_1+b_2+\cdots+b_n) = \frac{b_1+b_2+\cdots+b_n}{1+1+\cdots+1}.$$ In other words, it's the ratio of the number of darts landing in the blue compared to those landing in the red. But because the darts land uniformly at random, in the limit this ratio must approach the ratio of blue to red areas, namely $(1-\lambda):\lambda$. Thus $$\lambda \sum_{t=0}^\infty (1-\lambda)^t t = \frac{1-\lambda}{\lambda}.$$ Dividing both sides by $\lambda$ gives the answer! This question might also benefit from some elementary mathematical answers. To that end, notice that whenever $|\lambda-1| \lt 1$, the series $$S(\lambda) = \sum_{t=0}^\infty (1-\lambda)^tt = (1-\lambda) + 2(1-\lambda)^2 + \cdots + t(1-\lambda)^t + \cdots$$ converges absolutely. (It eventually is dominated by a geometric series with common ratio less than $1$.) This implies we may freely re-arrange its terms when doing arithmetic with it, as in the following calculation: $$\eqalign{ \lambda S(\lambda) &= S(\lambda) - (1-\lambda)S(\lambda) \\ &= (1-\lambda) + 2(1-\lambda)^2 + 3(1-\lambda)^3 + \cdots - \left((1-\lambda)^2 + 2(1-\lambda)^3 + 3(1-\lambda)^4\cdots \right)\\ &= (1-\lambda) + (2-1)(1-\lambda)^2 + (3-2)(1-\lambda)^3 + \cdots \\ &= (1-\lambda)\left(1 + (1-\lambda)^1 + (1-\lambda)^2 + \cdots\right)\\ &= (1-\lambda)\sum_{t=0}^\infty (1-\lambda)^t \\ &= \frac{ 1 - \lambda }{\lambda}, }$$ as stated in the question. Because $|1-\lambda| \lt 1$, $\lambda$ is nonzero, so we may divide both sides by $\lambda$ to produce the equality $$S(\lambda) = \frac{1}{\lambda}\frac{ 1 - \lambda }{\lambda} = \frac{1-\lambda}{\lambda^2},$$ QED. Another solution notes that for integral $t \ge 1$, $$\binom{-2}{t-1} = \frac{-2(-3)\cdots(-2-(t-1)+1)}{1(2)(3)\cdots(t-1)} = \frac{(-1)^{t-1}t!}{(t-1)!} = (-1)^{t-1}t.$$ Recall the Binomial Theorem asserts that when $|x|\lt 1$ and $n$ is any number at all, then $$(1 + x)^n = \sum_{t=0}^\infty \binom{n}{t}x^t = \sum_{t=1}^\infty \binom{n}{t-1}x^{t-1}.$$ Taking $n=-2$ and $x=1-\lambda$ gives $$\frac{1-\lambda}{\lambda^2} = (1-\lambda)(1 - (1-\lambda))^{-2} = (1-\lambda)\sum_{t=1}^\infty \binom{-2}{t-1}(-(1-\lambda))^{t-1} = \sum_{t=0}^\infty (1-\lambda)^{t}t.$$
Problem with proof - why exponentially smoothed time series is biased
Because this is a statistics site, let's develop a purely statistical solution. The first formula in the question correctly observes that $$\lambda + \lambda(1-\lambda)^1 + \lambda(1-\lambda)^2 + \la
Problem with proof - why exponentially smoothed time series is biased Because this is a statistics site, let's develop a purely statistical solution. The first formula in the question correctly observes that $$\lambda + \lambda(1-\lambda)^1 + \lambda(1-\lambda)^2 + \lambda(1-\lambda)^3 + \cdots = 1,$$ implicitly assuming $|1-\lambda|\lt 1$. For real numbers $0 \lt \lambda \lt 1$, this exhibits $1$ as the sum of a series of non-negative values. That allows us to view these values as probabilities. (This particular set of numbers is a Geometric Distribution.) What could they be the probabilities of? Consider a long, wide rectangular dartboard. The $\lambda$eft portion, covering $\lambda$ of it, is colored red--this is what you would like to hit--while the right portion, covering the remaining $1-\lambda$ portion, is colored blue. You plan to throw darts at this board until one hits in the red. Suppose you are a poor dart shooter, just barely good enough to ensure the darts hit the board, but otherwise you have no control over where on the board they land. Let "$t$" stand for the number of tosses you make in toto. According to the axioms of probability, any sequence of $t\ge 1$ independent random dart tosses (each having an equal probability of hitting any part of the dartboard) that lands $t-1$ times in the blue and finally in the red has a chance of $$(1-\lambda)\cdots(1-\lambda)\lambda = (1-\lambda)^{t-1}\lambda$$ of occurring: this simply is the product of the individual chances, $1-\lambda$ for blue and $\lambda$ for red. These are the same probabilities as above. By definition, the expectation of the number of blue hits in such a sequence is the sum of the probability-weighted counts of blue hits; to wit, $$\lambda(1-\lambda)^0(0) + \lambda(1-\lambda)^1(1) + \lambda(1-\lambda)^2(2) + \cdots = \lambda\sum_{t=0}^\infty (1-\lambda)^t t.$$ Up to a factor of $\lambda$, this is what we would like to compute. The Weak Law of Large Numbers (which is intuitively obvious and first proved by Jakob Bernoulli in the late 17th century) tells us that the expectation can be achieved arbitrarily closely by conducting this experiment repeatedly, so let's do so. Throw the darts until one lands in the red. Let $b_1$ be the number that land in the blue. Let $b_2$ be the number in the blue during the second trial, and so on, up through $b_n$. In the figure, which shows the holes left when the darts were pulled out, $n=25$ trials have resulted in $100$ darts being thrown, of which $75$ landed in the blue. The mean number of blue hits in these trials is, by definition, $$\frac{1}{n}(b_1+b_2+\cdots+b_n) = \frac{b_1+b_2+\cdots+b_n}{1+1+\cdots+1}.$$ In other words, it's the ratio of the number of darts landing in the blue compared to those landing in the red. But because the darts land uniformly at random, in the limit this ratio must approach the ratio of blue to red areas, namely $(1-\lambda):\lambda$. Thus $$\lambda \sum_{t=0}^\infty (1-\lambda)^t t = \frac{1-\lambda}{\lambda}.$$ Dividing both sides by $\lambda$ gives the answer! This question might also benefit from some elementary mathematical answers. To that end, notice that whenever $|\lambda-1| \lt 1$, the series $$S(\lambda) = \sum_{t=0}^\infty (1-\lambda)^tt = (1-\lambda) + 2(1-\lambda)^2 + \cdots + t(1-\lambda)^t + \cdots$$ converges absolutely. (It eventually is dominated by a geometric series with common ratio less than $1$.) This implies we may freely re-arrange its terms when doing arithmetic with it, as in the following calculation: $$\eqalign{ \lambda S(\lambda) &= S(\lambda) - (1-\lambda)S(\lambda) \\ &= (1-\lambda) + 2(1-\lambda)^2 + 3(1-\lambda)^3 + \cdots - \left((1-\lambda)^2 + 2(1-\lambda)^3 + 3(1-\lambda)^4\cdots \right)\\ &= (1-\lambda) + (2-1)(1-\lambda)^2 + (3-2)(1-\lambda)^3 + \cdots \\ &= (1-\lambda)\left(1 + (1-\lambda)^1 + (1-\lambda)^2 + \cdots\right)\\ &= (1-\lambda)\sum_{t=0}^\infty (1-\lambda)^t \\ &= \frac{ 1 - \lambda }{\lambda}, }$$ as stated in the question. Because $|1-\lambda| \lt 1$, $\lambda$ is nonzero, so we may divide both sides by $\lambda$ to produce the equality $$S(\lambda) = \frac{1}{\lambda}\frac{ 1 - \lambda }{\lambda} = \frac{1-\lambda}{\lambda^2},$$ QED. Another solution notes that for integral $t \ge 1$, $$\binom{-2}{t-1} = \frac{-2(-3)\cdots(-2-(t-1)+1)}{1(2)(3)\cdots(t-1)} = \frac{(-1)^{t-1}t!}{(t-1)!} = (-1)^{t-1}t.$$ Recall the Binomial Theorem asserts that when $|x|\lt 1$ and $n$ is any number at all, then $$(1 + x)^n = \sum_{t=0}^\infty \binom{n}{t}x^t = \sum_{t=1}^\infty \binom{n}{t-1}x^{t-1}.$$ Taking $n=-2$ and $x=1-\lambda$ gives $$\frac{1-\lambda}{\lambda^2} = (1-\lambda)(1 - (1-\lambda))^{-2} = (1-\lambda)\sum_{t=1}^\infty \binom{-2}{t-1}(-(1-\lambda))^{t-1} = \sum_{t=0}^\infty (1-\lambda)^{t}t.$$
Problem with proof - why exponentially smoothed time series is biased Because this is a statistics site, let's develop a purely statistical solution. The first formula in the question correctly observes that $$\lambda + \lambda(1-\lambda)^1 + \lambda(1-\lambda)^2 + \la
30,376
Problem with proof - why exponentially smoothed time series is biased
If we assume that the derivative and the infinite sum may be interchanged, there is a quick way to arrive at your result. As @whuber pointed out, we require absolute convergence for this to be possible. This holds for the series in question when $|1-\lambda|<1$. We then have $$\sum_{t} t \left( 1-\lambda \right)^{t} = - \left(1-\lambda\right) \sum_{t} \frac{\partial}{\partial \lambda} \left(1-\lambda \right)^{t}$$ Notice that with the use of the derivative we get rid of $t$. You can verify that these expressions are equivalent. Now, $$\sum_{t} \frac{\partial}{\partial \lambda} \left(1-\lambda \right)^{t} = \frac{\partial}{\partial \lambda} \sum_{t} \left(1-\lambda \right)^{t} = \frac{\partial}{\partial \lambda} \frac{1}{\lambda} = -\frac{1}{\lambda^2} $$ under our assumptions. Multiply that by the factor we left out to get your result. EDIT: For completeness, here is the relevant theorem from Casella and Berger. It is easy to verify that the conditions apply here, thus we can take the derivative outside of the summation without any issues.
Problem with proof - why exponentially smoothed time series is biased
If we assume that the derivative and the infinite sum may be interchanged, there is a quick way to arrive at your result. As @whuber pointed out, we require absolute convergence for this to be possibl
Problem with proof - why exponentially smoothed time series is biased If we assume that the derivative and the infinite sum may be interchanged, there is a quick way to arrive at your result. As @whuber pointed out, we require absolute convergence for this to be possible. This holds for the series in question when $|1-\lambda|<1$. We then have $$\sum_{t} t \left( 1-\lambda \right)^{t} = - \left(1-\lambda\right) \sum_{t} \frac{\partial}{\partial \lambda} \left(1-\lambda \right)^{t}$$ Notice that with the use of the derivative we get rid of $t$. You can verify that these expressions are equivalent. Now, $$\sum_{t} \frac{\partial}{\partial \lambda} \left(1-\lambda \right)^{t} = \frac{\partial}{\partial \lambda} \sum_{t} \left(1-\lambda \right)^{t} = \frac{\partial}{\partial \lambda} \frac{1}{\lambda} = -\frac{1}{\lambda^2} $$ under our assumptions. Multiply that by the factor we left out to get your result. EDIT: For completeness, here is the relevant theorem from Casella and Berger. It is easy to verify that the conditions apply here, thus we can take the derivative outside of the summation without any issues.
Problem with proof - why exponentially smoothed time series is biased If we assume that the derivative and the infinite sum may be interchanged, there is a quick way to arrive at your result. As @whuber pointed out, we require absolute convergence for this to be possibl
30,377
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees
After some valuable remarks, I was able to find the solution: We have $f_X(x)=\frac{1}{B(1,K-1)} (1-x)^{K-2}$ and $f_Y(y)=\frac{1}{2^K \Gamma(K)} y^{K-1} e^{-y/2}$. Also, we have $0\le x\le 1$. Thus, if $x=\frac{z}{y}$, we get $0 \le \frac{z}{y} \le 1$ which implies that $z\le y \le \infty$. Hence: \begin{align} f_Z &= \int_{y=-\infty}^{y=+\infty}\frac{1}{|y|}f_Y(y) f_X \left (\frac{z}{y} \right ) dy \\ &= \int_{z}^{+\infty} \frac{1}{B(1,K-1)2^K \Gamma(K)} \frac{1}{y} y^{K-1} e^{-y/2} (1-z/y)^{K-2} dy \\ &= \frac{1}{B(1,K-1)2^K \Gamma(K)}\int_{z}^{+\infty} e^{-y/2} (y-z)^{K-2} dy \\ &=\frac{1}{B(1,K-1)2^K \Gamma(K)} \left[-2^{K-1}e^{-z/2}\Gamma(K-1,\frac{y-z}{2})\right]_z^\infty \\ &= \frac{2^{K-1}}{B(1,K-1)2^K \Gamma(K)} e^{-z/2} \Gamma(K-1) \\ &= \frac{1}{2} e^{-z/2} \end{align} where the last equality holds since $B(1,K-1)=\frac{\Gamma(1)\Gamma(K-1)}{\Gamma(K)}$. So $Z$ follows an exponential distribution of parameter $\frac{1}{2}$; or equivalently, $Z \sim\chi_2^2$.
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees
After some valuable remarks, I was able to find the solution: We have $f_X(x)=\frac{1}{B(1,K-1)} (1-x)^{K-2}$ and $f_Y(y)=\frac{1}{2^K \Gamma(K)} y^{K-1} e^{-y/2}$. Also, we have $0\le x\le 1$. Thus,
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees After some valuable remarks, I was able to find the solution: We have $f_X(x)=\frac{1}{B(1,K-1)} (1-x)^{K-2}$ and $f_Y(y)=\frac{1}{2^K \Gamma(K)} y^{K-1} e^{-y/2}$. Also, we have $0\le x\le 1$. Thus, if $x=\frac{z}{y}$, we get $0 \le \frac{z}{y} \le 1$ which implies that $z\le y \le \infty$. Hence: \begin{align} f_Z &= \int_{y=-\infty}^{y=+\infty}\frac{1}{|y|}f_Y(y) f_X \left (\frac{z}{y} \right ) dy \\ &= \int_{z}^{+\infty} \frac{1}{B(1,K-1)2^K \Gamma(K)} \frac{1}{y} y^{K-1} e^{-y/2} (1-z/y)^{K-2} dy \\ &= \frac{1}{B(1,K-1)2^K \Gamma(K)}\int_{z}^{+\infty} e^{-y/2} (y-z)^{K-2} dy \\ &=\frac{1}{B(1,K-1)2^K \Gamma(K)} \left[-2^{K-1}e^{-z/2}\Gamma(K-1,\frac{y-z}{2})\right]_z^\infty \\ &= \frac{2^{K-1}}{B(1,K-1)2^K \Gamma(K)} e^{-z/2} \Gamma(K-1) \\ &= \frac{1}{2} e^{-z/2} \end{align} where the last equality holds since $B(1,K-1)=\frac{\Gamma(1)\Gamma(K-1)}{\Gamma(K)}$. So $Z$ follows an exponential distribution of parameter $\frac{1}{2}$; or equivalently, $Z \sim\chi_2^2$.
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees After some valuable remarks, I was able to find the solution: We have $f_X(x)=\frac{1}{B(1,K-1)} (1-x)^{K-2}$ and $f_Y(y)=\frac{1}{2^K \Gamma(K)} y^{K-1} e^{-y/2}$. Also, we have $0\le x\le 1$. Thus,
30,378
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees
There is a pleasant, natural statistical solution to this problem for integral values of $K$, showing that the product has a $\chi^2(2)$ distribution. It relies only on well-known, easily established relationships among functions of standard normal variables. When $K$ is integral, a Beta$(1,K-1)$ distribution arises as the ratio $$\frac{X}{X+Z}$$ where $X$ and $Z$ are independent, $X$ has a $\chi^2(2)$ distribution, and $Z$ has a $\chi^2(2K-2)$ distribution. (See the Wikipedia article on the Beta distribution for instance.) Any $\chi^2(n)$ distribution is that of the sum of squares of $n$ independent standard Normal variates. Consequently, $X+Z$ is distributed as the squared length of a $2 + 2K-2 = 2K$ vector with a standard multinormal distribution in $\mathbb{R}^{2K}$ and $X/(X+Z)$ is the squared length of the first two components when that vector is radially projected to the unit sphere $S^{2K-1}$. The projection of a standard multinormal $n$-vector onto the unit sphere has a uniform distribution because the multinormal distribution is spherically symmetric. (That is, it is invariant under the orthogonal group, a result that follows immediately from two simple facts: (a), the orthogonal group fixes the origin and by definition does not change covariances; and (b) the mean and covariance completely determine the multivariate normal distribution. I illustrated this for the case $n=3$ at https://stats.stackexchange.com/a/7984). In fact, the spherical symmetry immediately shows this distribution is uniform conditional on the length of the original vector. The ratio $X/(X+Z)$ therefore is independent of the length. What all this implies is that multiplying $X/(X+Z)$ by an independent $\chi^2(2K)$ variable $Y$ creates a variable with the same distribution as $X/(X+Z)$ multiplied by $X+Z$; to wit, the distribution of $X$, which has a $\chi^2(2)$ distribution.
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees
There is a pleasant, natural statistical solution to this problem for integral values of $K$, showing that the product has a $\chi^2(2)$ distribution. It relies only on well-known, easily established
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees There is a pleasant, natural statistical solution to this problem for integral values of $K$, showing that the product has a $\chi^2(2)$ distribution. It relies only on well-known, easily established relationships among functions of standard normal variables. When $K$ is integral, a Beta$(1,K-1)$ distribution arises as the ratio $$\frac{X}{X+Z}$$ where $X$ and $Z$ are independent, $X$ has a $\chi^2(2)$ distribution, and $Z$ has a $\chi^2(2K-2)$ distribution. (See the Wikipedia article on the Beta distribution for instance.) Any $\chi^2(n)$ distribution is that of the sum of squares of $n$ independent standard Normal variates. Consequently, $X+Z$ is distributed as the squared length of a $2 + 2K-2 = 2K$ vector with a standard multinormal distribution in $\mathbb{R}^{2K}$ and $X/(X+Z)$ is the squared length of the first two components when that vector is radially projected to the unit sphere $S^{2K-1}$. The projection of a standard multinormal $n$-vector onto the unit sphere has a uniform distribution because the multinormal distribution is spherically symmetric. (That is, it is invariant under the orthogonal group, a result that follows immediately from two simple facts: (a), the orthogonal group fixes the origin and by definition does not change covariances; and (b) the mean and covariance completely determine the multivariate normal distribution. I illustrated this for the case $n=3$ at https://stats.stackexchange.com/a/7984). In fact, the spherical symmetry immediately shows this distribution is uniform conditional on the length of the original vector. The ratio $X/(X+Z)$ therefore is independent of the length. What all this implies is that multiplying $X/(X+Z)$ by an independent $\chi^2(2K)$ variable $Y$ creates a variable with the same distribution as $X/(X+Z)$ multiplied by $X+Z$; to wit, the distribution of $X$, which has a $\chi^2(2)$ distribution.
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees There is a pleasant, natural statistical solution to this problem for integral values of $K$, showing that the product has a $\chi^2(2)$ distribution. It relies only on well-known, easily established
30,379
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees
I greatly deprecate the commonly used tactic of finding the density of $Z = g(X,Y)$ by computing first computing the joint density of $Z$ and $X$ (or $Y$) because it is "easy" to use Jacobians, and then getting $f_Z$ as a marginal density (cf. Rusty Statistician's answer). It is much easier to find the CDF of $Z$ directly and then differentiate to find the pdf. This is the approach used below. $X$ and $Y$ are independent random variables with densities $f_X(x) = (K-1)(1-x)^{K-2}\mathbf 1_{(0,1)}(x)$ and $f_Y(y) = \frac{1}{2^K (K-1)!} y^{K-1} e^{-y/2}\mathbf 1_{(0,\infty)}(y)$. Then, with $Z = XY$, we have for $z > 0$, \begin{align} P\{Z > z\} &= P\{XY > z\}\\ &= \int_{y=z}^\infty \frac{1}{2^K (K-1)!} y^{K-1} e^{-y/2} \left[\int_{x=\frac{z}{y}}^1 (K-1)(1-x)^{K-2}\,\mathrm dx \right] \,\mathrm dy\\ &= \int_{y=z}^\infty \frac{1}{2^K (K-1)!} y^{K-1} e^{-y/2} \left(1-\frac{z}{y}\right)^{K-1}\,\mathrm dy\\ &= \int_{y=z}^\infty \frac{1}{2^K (K-1)!} (y-z)^{K-1} e^{-y/2} \,\mathrm dy\\ &= e^{-z/2}\int_0^\infty \frac{1}{2^K (K-1)!}t^{K-1} e^{-t/2} \,\mathrm dy~~~\scriptstyle{\text{on setting}~y-z = t}\\ &= e^{-z/2}\qquad\scriptstyle{\text{on noting that the integral is that of a Gamma pdf}}\\ \end{align} It is well-known that if $V \sim \mathsf{Exponential}(\lambda)$, then $P\{V > v\} = e^{-\lambda v}$. It follows that $Z = XY$ has an exponential density with parameter $\lambda = \frac 12$, which is also the $\chi^2(2)$ distribution.
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees
I greatly deprecate the commonly used tactic of finding the density of $Z = g(X,Y)$ by computing first computing the joint density of $Z$ and $X$ (or $Y$) because it is "easy" to use Jacobians, and th
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees I greatly deprecate the commonly used tactic of finding the density of $Z = g(X,Y)$ by computing first computing the joint density of $Z$ and $X$ (or $Y$) because it is "easy" to use Jacobians, and then getting $f_Z$ as a marginal density (cf. Rusty Statistician's answer). It is much easier to find the CDF of $Z$ directly and then differentiate to find the pdf. This is the approach used below. $X$ and $Y$ are independent random variables with densities $f_X(x) = (K-1)(1-x)^{K-2}\mathbf 1_{(0,1)}(x)$ and $f_Y(y) = \frac{1}{2^K (K-1)!} y^{K-1} e^{-y/2}\mathbf 1_{(0,\infty)}(y)$. Then, with $Z = XY$, we have for $z > 0$, \begin{align} P\{Z > z\} &= P\{XY > z\}\\ &= \int_{y=z}^\infty \frac{1}{2^K (K-1)!} y^{K-1} e^{-y/2} \left[\int_{x=\frac{z}{y}}^1 (K-1)(1-x)^{K-2}\,\mathrm dx \right] \,\mathrm dy\\ &= \int_{y=z}^\infty \frac{1}{2^K (K-1)!} y^{K-1} e^{-y/2} \left(1-\frac{z}{y}\right)^{K-1}\,\mathrm dy\\ &= \int_{y=z}^\infty \frac{1}{2^K (K-1)!} (y-z)^{K-1} e^{-y/2} \,\mathrm dy\\ &= e^{-z/2}\int_0^\infty \frac{1}{2^K (K-1)!}t^{K-1} e^{-t/2} \,\mathrm dy~~~\scriptstyle{\text{on setting}~y-z = t}\\ &= e^{-z/2}\qquad\scriptstyle{\text{on noting that the integral is that of a Gamma pdf}}\\ \end{align} It is well-known that if $V \sim \mathsf{Exponential}(\lambda)$, then $P\{V > v\} = e^{-\lambda v}$. It follows that $Z = XY$ has an exponential density with parameter $\lambda = \frac 12$, which is also the $\chi^2(2)$ distribution.
Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees I greatly deprecate the commonly used tactic of finding the density of $Z = g(X,Y)$ by computing first computing the joint density of $Z$ and $X$ (or $Y$) because it is "easy" to use Jacobians, and th
30,380
Linear combination of two kernel functions
A necessary and sufficient condition for a function $\kappa(\cdot,\cdot)$ to be expressible as an inner product in some feature space $\mathcal{F}$ is a weak form of Mercer's condition, namely that: $$ \int_\mathbf{x} \int_\mathbf{y} \kappa(\mathbf{x},\mathbf{y})g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y} \geq 0, $$ for all square, integrable functions $g(\cdot)$ [1,2]. In your case, this reduces to the following: $$ \begin{align} &\int_\mathbf{x} \int_\mathbf{y} \big(a_1\kappa_1(\mathbf{x},\mathbf{y}) + a_2 \kappa_2(\mathbf{x},\mathbf{y})\big)g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y} \\ &= a_1 \underbrace{\int_\mathbf{x} \int_\mathbf{y} \kappa_1(\mathbf{x},\mathbf{y})g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y}}_{\geq 0} + a_2 \underbrace{\int_\mathbf{x} \int_\mathbf{y}\kappa_2(\mathbf{x},\mathbf{y})g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y}}_{\geq 0} \geq 0. \end{align} $$ Since $\kappa_1(\cdot,\cdot)$ and $\kappa_2(\cdot,\cdot)$ are given to be kernel functions, their integrals both satisfy Mercer's condition. Finally, if $a_1 \geq 0$ and $a_2 \geq 0$, then the overall integral is guaranteed to satisfy it too. $\blacksquare$ Note that, as @Dougal correctly pointed out, it is still possible to get a valid kernel function with negative $a_1$ or $a_2$ (not both), but that depends on several factors. [1] Vladimir N. Vapnik. Statistical learning theory. Wiley, 1 edition, September 1998. [2] Richard Courant and David Hilbert. Methods of Mathematical Physics, volume 1. Interscience Publishers, Inc., New York, NY, 1953
Linear combination of two kernel functions
A necessary and sufficient condition for a function $\kappa(\cdot,\cdot)$ to be expressible as an inner product in some feature space $\mathcal{F}$ is a weak form of Mercer's condition, namely that: $
Linear combination of two kernel functions A necessary and sufficient condition for a function $\kappa(\cdot,\cdot)$ to be expressible as an inner product in some feature space $\mathcal{F}$ is a weak form of Mercer's condition, namely that: $$ \int_\mathbf{x} \int_\mathbf{y} \kappa(\mathbf{x},\mathbf{y})g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y} \geq 0, $$ for all square, integrable functions $g(\cdot)$ [1,2]. In your case, this reduces to the following: $$ \begin{align} &\int_\mathbf{x} \int_\mathbf{y} \big(a_1\kappa_1(\mathbf{x},\mathbf{y}) + a_2 \kappa_2(\mathbf{x},\mathbf{y})\big)g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y} \\ &= a_1 \underbrace{\int_\mathbf{x} \int_\mathbf{y} \kappa_1(\mathbf{x},\mathbf{y})g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y}}_{\geq 0} + a_2 \underbrace{\int_\mathbf{x} \int_\mathbf{y}\kappa_2(\mathbf{x},\mathbf{y})g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y}}_{\geq 0} \geq 0. \end{align} $$ Since $\kappa_1(\cdot,\cdot)$ and $\kappa_2(\cdot,\cdot)$ are given to be kernel functions, their integrals both satisfy Mercer's condition. Finally, if $a_1 \geq 0$ and $a_2 \geq 0$, then the overall integral is guaranteed to satisfy it too. $\blacksquare$ Note that, as @Dougal correctly pointed out, it is still possible to get a valid kernel function with negative $a_1$ or $a_2$ (not both), but that depends on several factors. [1] Vladimir N. Vapnik. Statistical learning theory. Wiley, 1 edition, September 1998. [2] Richard Courant and David Hilbert. Methods of Mathematical Physics, volume 1. Interscience Publishers, Inc., New York, NY, 1953
Linear combination of two kernel functions A necessary and sufficient condition for a function $\kappa(\cdot,\cdot)$ to be expressible as an inner product in some feature space $\mathcal{F}$ is a weak form of Mercer's condition, namely that: $
30,381
Linear combination of two kernel functions
As an alternative approach to Marc's: A symmetric function $k : \mathcal X \times \mathcal X \to \mathbb R$ is a kernel function iff there is some "feature map" $\varphi : \mathcal X \to \mathcal H$ such that $k(x, y) = \langle \varphi(x), \varphi(y) \rangle_{\mathcal H}$, where $\mathcal H$ is a Hilbert space. Let $\varphi_i$ be the feature map for $k_i$, and $\mathcal H_i$ its Hilbert space. Now, $\mathcal H_p := \mathcal H_1 \oplus \mathcal H_2$ is a Hilbert space, and $\varphi_p := \sqrt{a_1} \varphi_1 \oplus \sqrt{a_2} \varphi_2$ is a feature map from $\mathcal X$ to it as long as $a_1, a_2 \ge 0$. (For finite-dimensional feature spaces, this is just concatenating the feature maps together.) Note that \begin{align} \langle \varphi_p(x), \varphi_p(y) \rangle_{\mathcal H_p} &= \langle \sqrt{a_1} \varphi_1(x) \oplus \sqrt{a_2} \varphi_2(x), \sqrt{a_1} \varphi_1(y) \oplus \sqrt{a_2} \varphi_2(x) \rangle_{\mathcal H_1 \oplus \mathcal H_2} \\&= a_1 \langle \varphi_1(x), \varphi_1(y) \rangle_{\mathcal H_1} + a_2 \langle \varphi_2(x), \varphi_2(y) \rangle_{\mathcal H_2} \\&= k_p(x, y) ,\end{align} so $k_p$ has feature map $\varphi_p$, and is therefore a valid kernel. To your "in general" question at the end: if you want to prove them for arbitrary kernels, the two main techniques are the one Marc used and the one I used. Often, though, for Marc's approach we directly use the Mercer condition rather than the integral form, which can be easier to reason about: A symmetric function $k : \mathcal X \times \mathcal X \to \mathcal R$ is positive semidefinite if and only if for all $M$, all $x_1, \dots, x_M \in \mathcal X$, and all $c_1, \dots, c_M \in \mathbb R$, $\sum_{i=1}^M \sum_{j=1}^M c_i k(x_i, x_j) c_j \ge 0$. We can also use the following equivalent form: A symmetric function $k : \mathcal X \times \mathcal X \to \mathcal R$ is positive semidefinite if and only if for all $M$, all $x_1, \dots, x_M \in \mathcal X$, the matrix $K$ with $K_{ij} = k(x_i, x_j)$ is positive semidefinite. I previously gave brief proofs for several such properties in this answer.
Linear combination of two kernel functions
As an alternative approach to Marc's: A symmetric function $k : \mathcal X \times \mathcal X \to \mathbb R$ is a kernel function iff there is some "feature map" $\varphi : \mathcal X \to \mathcal H$ s
Linear combination of two kernel functions As an alternative approach to Marc's: A symmetric function $k : \mathcal X \times \mathcal X \to \mathbb R$ is a kernel function iff there is some "feature map" $\varphi : \mathcal X \to \mathcal H$ such that $k(x, y) = \langle \varphi(x), \varphi(y) \rangle_{\mathcal H}$, where $\mathcal H$ is a Hilbert space. Let $\varphi_i$ be the feature map for $k_i$, and $\mathcal H_i$ its Hilbert space. Now, $\mathcal H_p := \mathcal H_1 \oplus \mathcal H_2$ is a Hilbert space, and $\varphi_p := \sqrt{a_1} \varphi_1 \oplus \sqrt{a_2} \varphi_2$ is a feature map from $\mathcal X$ to it as long as $a_1, a_2 \ge 0$. (For finite-dimensional feature spaces, this is just concatenating the feature maps together.) Note that \begin{align} \langle \varphi_p(x), \varphi_p(y) \rangle_{\mathcal H_p} &= \langle \sqrt{a_1} \varphi_1(x) \oplus \sqrt{a_2} \varphi_2(x), \sqrt{a_1} \varphi_1(y) \oplus \sqrt{a_2} \varphi_2(x) \rangle_{\mathcal H_1 \oplus \mathcal H_2} \\&= a_1 \langle \varphi_1(x), \varphi_1(y) \rangle_{\mathcal H_1} + a_2 \langle \varphi_2(x), \varphi_2(y) \rangle_{\mathcal H_2} \\&= k_p(x, y) ,\end{align} so $k_p$ has feature map $\varphi_p$, and is therefore a valid kernel. To your "in general" question at the end: if you want to prove them for arbitrary kernels, the two main techniques are the one Marc used and the one I used. Often, though, for Marc's approach we directly use the Mercer condition rather than the integral form, which can be easier to reason about: A symmetric function $k : \mathcal X \times \mathcal X \to \mathcal R$ is positive semidefinite if and only if for all $M$, all $x_1, \dots, x_M \in \mathcal X$, and all $c_1, \dots, c_M \in \mathbb R$, $\sum_{i=1}^M \sum_{j=1}^M c_i k(x_i, x_j) c_j \ge 0$. We can also use the following equivalent form: A symmetric function $k : \mathcal X \times \mathcal X \to \mathcal R$ is positive semidefinite if and only if for all $M$, all $x_1, \dots, x_M \in \mathcal X$, the matrix $K$ with $K_{ij} = k(x_i, x_j)$ is positive semidefinite. I previously gave brief proofs for several such properties in this answer.
Linear combination of two kernel functions As an alternative approach to Marc's: A symmetric function $k : \mathcal X \times \mathcal X \to \mathbb R$ is a kernel function iff there is some "feature map" $\varphi : \mathcal X \to \mathcal H$ s
30,382
What is the difference between independent variable and a feature?
"Feature" and "independent variable" are different terms for the same thing. "Feature" is more common in machine learning, whereas "independent variable" is more common in statistics. So yes, in this case, TV is both a feature and an independent variable. Some more mostly equivalent terms are "covariate", "predictor", and "regression input". Editing four years later to add: some psychologists and other social scientists reserve the term "independent variable" for a variable that has been randomly assigned or otherwise manipulated by the experimenter. "Predictor" or another word is then used for the other variables. But statisticians don't usually restrict the word like this.
What is the difference between independent variable and a feature?
"Feature" and "independent variable" are different terms for the same thing. "Feature" is more common in machine learning, whereas "independent variable" is more common in statistics. So yes, in this
What is the difference between independent variable and a feature? "Feature" and "independent variable" are different terms for the same thing. "Feature" is more common in machine learning, whereas "independent variable" is more common in statistics. So yes, in this case, TV is both a feature and an independent variable. Some more mostly equivalent terms are "covariate", "predictor", and "regression input". Editing four years later to add: some psychologists and other social scientists reserve the term "independent variable" for a variable that has been randomly assigned or otherwise manipulated by the experimenter. "Predictor" or another word is then used for the other variables. But statisticians don't usually restrict the word like this.
What is the difference between independent variable and a feature? "Feature" and "independent variable" are different terms for the same thing. "Feature" is more common in machine learning, whereas "independent variable" is more common in statistics. So yes, in this
30,383
What is the difference between independent variable and a feature?
It seems that the terms are used interchangeably, however, I found this explanation on a paper that used both: We call “variable” the “raw” input variables and “features” variables constructed for the input variables. We use without distinction the terms “variable” and “feature” when there is no impact on the selection algorithms, e.g., when features resulting from a pre-processing of input variables are explicitly computed. The distinction is necessary in the case of kernel methods for which features are not explicitly computed The usage mentioned here seems to be specific to the paper, so confirming that the two terms are synonyms. link to paper Guyon & Elisseeff - An Introduction to Variable and Feature Selection - Journal of Machine Learning Research 3 (2003) 1157-1182
What is the difference between independent variable and a feature?
It seems that the terms are used interchangeably, however, I found this explanation on a paper that used both: We call “variable” the “raw” input variables and “features” variables constructed for th
What is the difference between independent variable and a feature? It seems that the terms are used interchangeably, however, I found this explanation on a paper that used both: We call “variable” the “raw” input variables and “features” variables constructed for the input variables. We use without distinction the terms “variable” and “feature” when there is no impact on the selection algorithms, e.g., when features resulting from a pre-processing of input variables are explicitly computed. The distinction is necessary in the case of kernel methods for which features are not explicitly computed The usage mentioned here seems to be specific to the paper, so confirming that the two terms are synonyms. link to paper Guyon & Elisseeff - An Introduction to Variable and Feature Selection - Journal of Machine Learning Research 3 (2003) 1157-1182
What is the difference between independent variable and a feature? It seems that the terms are used interchangeably, however, I found this explanation on a paper that used both: We call “variable” the “raw” input variables and “features” variables constructed for th
30,384
What is the difference between independent variable and a feature?
Take the example of a house - We want to build a model to calculate the price of the house based on certain criteria such as location, area (size), age, etc. Feature - all "input" to the model Variables - all Features + Price (the output). In essence, Features (input variables) + output variable(s) of a model = Variables
What is the difference between independent variable and a feature?
Take the example of a house - We want to build a model to calculate the price of the house based on certain criteria such as location, area (size), age, etc. Feature - all "input" to the model Variabl
What is the difference between independent variable and a feature? Take the example of a house - We want to build a model to calculate the price of the house based on certain criteria such as location, area (size), age, etc. Feature - all "input" to the model Variables - all Features + Price (the output). In essence, Features (input variables) + output variable(s) of a model = Variables
What is the difference between independent variable and a feature? Take the example of a house - We want to build a model to calculate the price of the house based on certain criteria such as location, area (size), age, etc. Feature - all "input" to the model Variabl
30,385
What is the difference between independent variable and a feature?
Inputs can be considered as raw data like number of bathrooms,number of bedrooms whereas features are considered as some function of input like for example feature can be simply number of bathrooms or product of number of bathrooms and number of bedrooms
What is the difference between independent variable and a feature?
Inputs can be considered as raw data like number of bathrooms,number of bedrooms whereas features are considered as some function of input like for example feature can be simply number of bathrooms or
What is the difference between independent variable and a feature? Inputs can be considered as raw data like number of bathrooms,number of bedrooms whereas features are considered as some function of input like for example feature can be simply number of bathrooms or product of number of bathrooms and number of bedrooms
What is the difference between independent variable and a feature? Inputs can be considered as raw data like number of bathrooms,number of bedrooms whereas features are considered as some function of input like for example feature can be simply number of bathrooms or
30,386
What is the difference between independent variable and a feature?
Features are different from variables to the extent that features methodologically precede variables. When algorithms are being used to identify potential variables within unstructured data, for example, the inputs (features:) cannot accurately be called variables.
What is the difference between independent variable and a feature?
Features are different from variables to the extent that features methodologically precede variables. When algorithms are being used to identify potential variables within unstructured data, for examp
What is the difference between independent variable and a feature? Features are different from variables to the extent that features methodologically precede variables. When algorithms are being used to identify potential variables within unstructured data, for example, the inputs (features:) cannot accurately be called variables.
What is the difference between independent variable and a feature? Features are different from variables to the extent that features methodologically precede variables. When algorithms are being used to identify potential variables within unstructured data, for examp
30,387
Forecast accuracy calculation
There are many different ways of measuring forecast accuracy, and the accuracy() function from the forecast package for R outputs several of them. From your comment about "% of deviation" it sounds like you want to use Mean Absolute Percentage Error, which is one of the measures provided by accuracy(). The most common measures of forecast accuracy are discussed here. You might like to think about whether MAPE is the most appropriate measure for your problem, or whether one of the other measures is better. The accuracy() function does work on real data. The "test data" are those data that were not used to construct the forecasts. Sometimes they are available but not used when the forecasts are computed (the classical split of data into training and test sets). In other situations, all the available data are used to compute the forecasts, and then you have to wait until there are some future observations available to use as the test data. So if f is a vector of forecasts and x is a vector of observations corresponding to the same times, then accuracy(f,x) will do what you want.
Forecast accuracy calculation
There are many different ways of measuring forecast accuracy, and the accuracy() function from the forecast package for R outputs several of them. From your comment about "% of deviation" it sounds li
Forecast accuracy calculation There are many different ways of measuring forecast accuracy, and the accuracy() function from the forecast package for R outputs several of them. From your comment about "% of deviation" it sounds like you want to use Mean Absolute Percentage Error, which is one of the measures provided by accuracy(). The most common measures of forecast accuracy are discussed here. You might like to think about whether MAPE is the most appropriate measure for your problem, or whether one of the other measures is better. The accuracy() function does work on real data. The "test data" are those data that were not used to construct the forecasts. Sometimes they are available but not used when the forecasts are computed (the classical split of data into training and test sets). In other situations, all the available data are used to compute the forecasts, and then you have to wait until there are some future observations available to use as the test data. So if f is a vector of forecasts and x is a vector of observations corresponding to the same times, then accuracy(f,x) will do what you want.
Forecast accuracy calculation There are many different ways of measuring forecast accuracy, and the accuracy() function from the forecast package for R outputs several of them. From your comment about "% of deviation" it sounds li
30,388
Forecast accuracy calculation
First, let's clarify that there are concepts of accuracy and precision. Accuracy is usually associated with a bias, i.e. systematic deviation of the forecast from the actuals. Precision is usually associated with the variance of the forecast errors. Something like this: $Accuracy=E(f)-y$ vs. $Precision=Var[f-y]$. So, when you mention "accuracy" in your post, were aware of the distinction? Second, there are integrated measures of forecast quality, such as $MSFE=\frac{1}{n}\sum_{i=1}^n(f_i-y_i)^2$, where $f_i$ and $y_i$ are forecasts and actuals. There are statistics for this measure, such as Chow test for parameter constancy.
Forecast accuracy calculation
First, let's clarify that there are concepts of accuracy and precision. Accuracy is usually associated with a bias, i.e. systematic deviation of the forecast from the actuals. Precision is usually ass
Forecast accuracy calculation First, let's clarify that there are concepts of accuracy and precision. Accuracy is usually associated with a bias, i.e. systematic deviation of the forecast from the actuals. Precision is usually associated with the variance of the forecast errors. Something like this: $Accuracy=E(f)-y$ vs. $Precision=Var[f-y]$. So, when you mention "accuracy" in your post, were aware of the distinction? Second, there are integrated measures of forecast quality, such as $MSFE=\frac{1}{n}\sum_{i=1}^n(f_i-y_i)^2$, where $f_i$ and $y_i$ are forecasts and actuals. There are statistics for this measure, such as Chow test for parameter constancy.
Forecast accuracy calculation First, let's clarify that there are concepts of accuracy and precision. Accuracy is usually associated with a bias, i.e. systematic deviation of the forecast from the actuals. Precision is usually ass
30,389
Forecast accuracy calculation
I have been doing this in R here is my code for my data for both in-sample and out-of-sample data: #accuracy testing for out-of-sample sample# M<-#data# deltaT<-#set observations per year,1/4 for quarterly, 1/12 for monthly horiz<-#set amount of forecasts required startY<-c(#,#) #set start date N<-head(M,-horiz) Nu<-log(Nu) Nu<-ts(Nu,deltat=deltaT,start=startY) #Run your forecasting method# ##My forecasting method is arima## N<-#data# N<-ts(N,deltat=deltaT,start=startY) N<-tail(N,horiz) fitted<-ts(append(fitted(Arimab), fArimab$mean[1]), deltat=deltaT, start = startY) #where Arimab is the ARIMA model and fArimab<-forecast(Arimab, h=horiz*2, simulate= TRUE, fan=TRUE) N<-log(N) fitted<-head(fitted,length(N)) error<-N-fitted percenterror<-100*error/N plus<-N+fitted rmse<-function(error) sqrt(mean(error^2)) mae<-function(error) mean(abs(error)) mape<-function(percenterror) mean(abs(percenterror)) smape<-function(error,plus) mean(200*abs(error)/(plus)) mse<-function(error) mean(error^2) me<-function(error) mean(error) mpe<-function(percenterror) mean(percenterror) accuracy<-matrix(c("rmse","mae","mape","smape","mse","me","mpe",(round(rmse(error),digits=3)),(round(mae(error),digits=3)),(round(mape(percenterror),digits=3)),(round(smape(error,plus),digits=3)),(round(mse(error),digits=3)),(round(me(error),digits=3)),(round(mpe(percenterror),digits=3))),ncol=2,byrow=FALSE) View(accuracy,title="Accuracy of ARIMA out sample") #Accuracy testing for the in sample M<-#data# deltaT<-#set observations per year,1/4 for quarterly, 1/12 for monthly horiz<-#set amount of forecasts required startY<-c(#,#) #set start date Nu<-log(Nu) Nu<-ts(Nu,deltat=deltaT,start=startY) #run your forecasting method# fitted<-ts(append(fitted(Arimab), fArimab$mean[1]), deltat=deltaT, start = startY) N<-exp(Nu) fitted<-exp(fitted) fitted<-head(fitted,length(N)) error<-N-fitted percenterror<-100*error/N plus<-N+fitted rmse<-function(error) sqrt(mean(error^2)) mae<-function(error) mean(abs(error)) mape<-function(percenterror) mean(abs(percenterror)) smape<-function(error,plus) mean(200*abs(error)/(plus)) mse<-function(error) mean(error^2) me<-function(error) mean(error) mpe<-function(percenterror) mean(percenterror) accuracy<-matrix(c("rmse","mae","mape","smape","mse","me","mpe",(round(rmse(error),digits=3)),(round(mae(error),digits=3)),(round(mape(percenterror),digits=3)),(round(smape(error,plus),digits=3)),(round(mse(error),digits=3)),(round(me(error),digits=3)),(round(mpe(percenterror),digits=3))),ncol=2,byrow=FALSE) View(accuracy,title="Accuracy of ARIMA in sample") hope this helps a bit. if you want my full code i used to run this please ask as this is very basic
Forecast accuracy calculation
I have been doing this in R here is my code for my data for both in-sample and out-of-sample data: #accuracy testing for out-of-sample sample# M<-#data# deltaT<-#set observations per year,1/4 for qua
Forecast accuracy calculation I have been doing this in R here is my code for my data for both in-sample and out-of-sample data: #accuracy testing for out-of-sample sample# M<-#data# deltaT<-#set observations per year,1/4 for quarterly, 1/12 for monthly horiz<-#set amount of forecasts required startY<-c(#,#) #set start date N<-head(M,-horiz) Nu<-log(Nu) Nu<-ts(Nu,deltat=deltaT,start=startY) #Run your forecasting method# ##My forecasting method is arima## N<-#data# N<-ts(N,deltat=deltaT,start=startY) N<-tail(N,horiz) fitted<-ts(append(fitted(Arimab), fArimab$mean[1]), deltat=deltaT, start = startY) #where Arimab is the ARIMA model and fArimab<-forecast(Arimab, h=horiz*2, simulate= TRUE, fan=TRUE) N<-log(N) fitted<-head(fitted,length(N)) error<-N-fitted percenterror<-100*error/N plus<-N+fitted rmse<-function(error) sqrt(mean(error^2)) mae<-function(error) mean(abs(error)) mape<-function(percenterror) mean(abs(percenterror)) smape<-function(error,plus) mean(200*abs(error)/(plus)) mse<-function(error) mean(error^2) me<-function(error) mean(error) mpe<-function(percenterror) mean(percenterror) accuracy<-matrix(c("rmse","mae","mape","smape","mse","me","mpe",(round(rmse(error),digits=3)),(round(mae(error),digits=3)),(round(mape(percenterror),digits=3)),(round(smape(error,plus),digits=3)),(round(mse(error),digits=3)),(round(me(error),digits=3)),(round(mpe(percenterror),digits=3))),ncol=2,byrow=FALSE) View(accuracy,title="Accuracy of ARIMA out sample") #Accuracy testing for the in sample M<-#data# deltaT<-#set observations per year,1/4 for quarterly, 1/12 for monthly horiz<-#set amount of forecasts required startY<-c(#,#) #set start date Nu<-log(Nu) Nu<-ts(Nu,deltat=deltaT,start=startY) #run your forecasting method# fitted<-ts(append(fitted(Arimab), fArimab$mean[1]), deltat=deltaT, start = startY) N<-exp(Nu) fitted<-exp(fitted) fitted<-head(fitted,length(N)) error<-N-fitted percenterror<-100*error/N plus<-N+fitted rmse<-function(error) sqrt(mean(error^2)) mae<-function(error) mean(abs(error)) mape<-function(percenterror) mean(abs(percenterror)) smape<-function(error,plus) mean(200*abs(error)/(plus)) mse<-function(error) mean(error^2) me<-function(error) mean(error) mpe<-function(percenterror) mean(percenterror) accuracy<-matrix(c("rmse","mae","mape","smape","mse","me","mpe",(round(rmse(error),digits=3)),(round(mae(error),digits=3)),(round(mape(percenterror),digits=3)),(round(smape(error,plus),digits=3)),(round(mse(error),digits=3)),(round(me(error),digits=3)),(round(mpe(percenterror),digits=3))),ncol=2,byrow=FALSE) View(accuracy,title="Accuracy of ARIMA in sample") hope this helps a bit. if you want my full code i used to run this please ask as this is very basic
Forecast accuracy calculation I have been doing this in R here is my code for my data for both in-sample and out-of-sample data: #accuracy testing for out-of-sample sample# M<-#data# deltaT<-#set observations per year,1/4 for qua
30,390
Forecast accuracy calculation
The short answer: to evaluate the quality of your predictions, use exactly the same measure that you used in the training (fitting) of your model. The long answer: In order to chose a measure for the accuracy of your forecasts, your first need to know how you interpret you predictions. In other words, what do you actually give as a "forecast"? Is it mean value? Median? Most probable value? The answer on this question will uniquely identify the measure of the forecast accuracy. If you predict mean, you have to use the root mean square deviation as the measure of the forecast accuracy. If you predict median you have to use mean absolute deviation as the measure of accuracy. I will elaborate a bit on this point. Let us assume that you make a prediction / forecast for tomorrow. Let us also assume that for any value that you might observe tomorrow you have a corresponding probability to be observed. For example you know that you might observe 1 with probability 0.03, 2 with probability 0.07, 3 with probability 0.11, and so on. So, you have a distribution of probabilities over different values. Having this distribution you can calculate different properties and give them as your "predictions". You can calculate mean and give it as the prediction for tomorrow. Alternatively you can use median as your prediction. You can also find the most probable value and give it as your prediction for tomorrow. If you use mean value as prediction, than the question of "how to measure the accuracy of my prediction" has to be replaced by "what is the measure of the accuracy for the mean" and the answer is "root mean square deviation between the real values and prediction". If you use median as predictions, you have to use mean absolute deviation. It might be that you do not know if you use median or mean or something else. To find out what you actually use as predictions you have to know what measure you try to minimize in the training. If you try to find parameters of the model that minimize root mean square deviation between the predictions and target values from the training data, then your predictions have to be treated as mean. If you minimize absolute deviations, then you train your model to provide medians and so on. ADDED I would like to emphasize one thing. As I have mentioned above it is important to keep the same measure of accuracy in "fit" and in "predict". In addition to that I would like to say that you are absolutely free in choosing your measures. There are no "better" or "worse" measures. The measure should be determined by the way you (or your client) use your predictions. For example it might be very important (to you or your client) to have an exact match and if you do not have it, it does not play any role if the difference between the real and predicted values is big or small. In other cases this difference plays a role. Difference of 1 is better than difference of 2. In some cases difference of 2 is 2 time worse than difference of 1. In other cases difference equal to 2 is 100 times worse than difference equal to 1. You can also imagine exotic cases in which you need to generate a value that differs from observations. So, measure of quality of the numbers that you generate can be whatever you want, depending on what you need. What is important, is to use the same measure in training (fit) and evaluation of predictions.
Forecast accuracy calculation
The short answer: to evaluate the quality of your predictions, use exactly the same measure that you used in the training (fitting) of your model. The long answer: In order to chose a measure for the
Forecast accuracy calculation The short answer: to evaluate the quality of your predictions, use exactly the same measure that you used in the training (fitting) of your model. The long answer: In order to chose a measure for the accuracy of your forecasts, your first need to know how you interpret you predictions. In other words, what do you actually give as a "forecast"? Is it mean value? Median? Most probable value? The answer on this question will uniquely identify the measure of the forecast accuracy. If you predict mean, you have to use the root mean square deviation as the measure of the forecast accuracy. If you predict median you have to use mean absolute deviation as the measure of accuracy. I will elaborate a bit on this point. Let us assume that you make a prediction / forecast for tomorrow. Let us also assume that for any value that you might observe tomorrow you have a corresponding probability to be observed. For example you know that you might observe 1 with probability 0.03, 2 with probability 0.07, 3 with probability 0.11, and so on. So, you have a distribution of probabilities over different values. Having this distribution you can calculate different properties and give them as your "predictions". You can calculate mean and give it as the prediction for tomorrow. Alternatively you can use median as your prediction. You can also find the most probable value and give it as your prediction for tomorrow. If you use mean value as prediction, than the question of "how to measure the accuracy of my prediction" has to be replaced by "what is the measure of the accuracy for the mean" and the answer is "root mean square deviation between the real values and prediction". If you use median as predictions, you have to use mean absolute deviation. It might be that you do not know if you use median or mean or something else. To find out what you actually use as predictions you have to know what measure you try to minimize in the training. If you try to find parameters of the model that minimize root mean square deviation between the predictions and target values from the training data, then your predictions have to be treated as mean. If you minimize absolute deviations, then you train your model to provide medians and so on. ADDED I would like to emphasize one thing. As I have mentioned above it is important to keep the same measure of accuracy in "fit" and in "predict". In addition to that I would like to say that you are absolutely free in choosing your measures. There are no "better" or "worse" measures. The measure should be determined by the way you (or your client) use your predictions. For example it might be very important (to you or your client) to have an exact match and if you do not have it, it does not play any role if the difference between the real and predicted values is big or small. In other cases this difference plays a role. Difference of 1 is better than difference of 2. In some cases difference of 2 is 2 time worse than difference of 1. In other cases difference equal to 2 is 100 times worse than difference equal to 1. You can also imagine exotic cases in which you need to generate a value that differs from observations. So, measure of quality of the numbers that you generate can be whatever you want, depending on what you need. What is important, is to use the same measure in training (fit) and evaluation of predictions.
Forecast accuracy calculation The short answer: to evaluate the quality of your predictions, use exactly the same measure that you used in the training (fitting) of your model. The long answer: In order to chose a measure for the
30,391
How to prepare interactions of categorical variables in scikit-learn?
Indeed you can use Patsy with scikit-learn to obtain the same results you would obtain with R, or with the formula notation in stats models. See code below: from patsy import dmatrices # create dummy variables, and their interactions y, X = dmatrices('depvar ~ C(var1)*C(var2)', df, return_type="dataframe") # flatten y into a 1-D array so scikit-learn can understand it y = np.ravel(y) you can now use any model implemented in scikit-learn with the usual notations having X as independent variables, and y as dependent one.
How to prepare interactions of categorical variables in scikit-learn?
Indeed you can use Patsy with scikit-learn to obtain the same results you would obtain with R, or with the formula notation in stats models. See code below: from patsy import dmatrices # create dummy
How to prepare interactions of categorical variables in scikit-learn? Indeed you can use Patsy with scikit-learn to obtain the same results you would obtain with R, or with the formula notation in stats models. See code below: from patsy import dmatrices # create dummy variables, and their interactions y, X = dmatrices('depvar ~ C(var1)*C(var2)', df, return_type="dataframe") # flatten y into a 1-D array so scikit-learn can understand it y = np.ravel(y) you can now use any model implemented in scikit-learn with the usual notations having X as independent variables, and y as dependent one.
How to prepare interactions of categorical variables in scikit-learn? Indeed you can use Patsy with scikit-learn to obtain the same results you would obtain with R, or with the formula notation in stats models. See code below: from patsy import dmatrices # create dummy
30,392
How to prepare interactions of categorical variables in scikit-learn?
Use Patsy. Patsy is one of my favourite Python libraries: it does one thing, and only one thing, really really well.
How to prepare interactions of categorical variables in scikit-learn?
Use Patsy. Patsy is one of my favourite Python libraries: it does one thing, and only one thing, really really well.
How to prepare interactions of categorical variables in scikit-learn? Use Patsy. Patsy is one of my favourite Python libraries: it does one thing, and only one thing, really really well.
How to prepare interactions of categorical variables in scikit-learn? Use Patsy. Patsy is one of my favourite Python libraries: it does one thing, and only one thing, really really well.
30,393
Data Setup for Differences-in-Differences
A key assumption of difference-in-differences (DID) is that both groups have a common trend in the outcome variable before the treatment. This is important in order to make the argument that the change for the treated group is because of the treatment and not because the two groups were already different from each other to begin with. If you sample different people before and after the treatment this will weaken the argument unless your samples from the treatment and control groups are actually random and large. So it well might happen that somebody is going to ask you: "How can you make sure that the effect is due to the treatment and not just because you sampled different people?" - and that will be difficult to answer. This question you can avoid by using panel data because there you track the same statistical units over time and generally this is the more solid approach. To answer your last question: yes the data matters but you can surely use OLS to estimate your equation above. An important thing which in the past was often overlooked is the correct estimation of the standard errors. If you don't correct them, serial correlation will underestimate them by a good amount and you will find significant effects even though you probably shouldn't. As a reference and suggestions for how to deal with this problem see Bertrand et al. (2004) "How Much Should We Trust Differences-In-Differences Estimates?". As a last thing, if you have aggregate data (e.g. at the state level) or if you can easily aggregate yours and if you want to use a more recent econometric method than DID, you might want to have a look at Abadie et al. (2010) "Synthetic Control Methods for Comparative Case Studies". The synthetic control method is increasingly used in nowadays research and there exist well documented routines for R and Stata. Maybe this is something interesting for you as well.
Data Setup for Differences-in-Differences
A key assumption of difference-in-differences (DID) is that both groups have a common trend in the outcome variable before the treatment. This is important in order to make the argument that the chang
Data Setup for Differences-in-Differences A key assumption of difference-in-differences (DID) is that both groups have a common trend in the outcome variable before the treatment. This is important in order to make the argument that the change for the treated group is because of the treatment and not because the two groups were already different from each other to begin with. If you sample different people before and after the treatment this will weaken the argument unless your samples from the treatment and control groups are actually random and large. So it well might happen that somebody is going to ask you: "How can you make sure that the effect is due to the treatment and not just because you sampled different people?" - and that will be difficult to answer. This question you can avoid by using panel data because there you track the same statistical units over time and generally this is the more solid approach. To answer your last question: yes the data matters but you can surely use OLS to estimate your equation above. An important thing which in the past was often overlooked is the correct estimation of the standard errors. If you don't correct them, serial correlation will underestimate them by a good amount and you will find significant effects even though you probably shouldn't. As a reference and suggestions for how to deal with this problem see Bertrand et al. (2004) "How Much Should We Trust Differences-In-Differences Estimates?". As a last thing, if you have aggregate data (e.g. at the state level) or if you can easily aggregate yours and if you want to use a more recent econometric method than DID, you might want to have a look at Abadie et al. (2010) "Synthetic Control Methods for Comparative Case Studies". The synthetic control method is increasingly used in nowadays research and there exist well documented routines for R and Stata. Maybe this is something interesting for you as well.
Data Setup for Differences-in-Differences A key assumption of difference-in-differences (DID) is that both groups have a common trend in the outcome variable before the treatment. This is important in order to make the argument that the chang
30,394
Do we need to worry about outliers when using rank-based tests?
No. When the data are ranked, an outlier will simply be recognized as a case that is ranked one above (or below) the next less extreme case. Regardless of whether there is .01 or 5 standard deviations between the most and second most extreme value, that degree of difference is thrown away when data are ranked. In fact, one of the many reasons why someone might use a rank-based (or nonparametric) test is because of outliers.
Do we need to worry about outliers when using rank-based tests?
No. When the data are ranked, an outlier will simply be recognized as a case that is ranked one above (or below) the next less extreme case. Regardless of whether there is .01 or 5 standard deviations
Do we need to worry about outliers when using rank-based tests? No. When the data are ranked, an outlier will simply be recognized as a case that is ranked one above (or below) the next less extreme case. Regardless of whether there is .01 or 5 standard deviations between the most and second most extreme value, that degree of difference is thrown away when data are ranked. In fact, one of the many reasons why someone might use a rank-based (or nonparametric) test is because of outliers.
Do we need to worry about outliers when using rank-based tests? No. When the data are ranked, an outlier will simply be recognized as a case that is ranked one above (or below) the next less extreme case. Regardless of whether there is .01 or 5 standard deviations
30,395
Do we need to worry about outliers when using rank-based tests?
@Hotaka's answer is quite correct. Ranking makes transformation unnecessary; it is itself a transformation that ignores exact values except in so far as they lead to differences in rank. In fact, a little thought, or some example calculations, will show that the results after ranking logarithms or square roots or any other monotonic transformation are exactly the same as those after ranking the original data. But more can be said. The either-or thinking Either my data are normally distributed, and I can use standard or classical procedures. Or I need to resort to rank-based tests. is a little stark, and (it may be suggested) over-simplified. Although it's hard to suggest exactly what you should be doing without some sight of your data and your precise goals, there are other perspectives: Many users of statistics look at marginal (univariate) distributions and assess whether they are close to normality, but that may not even be relevant. For example, marginal normality is not required for regression-type procedures. For many procedures, it's how the means behave, not how the data behave, that is more important and closer to the main assumptions. Even (say) a significant result at conventional levels for a Shapiro-Wilk test is equivocal in terms of guiding later analysis. It just says "your distribution is detectably different from a normal distribution". That itself does not imply that the degree of non-normality you have makes whatever you have in mind invalid or absurd. It may just mean: go carefully, as underlying assumptions are not exactly satisfied. (In practice, they never are exactly satisfied, any way.) The habit to cultivate is that of thinking that all P-values are approximations. (Even when assumptions about distributions are not being made, assumptions about sampling or independence or error-free measurement are usually implicit.) Although many texts and courses imply otherwise, non-parametric statistics is something of a glorious dead end: there are a bundle of sometimes useful tests, but in practice you give up on most of the useful modelling that is central to modern statistics. Outliers are mentioned here, and they always deserve close attention. They should never be omitted just because they are inconvenient or appear to be the reason why assumptions are not satisfied. Sometimes analysis on a transformed scale is the best way forward. Sometimes a few mild outliers are not as problematic as less experienced users of statistics fear. With small samples, data will often look ragged or lumpy, even if the generating process is quite well-behaved; with large samples, a single outlier need not dominate the rest of the data. There is always the option of doing both kinds of tests, e.g. Student's t and Mann-Whitney-Wilcoxon. They don't ask exactly the same question, but it is often easy to see if they point in the same direction. That is, if a t test and the other test both give clear signals that two groups are different, you have some reassurance that your conclusion is well supported (and some defence against the sceptic who distrusts one or other procedure given a whiff of non-normality). If the two tests give very different answers, this in itself is useful evidence that you need to think very carefully about how best to analyse data. (Perhaps that massive outlier really does determine which way the answer comes out.) With experience, users of statistics are often more informal than texts or courses imply they should be. If you talked through an analysis with them, you would often find that they make quick judgements such as "Sure, the box plots show some mild outliers, but with data like this analysis of variance should work fine" or "With skew that marked, a logarithmic scale is the only sensible choice". I don't think you will often find them choosing techniques based on whether a Shapiro-Wilk test is or is not significant at $P < 0.05$. Saying something like that may not help less experienced users much, but it seems truer than the idea that statistics offers exact recipes that must always be followed.
Do we need to worry about outliers when using rank-based tests?
@Hotaka's answer is quite correct. Ranking makes transformation unnecessary; it is itself a transformation that ignores exact values except in so far as they lead to differences in rank. In fact, a li
Do we need to worry about outliers when using rank-based tests? @Hotaka's answer is quite correct. Ranking makes transformation unnecessary; it is itself a transformation that ignores exact values except in so far as they lead to differences in rank. In fact, a little thought, or some example calculations, will show that the results after ranking logarithms or square roots or any other monotonic transformation are exactly the same as those after ranking the original data. But more can be said. The either-or thinking Either my data are normally distributed, and I can use standard or classical procedures. Or I need to resort to rank-based tests. is a little stark, and (it may be suggested) over-simplified. Although it's hard to suggest exactly what you should be doing without some sight of your data and your precise goals, there are other perspectives: Many users of statistics look at marginal (univariate) distributions and assess whether they are close to normality, but that may not even be relevant. For example, marginal normality is not required for regression-type procedures. For many procedures, it's how the means behave, not how the data behave, that is more important and closer to the main assumptions. Even (say) a significant result at conventional levels for a Shapiro-Wilk test is equivocal in terms of guiding later analysis. It just says "your distribution is detectably different from a normal distribution". That itself does not imply that the degree of non-normality you have makes whatever you have in mind invalid or absurd. It may just mean: go carefully, as underlying assumptions are not exactly satisfied. (In practice, they never are exactly satisfied, any way.) The habit to cultivate is that of thinking that all P-values are approximations. (Even when assumptions about distributions are not being made, assumptions about sampling or independence or error-free measurement are usually implicit.) Although many texts and courses imply otherwise, non-parametric statistics is something of a glorious dead end: there are a bundle of sometimes useful tests, but in practice you give up on most of the useful modelling that is central to modern statistics. Outliers are mentioned here, and they always deserve close attention. They should never be omitted just because they are inconvenient or appear to be the reason why assumptions are not satisfied. Sometimes analysis on a transformed scale is the best way forward. Sometimes a few mild outliers are not as problematic as less experienced users of statistics fear. With small samples, data will often look ragged or lumpy, even if the generating process is quite well-behaved; with large samples, a single outlier need not dominate the rest of the data. There is always the option of doing both kinds of tests, e.g. Student's t and Mann-Whitney-Wilcoxon. They don't ask exactly the same question, but it is often easy to see if they point in the same direction. That is, if a t test and the other test both give clear signals that two groups are different, you have some reassurance that your conclusion is well supported (and some defence against the sceptic who distrusts one or other procedure given a whiff of non-normality). If the two tests give very different answers, this in itself is useful evidence that you need to think very carefully about how best to analyse data. (Perhaps that massive outlier really does determine which way the answer comes out.) With experience, users of statistics are often more informal than texts or courses imply they should be. If you talked through an analysis with them, you would often find that they make quick judgements such as "Sure, the box plots show some mild outliers, but with data like this analysis of variance should work fine" or "With skew that marked, a logarithmic scale is the only sensible choice". I don't think you will often find them choosing techniques based on whether a Shapiro-Wilk test is or is not significant at $P < 0.05$. Saying something like that may not help less experienced users much, but it seems truer than the idea that statistics offers exact recipes that must always be followed.
Do we need to worry about outliers when using rank-based tests? @Hotaka's answer is quite correct. Ranking makes transformation unnecessary; it is itself a transformation that ignores exact values except in so far as they lead to differences in rank. In fact, a li
30,396
Gaussian process regression toy problem
The mean function passing through the datapoints is usually an indication of over-fitting. Optimising the hyper-parameters by maximising the marginal likelihood will tend to favour very simple models unless there is enough data to justify something more complex. As you only have three datapoints, which are more or less in a line with little noise, the model that has been found seems pretty reasonable to me. Essentially the data can either be explained as a linear underlying function with moderate noise, or a moderately non-linear underlying function with little noise. The former is the simpler of the two hypotheses, and is favoured by "Occam's razor".
Gaussian process regression toy problem
The mean function passing through the datapoints is usually an indication of over-fitting. Optimising the hyper-parameters by maximising the marginal likelihood will tend to favour very simple models
Gaussian process regression toy problem The mean function passing through the datapoints is usually an indication of over-fitting. Optimising the hyper-parameters by maximising the marginal likelihood will tend to favour very simple models unless there is enough data to justify something more complex. As you only have three datapoints, which are more or less in a line with little noise, the model that has been found seems pretty reasonable to me. Essentially the data can either be explained as a linear underlying function with moderate noise, or a moderately non-linear underlying function with little noise. The former is the simpler of the two hypotheses, and is favoured by "Occam's razor".
Gaussian process regression toy problem The mean function passing through the datapoints is usually an indication of over-fitting. Optimising the hyper-parameters by maximising the marginal likelihood will tend to favour very simple models
30,397
Gaussian process regression toy problem
You are using the Kriging estimators with the addition of a noise term (known as a nugget effect in the Gaussian process literature). If the noise term was set to zero, i.e., $$\sigma^2_n \delta_{pq}=0$$ then your predictions would act as an interpolation and pass through the sample data points.
Gaussian process regression toy problem
You are using the Kriging estimators with the addition of a noise term (known as a nugget effect in the Gaussian process literature). If the noise term was set to zero, i.e., $$\sigma^2_n \delta_{pq}
Gaussian process regression toy problem You are using the Kriging estimators with the addition of a noise term (known as a nugget effect in the Gaussian process literature). If the noise term was set to zero, i.e., $$\sigma^2_n \delta_{pq}=0$$ then your predictions would act as an interpolation and pass through the sample data points.
Gaussian process regression toy problem You are using the Kriging estimators with the addition of a noise term (known as a nugget effect in the Gaussian process literature). If the noise term was set to zero, i.e., $$\sigma^2_n \delta_{pq}
30,398
Gaussian process regression toy problem
This looks OK to me, in the GP book by Rasmussen it definitely shows examples where the mean function does not pass through each data point. Note that the regression line is an estimate for the underlying function, and we're assuming that the observations are the underlying function values plus some noise. If the regression line based through all three points it would essentially be saying that there is no noise in the observed values. You could force a no noise assumption by setting $\sigma_n = 0$, and just optimizing the other hyper-parameters. I also suspect that the hyper-parmeter $l$ is being set to a relatively large value, giving a very shallow function. You could try holding $l$ fixed at various smaller values, and see how that changes the curve. Perhaps if you forced $l$ to be a bit smaller, the regression line would pass through all of the data points. As noted by Dikran Marsupial, this is a built in feature of Gaussian Processes, the marginal likelihood penalizes models that are too specific, and prefers ones that can explain many data sets.
Gaussian process regression toy problem
This looks OK to me, in the GP book by Rasmussen it definitely shows examples where the mean function does not pass through each data point. Note that the regression line is an estimate for the underl
Gaussian process regression toy problem This looks OK to me, in the GP book by Rasmussen it definitely shows examples where the mean function does not pass through each data point. Note that the regression line is an estimate for the underlying function, and we're assuming that the observations are the underlying function values plus some noise. If the regression line based through all three points it would essentially be saying that there is no noise in the observed values. You could force a no noise assumption by setting $\sigma_n = 0$, and just optimizing the other hyper-parameters. I also suspect that the hyper-parmeter $l$ is being set to a relatively large value, giving a very shallow function. You could try holding $l$ fixed at various smaller values, and see how that changes the curve. Perhaps if you forced $l$ to be a bit smaller, the regression line would pass through all of the data points. As noted by Dikran Marsupial, this is a built in feature of Gaussian Processes, the marginal likelihood penalizes models that are too specific, and prefers ones that can explain many data sets.
Gaussian process regression toy problem This looks OK to me, in the GP book by Rasmussen it definitely shows examples where the mean function does not pass through each data point. Note that the regression line is an estimate for the underl
30,399
How to interpret a box plot?
Interpretation of the box plot (alternatively box and whisker plot) rests in understanding that it provides a graphical representation of a five number summary, i.e. minimum, 1st quartile, median, 3rd quartile and maximum. The box encompasses 50% of the observations. The ends of the whiskers (vertical lines emanating from the top and bottom of the box) typically show where the minimum and maximum lie. However, where possible outliers exist (sometimes assessed based on 1.5 $\times$ interquartile range) points are added, as is the case for your figure. It may be useful for you to look at a histogram or density plots on specific categories of the data as that may help you understand what the box plot is saying. @Glen_b rightly indicates that left skew is evident and the central tendency for the 5th level of strength of feeling is lower than the others. It is difficult however to see whether that difference would be statistically significant or not.
How to interpret a box plot?
Interpretation of the box plot (alternatively box and whisker plot) rests in understanding that it provides a graphical representation of a five number summary, i.e. minimum, 1st quartile, median, 3rd
How to interpret a box plot? Interpretation of the box plot (alternatively box and whisker plot) rests in understanding that it provides a graphical representation of a five number summary, i.e. minimum, 1st quartile, median, 3rd quartile and maximum. The box encompasses 50% of the observations. The ends of the whiskers (vertical lines emanating from the top and bottom of the box) typically show where the minimum and maximum lie. However, where possible outliers exist (sometimes assessed based on 1.5 $\times$ interquartile range) points are added, as is the case for your figure. It may be useful for you to look at a histogram or density plots on specific categories of the data as that may help you understand what the box plot is saying. @Glen_b rightly indicates that left skew is evident and the central tendency for the 5th level of strength of feeling is lower than the others. It is difficult however to see whether that difference would be statistically significant or not.
How to interpret a box plot? Interpretation of the box plot (alternatively box and whisker plot) rests in understanding that it provides a graphical representation of a five number summary, i.e. minimum, 1st quartile, median, 3rd
30,400
How to interpret a box plot?
Here's a basic summary of what's there: All the distributions appear left-skew, "jammed up" against the upper bound of 1.0, with many low 'outliers' tailing off toward the bottom. The 5th category in each plot seems to sit lower than the others. Sometimes the 4th category is also low. All 5 variables (concern, breath, weath, sleep, act) seem to have broadly similar patterns.
How to interpret a box plot?
Here's a basic summary of what's there: All the distributions appear left-skew, "jammed up" against the upper bound of 1.0, with many low 'outliers' tailing off toward the bottom. The 5th category in
How to interpret a box plot? Here's a basic summary of what's there: All the distributions appear left-skew, "jammed up" against the upper bound of 1.0, with many low 'outliers' tailing off toward the bottom. The 5th category in each plot seems to sit lower than the others. Sometimes the 4th category is also low. All 5 variables (concern, breath, weath, sleep, act) seem to have broadly similar patterns.
How to interpret a box plot? Here's a basic summary of what's there: All the distributions appear left-skew, "jammed up" against the upper bound of 1.0, with many low 'outliers' tailing off toward the bottom. The 5th category in