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
44,201
Regressions. Why a and b explains more than a+b?
The reason is flexibility. Option 1: When you regress $X_1, X_2$ on $Y$ you are allowing the coefficients to be different. In other words, your regression equation is $Y = \alpha + \beta_1X_1 + \beta_2X_2 + \epsilon$. Notice $\beta_1$ may equal $\beta_2$ if it wants to - if that's what the data suggests. Option 2: When you regress $X_3 = X_1 + X_2$ on $Y$ you are forcing the coefficients to be the same - even if the data doesn't want them to be the same. Your regression equation becomes $Y = \alpha^\prime + \beta_1^\prime(X_3) + \epsilon = \alpha + \beta_1^\prime X_1 + \beta_1^\prime X_2+ \epsilon$. A regression equation will always select values for the coefficients that minimizes SSE (and thus maximizes $R^2$) based on the data you give it. In option 2, it'll do it's best but this will never be better (in terms of $R^2$) then option 1. This is because every conceivable possible value for the vector of coefficients in option 2 is a subset of the conceivable possible value for the vector of coefficients in option 1.
Regressions. Why a and b explains more than a+b?
The reason is flexibility. Option 1: When you regress $X_1, X_2$ on $Y$ you are allowing the coefficients to be different. In other words, your regression equation is $Y = \alpha + \beta_1X_1 + \beta_
Regressions. Why a and b explains more than a+b? The reason is flexibility. Option 1: When you regress $X_1, X_2$ on $Y$ you are allowing the coefficients to be different. In other words, your regression equation is $Y = \alpha + \beta_1X_1 + \beta_2X_2 + \epsilon$. Notice $\beta_1$ may equal $\beta_2$ if it wants to - if that's what the data suggests. Option 2: When you regress $X_3 = X_1 + X_2$ on $Y$ you are forcing the coefficients to be the same - even if the data doesn't want them to be the same. Your regression equation becomes $Y = \alpha^\prime + \beta_1^\prime(X_3) + \epsilon = \alpha + \beta_1^\prime X_1 + \beta_1^\prime X_2+ \epsilon$. A regression equation will always select values for the coefficients that minimizes SSE (and thus maximizes $R^2$) based on the data you give it. In option 2, it'll do it's best but this will never be better (in terms of $R^2$) then option 1. This is because every conceivable possible value for the vector of coefficients in option 2 is a subset of the conceivable possible value for the vector of coefficients in option 1.
Regressions. Why a and b explains more than a+b? The reason is flexibility. Option 1: When you regress $X_1, X_2$ on $Y$ you are allowing the coefficients to be different. In other words, your regression equation is $Y = \alpha + \beta_1X_1 + \beta_
44,202
How to organise the variable names in R without messing up? [closed]
Use simple phrases Rather than relying on very generic variable names like x1, x2, y1, y2, develop a very simple variable name system: Common variables: Some variables are so ubiquitous that it's just easier to name them as is: male, edu, income or inc, age, etc. As time goes on the naming of this variable will be nearly instinctive. Keep it short: Keep the name within 6-8 characters. I don't usually use upper case because I tend to save upper case characters for function names. But it's also acceptable to use system such as satFat (saturated fat), skMilk (skim milk) to chain up two words with one capital letter without hurting readability. Slash vowels: Most of the English words can still be quite discernible without vowels. For instance, sector vs. sctr, district vs. dstrct, group1 vs grp1, quartile vs. qrtl. Again, it's a matter of habit and soon you will be able to name and recognize them quickly. Keep syntax Whatever you do, save the syntax. And keep periodic back up after each major revision so that you have an archive of your analysis flow. (aka, don't keep overwriting your one single file, save a historic cascade of copies.) With a good syntax keeping habit, even moderately messy variable naming will not be a major problem as users can always trace back how each variable comes about. Sign and date your syntax and demand other people to do so. Start the syntax by information like: # Childhood obesity analysis (project name) # by Penguin Knight # e-Mail: xxxxxxx@gmail.com # Phone: ext: 10101 # Date: Jun-12-2014 # Description of the analysis: blah blah blah. # Version: 1.00 # Revision date and history: That way, even later someone looking at your syntax may be lost, they can still contact you to discuss and generate some clues. Comment on your syntax Use comments as much as commands. Syntax like: lm(y ~ x1) can be cryptic, but this will not confuse you as badly: # y: body fat percent # x1: weekly fastfood meals frequency lm(y ~ x1) I may go so far to suggest that for each action, there should be at least one line of comment. Even it's something you have done million times in that week, once you have put down the project for a couple of weeks, it would be very hard to figure out what was going on. Maintain a code book Use comment function to maintain a code book: You can also dedicate a section to put all the variable names and their description at the same place. I often use code such as @codebook to start the code book section, and then whenever I need to look at the code book I just use Ctrl-F to search for the phrase @codebook and I'll be right there. Keep a separate file: For large group projects that involve more collaborators, I would suggest using a separate file such as an Excel file (or even another R data file) to maintain a code book. The data collection tools also make great code books: If you work on a questionnaire, you can also use a red pen to write down the variable name next to each item. I also use text boxes for that purpose if I need to work on an electronic version. Use suffixes and prefixes Develop a suffix and prefix system of your own to quickly identify the variables. For instance, I always put sv in front of all those scratch variables that I don't care to keep. In some software like Stata, this prefix can allow users to quickly clean them out by just typing: drop sv* Attach units: Another good use of suffix is to display unit. For instance, ageyr and agemo as age in years and months. inc1000 as income in 1000s. gdp2012, gdp2013 as GDP data of years 2012 and 2013, etc. Attach label: You may also use prefix to determine strata: e.g. use m and f in conjunction to variable that are for males and females: medu, fedu. I tend to avoid "." and "_": Most of the time these two characters cause problems when exporting data for another software package. Develop a style, and stick to it The most important point is to stick to your code style no matter how big or trivial the project is. Maintaining code legibility is not just a way to keep your stress and confusion in check, it's also a professional courtesy and ethics.
How to organise the variable names in R without messing up? [closed]
Use simple phrases Rather than relying on very generic variable names like x1, x2, y1, y2, develop a very simple variable name system: Common variables: Some variables are so ubiquitous that it's just
How to organise the variable names in R without messing up? [closed] Use simple phrases Rather than relying on very generic variable names like x1, x2, y1, y2, develop a very simple variable name system: Common variables: Some variables are so ubiquitous that it's just easier to name them as is: male, edu, income or inc, age, etc. As time goes on the naming of this variable will be nearly instinctive. Keep it short: Keep the name within 6-8 characters. I don't usually use upper case because I tend to save upper case characters for function names. But it's also acceptable to use system such as satFat (saturated fat), skMilk (skim milk) to chain up two words with one capital letter without hurting readability. Slash vowels: Most of the English words can still be quite discernible without vowels. For instance, sector vs. sctr, district vs. dstrct, group1 vs grp1, quartile vs. qrtl. Again, it's a matter of habit and soon you will be able to name and recognize them quickly. Keep syntax Whatever you do, save the syntax. And keep periodic back up after each major revision so that you have an archive of your analysis flow. (aka, don't keep overwriting your one single file, save a historic cascade of copies.) With a good syntax keeping habit, even moderately messy variable naming will not be a major problem as users can always trace back how each variable comes about. Sign and date your syntax and demand other people to do so. Start the syntax by information like: # Childhood obesity analysis (project name) # by Penguin Knight # e-Mail: xxxxxxx@gmail.com # Phone: ext: 10101 # Date: Jun-12-2014 # Description of the analysis: blah blah blah. # Version: 1.00 # Revision date and history: That way, even later someone looking at your syntax may be lost, they can still contact you to discuss and generate some clues. Comment on your syntax Use comments as much as commands. Syntax like: lm(y ~ x1) can be cryptic, but this will not confuse you as badly: # y: body fat percent # x1: weekly fastfood meals frequency lm(y ~ x1) I may go so far to suggest that for each action, there should be at least one line of comment. Even it's something you have done million times in that week, once you have put down the project for a couple of weeks, it would be very hard to figure out what was going on. Maintain a code book Use comment function to maintain a code book: You can also dedicate a section to put all the variable names and their description at the same place. I often use code such as @codebook to start the code book section, and then whenever I need to look at the code book I just use Ctrl-F to search for the phrase @codebook and I'll be right there. Keep a separate file: For large group projects that involve more collaborators, I would suggest using a separate file such as an Excel file (or even another R data file) to maintain a code book. The data collection tools also make great code books: If you work on a questionnaire, you can also use a red pen to write down the variable name next to each item. I also use text boxes for that purpose if I need to work on an electronic version. Use suffixes and prefixes Develop a suffix and prefix system of your own to quickly identify the variables. For instance, I always put sv in front of all those scratch variables that I don't care to keep. In some software like Stata, this prefix can allow users to quickly clean them out by just typing: drop sv* Attach units: Another good use of suffix is to display unit. For instance, ageyr and agemo as age in years and months. inc1000 as income in 1000s. gdp2012, gdp2013 as GDP data of years 2012 and 2013, etc. Attach label: You may also use prefix to determine strata: e.g. use m and f in conjunction to variable that are for males and females: medu, fedu. I tend to avoid "." and "_": Most of the time these two characters cause problems when exporting data for another software package. Develop a style, and stick to it The most important point is to stick to your code style no matter how big or trivial the project is. Maintaining code legibility is not just a way to keep your stress and confusion in check, it's also a professional courtesy and ethics.
How to organise the variable names in R without messing up? [closed] Use simple phrases Rather than relying on very generic variable names like x1, x2, y1, y2, develop a very simple variable name system: Common variables: Some variables are so ubiquitous that it's just
44,203
How to organise the variable names in R without messing up? [closed]
Got too long for a comment, so I guess it's an answer now. Use long, descriptive names for anything you need to keep around for more than a couple of minutes. The long names might be a nuisance to type, but if you're working by running scripts, writing functions and so on, the actual typing is not that much anyway. But even a lot of typing is far easier than trying to figure out what you did with variables you can't remember. Imagine you need to figure out what you did in 6 months or a year - or imagine some other poor person in the same position. Write your code for poor future-you. Help future-you out by making everything as obvious as possible. Imagine future-you can't remember anything about what you're doing. It's nearly always better to have scripts that generate your calculations, and document them as well as making them readable. To that end, also delete variables you don't need, it will help keep you disciplined about making everything generatable again. Keep related variables in data frames or lists (and keep related matrices, data frames and so in inside lists when there are more than a couple of them), and name all your data frame columns and your list components with names that explain what they are.
How to organise the variable names in R without messing up? [closed]
Got too long for a comment, so I guess it's an answer now. Use long, descriptive names for anything you need to keep around for more than a couple of minutes. The long names might be a nuisance to ty
How to organise the variable names in R without messing up? [closed] Got too long for a comment, so I guess it's an answer now. Use long, descriptive names for anything you need to keep around for more than a couple of minutes. The long names might be a nuisance to type, but if you're working by running scripts, writing functions and so on, the actual typing is not that much anyway. But even a lot of typing is far easier than trying to figure out what you did with variables you can't remember. Imagine you need to figure out what you did in 6 months or a year - or imagine some other poor person in the same position. Write your code for poor future-you. Help future-you out by making everything as obvious as possible. Imagine future-you can't remember anything about what you're doing. It's nearly always better to have scripts that generate your calculations, and document them as well as making them readable. To that end, also delete variables you don't need, it will help keep you disciplined about making everything generatable again. Keep related variables in data frames or lists (and keep related matrices, data frames and so in inside lists when there are more than a couple of them), and name all your data frame columns and your list components with names that explain what they are.
How to organise the variable names in R without messing up? [closed] Got too long for a comment, so I guess it's an answer now. Use long, descriptive names for anything you need to keep around for more than a couple of minutes. The long names might be a nuisance to ty
44,204
How to organise the variable names in R without messing up? [closed]
Just don't use obscure names like x1. It's important, both from a computing as well as an analyzing perspective, to take a minute to look at your variable and understand what it represents. It's name should naturally be what it represents. For example, if it's a vector of ages, why not name it age? If it's a large name, you can reduce it, but try to make it so --- as Glen put it --- future-you will understand what present-you was talking about. If you want to create backup objects, my tip is to prepend it's name with a dot (.) so it is invisible to ls() (but not to ls(all.names = TRUE)). I use this often, but sometimes I want to be able to see the backup object at all times, so I append .bak to the name.
How to organise the variable names in R without messing up? [closed]
Just don't use obscure names like x1. It's important, both from a computing as well as an analyzing perspective, to take a minute to look at your variable and understand what it represents. It's name
How to organise the variable names in R without messing up? [closed] Just don't use obscure names like x1. It's important, both from a computing as well as an analyzing perspective, to take a minute to look at your variable and understand what it represents. It's name should naturally be what it represents. For example, if it's a vector of ages, why not name it age? If it's a large name, you can reduce it, but try to make it so --- as Glen put it --- future-you will understand what present-you was talking about. If you want to create backup objects, my tip is to prepend it's name with a dot (.) so it is invisible to ls() (but not to ls(all.names = TRUE)). I use this often, but sometimes I want to be able to see the backup object at all times, so I append .bak to the name.
How to organise the variable names in R without messing up? [closed] Just don't use obscure names like x1. It's important, both from a computing as well as an analyzing perspective, to take a minute to look at your variable and understand what it represents. It's name
44,205
In R, what does a probability density function compute? [duplicate]
Densities are not probabilities. $$ $$ The density $f$ of a continuous random variable $X$ is defined as $$ f(x) = F'(x) = \lim_{\epsilon \rightarrow 0} \frac{\Pr\big(x < X \leq x + \epsilon\big)}{\epsilon} $$ with $F$ the cumulative distribution function (cdf). $$ $$ $f(x)$ can be larger than $1$. The area under the density equals $1$: $\displaystyle \int_{\text{dom}(f)} f(x) \, \text{d}x = 1$. The area under the density in the interval $(a,b)$ equals the probability that $X \in (a,b)$. That last property makes the bridge between densities and probabilities. $$ $$ The density of a $N(\mu, \sigma^2)$ random variable is given by $$ f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp \Big\{ - \frac{1}{2\sigma^2} (x - \mu)^2 \Big\} $$ In particular, with $\mu=0$ and $\sigma=1$, we have $f(0)= \dfrac{1}{\sqrt{2\pi}} = 0.3989$. To address @garciaj's comment: The fact that $f(0) = 0.3989$ indicates that (cf. the definition of $f(x)$ above) $$ \Pr\big(0 < X \leq \epsilon\big) \approx 0.3989 \, \epsilon $$ for $\epsilon$ small enough. For example, using $\epsilon = 0.1$, we have \begin{align*} \Pr\big(0 < X \leq 0.1\big) & = \Pr\big(X \leq 0.1\big) - \Pr\big(X \leq 0\big) \\ & = \text{pnorm(0.1)} - \text{pnorm(0)} \\ & = 0.03982784 \approx 0.3989 \times 0.1 \end{align*}
In R, what does a probability density function compute? [duplicate]
Densities are not probabilities. $$ $$ The density $f$ of a continuous random variable $X$ is defined as $$ f(x) = F'(x) = \lim_{\epsilon \rightarrow 0} \frac{\Pr\big(x < X \leq x + \epsilon\big)}{\e
In R, what does a probability density function compute? [duplicate] Densities are not probabilities. $$ $$ The density $f$ of a continuous random variable $X$ is defined as $$ f(x) = F'(x) = \lim_{\epsilon \rightarrow 0} \frac{\Pr\big(x < X \leq x + \epsilon\big)}{\epsilon} $$ with $F$ the cumulative distribution function (cdf). $$ $$ $f(x)$ can be larger than $1$. The area under the density equals $1$: $\displaystyle \int_{\text{dom}(f)} f(x) \, \text{d}x = 1$. The area under the density in the interval $(a,b)$ equals the probability that $X \in (a,b)$. That last property makes the bridge between densities and probabilities. $$ $$ The density of a $N(\mu, \sigma^2)$ random variable is given by $$ f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp \Big\{ - \frac{1}{2\sigma^2} (x - \mu)^2 \Big\} $$ In particular, with $\mu=0$ and $\sigma=1$, we have $f(0)= \dfrac{1}{\sqrt{2\pi}} = 0.3989$. To address @garciaj's comment: The fact that $f(0) = 0.3989$ indicates that (cf. the definition of $f(x)$ above) $$ \Pr\big(0 < X \leq \epsilon\big) \approx 0.3989 \, \epsilon $$ for $\epsilon$ small enough. For example, using $\epsilon = 0.1$, we have \begin{align*} \Pr\big(0 < X \leq 0.1\big) & = \Pr\big(X \leq 0.1\big) - \Pr\big(X \leq 0\big) \\ & = \text{pnorm(0.1)} - \text{pnorm(0)} \\ & = 0.03982784 \approx 0.3989 \times 0.1 \end{align*}
In R, what does a probability density function compute? [duplicate] Densities are not probabilities. $$ $$ The density $f$ of a continuous random variable $X$ is defined as $$ f(x) = F'(x) = \lim_{\epsilon \rightarrow 0} \frac{\Pr\big(x < X \leq x + \epsilon\big)}{\e
44,206
In R, what does a probability density function compute? [duplicate]
You shoud distinguish between probability mass and probability density. A discrete random variable is like a set of little stones: each stone has its own mass (weight). For example, if you toss a regular coin the mass of the "head-stone" is 1/2. The probability "density" function of a discrete variable is actually a probability mass function. A continuous random variable is like a heap of dust. You may think that a single speck of dust has no mass, but you can calculate the mass of a fistful of dust if you know its volume and its density: its mass is $volume\times density$. dnorm(0) is just the density of a (standard) normal variable. When the volume is zero, i.e. when $Z=0$, the probability mass is zero just because in $volume\times density$ the first factor is zero. As soon as the volume increases, as soon as you look for the probability mass of a range of values (a fistful of dust, i.e. an interval), you can compute a probability mass. For example: $$\begin{align}P(-0.1<Z<0.1)&=P(Z\in(-0.1,0.1))\\ &=\mathtt{pnorm(0.1)-pnorm(-0.1)}=0.07965567\end{align}$$ Each single value (each speck of dust) has a density, but only intervals like $(-0.1,0.1)$ (fistfuls of dust) have a "mass". So you can compute the probability mass of intervals, not of single values. But the probability density of single values does exist and make sense. The density of a uniform random variable is constant, the density of a normal variable is not. However you can approximate the mass of small intervals. For example: > pnorm(0.1)-pnorm(-0.1) [1] 0.07965567 > density_at0 <- dnorm(0) > volume_around0 <- (0.1) - (-0.1) > volume_around0 * density_at0 [1] 0.07978846
In R, what does a probability density function compute? [duplicate]
You shoud distinguish between probability mass and probability density. A discrete random variable is like a set of little stones: each stone has its own mass (weight). For example, if you toss a regu
In R, what does a probability density function compute? [duplicate] You shoud distinguish between probability mass and probability density. A discrete random variable is like a set of little stones: each stone has its own mass (weight). For example, if you toss a regular coin the mass of the "head-stone" is 1/2. The probability "density" function of a discrete variable is actually a probability mass function. A continuous random variable is like a heap of dust. You may think that a single speck of dust has no mass, but you can calculate the mass of a fistful of dust if you know its volume and its density: its mass is $volume\times density$. dnorm(0) is just the density of a (standard) normal variable. When the volume is zero, i.e. when $Z=0$, the probability mass is zero just because in $volume\times density$ the first factor is zero. As soon as the volume increases, as soon as you look for the probability mass of a range of values (a fistful of dust, i.e. an interval), you can compute a probability mass. For example: $$\begin{align}P(-0.1<Z<0.1)&=P(Z\in(-0.1,0.1))\\ &=\mathtt{pnorm(0.1)-pnorm(-0.1)}=0.07965567\end{align}$$ Each single value (each speck of dust) has a density, but only intervals like $(-0.1,0.1)$ (fistfuls of dust) have a "mass". So you can compute the probability mass of intervals, not of single values. But the probability density of single values does exist and make sense. The density of a uniform random variable is constant, the density of a normal variable is not. However you can approximate the mass of small intervals. For example: > pnorm(0.1)-pnorm(-0.1) [1] 0.07965567 > density_at0 <- dnorm(0) > volume_around0 <- (0.1) - (-0.1) > volume_around0 * density_at0 [1] 0.07978846
In R, what does a probability density function compute? [duplicate] You shoud distinguish between probability mass and probability density. A discrete random variable is like a set of little stones: each stone has its own mass (weight). For example, if you toss a regu
44,207
Is it possible to convert a Rayleigh distribution into a Gaussian distribution?
If you know the Rayleigh parameter, then the conversion to a standard normal is readily achieved by the probability integral transform followed by an inverse normal cdf. If $X\sim\text{Rayleigh}(\sigma)$, with cdf $F_\sigma(x)$, then $F_\sigma (X)$ is uniform, and $\Phi^{-1}(F_\sigma (X))$ is standard normal (where $\Phi$ is the standard normal cdf). If $\sigma$ is unknown we are left with one kind of approximation or another (even estimating $\sigma$ involves approximation). Since the square of a Rayleigh random variable is a special case of the gamma, the Wilson-Hilferty transformation (cube root in the case of the gamma) should produce a good approximation of normality. That is, if $X\sim \text{Rayleigh}$, then $X^{2/3}$ should be fairly normal looking. In practice it looks like a slightly smaller power, somewhere near 0.6, might be a little closer. $\text{ }$ Here's a comparison of the exact transformation (x-axis) and the three power transformations above (y-axis): The black is the 0.6 power, the red is the 2/3 power and the green is the 1/2 power. The one that most closely reproduces the exact transformation should lie closest to a straight line ... and that looks to be the green line. (Added in edit: I've checked more carefully; of those three, the green line is nearest to straight overall, but the black line is straighter in the right tail. All three give distributions that are pretty nearly normal - but I should have asked why you needed normality.) -- An additional discussion on powers of exponential - and hence of Rayleigh - variables: Powers of exponential random variables are distributed as Weibull. Specifically, if $X$ is exponential, $X^\frac{1}{k}$ is Weibull with shape parameter $k$. So cube roots and fourth roots of exponentials (Rayleigh variables to the powers $\frac{2}{3}$ and $\frac12$ respectively) will be Weibull with shape parameters $3$ and $4$. While no Weibull is symmetric, particular choices for $k$ will produce Weibull distributions with zero skewness (different choices for different measures of skewness). Here are the values of $k$ that have $0$ skewness for several skewness measures and the corresponding power ($p$) of the Rayleigh: 3rd-moment skewness: $\:\,\, k=3.60,\, p=0.56$ mean-median skewness: $k=3.44,\, p=0.58\,$ (second Pearson skewness) mean-mode skewness: $\:\,\, k=3.31,\, p=0.60\,$ (first Pearson skewness) mode-median skewness: $k=3.26,\, p=0.61$ So it's little surprise that a value of $p$ near $0.6$ would appear suitable. -- In respect of the issue with outliers: Can you define what you mean by 'outlier'? If the data has values that don't actually come from the Rayleigh distribution, the question of transforming Rayleigh-distributed data is irrelevant, since you don't have Rayleigh-distributed data. So if you have values from some distribution that's not Rayleigh (with values that a discrepant for a Rayleigh model) and you transform to normality as if it were Rayleigh, then you definitely end up with a non-normal result ... one which will likely have discrepant-looking values relatively to a normal model. In the absence of a specification of what makes an outlier, here's an example: This is the same data as above (a large sample from a Rayleigh distribution with $\sigma=1$). In the second panel I have added four outliers (at 6, 10, 30 and 100), marked in red. In the third panel, we see the effect of the power $p=\frac{2}{3}$ and in the last panel the effect of the power $p=\frac{1}{2}$. Note that for the Rayleigh data, $\mu+3\sigma$ is at about 3.22. The value at 6 is already far enough away as to be considered highly unlikely even in a quite large sample with that level of skewness -- an outlier in some sense. You can see that the transformation brings it back toward the main part of the data, so that by the last panel it's visually a somewhat mild outlier, fairly borderline given the sample size (about 4.5 sd's above the mean). The value 10 (on the original scale), while clearly an outlier, is noticeably less discrepant but still clearly inconsistent with the idea that the data are normal, and the larger values even more so. So they do in some sense "come in" -- but as to whether the status of them being 'outliers' has changed depends very much on how you define 'outlier'. -- The suggestion of a fourth root for a gamma* with small values of the shape parameter is in Hawkins and Wixley (ref below). While the Wilson-Hilferty works best over a wide range of gamma distributions, the Hawkins-Wixley does seem to do a little better in some parts of the low-end (smaller values of the shape parameters). That fourth root of a gamma corresponds to a square root of a Rayleigh. *(NB chi-square is a gamma with a particular scale, and when looking at power transformation, the scale won't matter. So even though both references seem to be about chi-square distributions, their conclusions apply to gamma distributions more generally) Wilson, E. B., and Hilferty, M. M. (1931), "The Distribution of Chi-Squares," Proceedings of the National Academy of Sciences, 17, 684–688. Hawkins, D. M., and Wixley, R. A. J. (1986), "A Note on the Transformation of Chi-Squared Variables to Normality," The American Statistician, 40, 296–298.
Is it possible to convert a Rayleigh distribution into a Gaussian distribution?
If you know the Rayleigh parameter, then the conversion to a standard normal is readily achieved by the probability integral transform followed by an inverse normal cdf. If $X\sim\text{Rayleigh}(\sigm
Is it possible to convert a Rayleigh distribution into a Gaussian distribution? If you know the Rayleigh parameter, then the conversion to a standard normal is readily achieved by the probability integral transform followed by an inverse normal cdf. If $X\sim\text{Rayleigh}(\sigma)$, with cdf $F_\sigma(x)$, then $F_\sigma (X)$ is uniform, and $\Phi^{-1}(F_\sigma (X))$ is standard normal (where $\Phi$ is the standard normal cdf). If $\sigma$ is unknown we are left with one kind of approximation or another (even estimating $\sigma$ involves approximation). Since the square of a Rayleigh random variable is a special case of the gamma, the Wilson-Hilferty transformation (cube root in the case of the gamma) should produce a good approximation of normality. That is, if $X\sim \text{Rayleigh}$, then $X^{2/3}$ should be fairly normal looking. In practice it looks like a slightly smaller power, somewhere near 0.6, might be a little closer. $\text{ }$ Here's a comparison of the exact transformation (x-axis) and the three power transformations above (y-axis): The black is the 0.6 power, the red is the 2/3 power and the green is the 1/2 power. The one that most closely reproduces the exact transformation should lie closest to a straight line ... and that looks to be the green line. (Added in edit: I've checked more carefully; of those three, the green line is nearest to straight overall, but the black line is straighter in the right tail. All three give distributions that are pretty nearly normal - but I should have asked why you needed normality.) -- An additional discussion on powers of exponential - and hence of Rayleigh - variables: Powers of exponential random variables are distributed as Weibull. Specifically, if $X$ is exponential, $X^\frac{1}{k}$ is Weibull with shape parameter $k$. So cube roots and fourth roots of exponentials (Rayleigh variables to the powers $\frac{2}{3}$ and $\frac12$ respectively) will be Weibull with shape parameters $3$ and $4$. While no Weibull is symmetric, particular choices for $k$ will produce Weibull distributions with zero skewness (different choices for different measures of skewness). Here are the values of $k$ that have $0$ skewness for several skewness measures and the corresponding power ($p$) of the Rayleigh: 3rd-moment skewness: $\:\,\, k=3.60,\, p=0.56$ mean-median skewness: $k=3.44,\, p=0.58\,$ (second Pearson skewness) mean-mode skewness: $\:\,\, k=3.31,\, p=0.60\,$ (first Pearson skewness) mode-median skewness: $k=3.26,\, p=0.61$ So it's little surprise that a value of $p$ near $0.6$ would appear suitable. -- In respect of the issue with outliers: Can you define what you mean by 'outlier'? If the data has values that don't actually come from the Rayleigh distribution, the question of transforming Rayleigh-distributed data is irrelevant, since you don't have Rayleigh-distributed data. So if you have values from some distribution that's not Rayleigh (with values that a discrepant for a Rayleigh model) and you transform to normality as if it were Rayleigh, then you definitely end up with a non-normal result ... one which will likely have discrepant-looking values relatively to a normal model. In the absence of a specification of what makes an outlier, here's an example: This is the same data as above (a large sample from a Rayleigh distribution with $\sigma=1$). In the second panel I have added four outliers (at 6, 10, 30 and 100), marked in red. In the third panel, we see the effect of the power $p=\frac{2}{3}$ and in the last panel the effect of the power $p=\frac{1}{2}$. Note that for the Rayleigh data, $\mu+3\sigma$ is at about 3.22. The value at 6 is already far enough away as to be considered highly unlikely even in a quite large sample with that level of skewness -- an outlier in some sense. You can see that the transformation brings it back toward the main part of the data, so that by the last panel it's visually a somewhat mild outlier, fairly borderline given the sample size (about 4.5 sd's above the mean). The value 10 (on the original scale), while clearly an outlier, is noticeably less discrepant but still clearly inconsistent with the idea that the data are normal, and the larger values even more so. So they do in some sense "come in" -- but as to whether the status of them being 'outliers' has changed depends very much on how you define 'outlier'. -- The suggestion of a fourth root for a gamma* with small values of the shape parameter is in Hawkins and Wixley (ref below). While the Wilson-Hilferty works best over a wide range of gamma distributions, the Hawkins-Wixley does seem to do a little better in some parts of the low-end (smaller values of the shape parameters). That fourth root of a gamma corresponds to a square root of a Rayleigh. *(NB chi-square is a gamma with a particular scale, and when looking at power transformation, the scale won't matter. So even though both references seem to be about chi-square distributions, their conclusions apply to gamma distributions more generally) Wilson, E. B., and Hilferty, M. M. (1931), "The Distribution of Chi-Squares," Proceedings of the National Academy of Sciences, 17, 684–688. Hawkins, D. M., and Wixley, R. A. J. (1986), "A Note on the Transformation of Chi-Squared Variables to Normality," The American Statistician, 40, 296–298.
Is it possible to convert a Rayleigh distribution into a Gaussian distribution? If you know the Rayleigh parameter, then the conversion to a standard normal is readily achieved by the probability integral transform followed by an inverse normal cdf. If $X\sim\text{Rayleigh}(\sigm
44,208
Is it possible to convert a Rayleigh distribution into a Gaussian distribution?
If $R$ is a Rayleigh random variable and $\Theta \sim U[0,2\pi)$ is independent of $R$, then $X=R\cos \Theta$ and $Y=R \sin \Theta$ are independent zero-mean normal random variables with identical variance $\sigma^2 = \frac{1}{2}E[R^2]$. Thus, if you transform your data set as $$\{r_1, r_2, \ldots, r_n\} \longrightarrow \{r_1\cos \theta_1, r_2\cos \theta_2, \ldots r_n\cos \theta_n\}$$ (similarly for $Y$ but using $\sin \theta_i$) where $\{\theta_i\colon 1 \leq i \leq n\}$ is a data set that you create as a sequence of independent samples drawn from $U[0,2\pi)$,, then the resulting data set is exactly a collection of $n$ samples from a $N(0,\sigma^2)$ distribution. Note that in contrast to the monotone transformations suggested in @Glen_b's answer, the resulting data set has both positive and negative numbers in it. A Rayleigh-distributed data set can have outliers that are very large, but since these will get multiplied by a cosine, which has magnitude less than $1$, they might not be outliers any more unless the cosine has magnitude close to $1$, as noted in Glen_b's comment. Note also that if $\cos \theta_i$ is close to $-1$, then this outlier will still be an outlier but in the other tail. If $E]R^2]$ is quite large, then a Rayleigh-distributed data set can also have very small outliers: sample values that are very close to $0$ while almost all of the other sample values are closer to the (large) sample mean. Such outliers will become very close to the mean when they undergo the transformation that I suggest above. With Glen_b's transformation, such outliers will remain small outliers. In short, the transformed data set does not enjoy the property that outliers in $\{r_i\colon 1 \le i \leq n\}$ are outliers in the transformed data set $\{r_i\cos \theta_i\colon 1 \le i \leq n\}$. If you are willing to have a transformed data set that is twice as large, then the set $$\{r_1\cos \theta_1, r_2\cos \theta_2, \ldots r_n\cos \theta_n\} \cup \{r_1\sin \theta_1, r_2\sin \theta_2, \ldots r_n\sin \theta_n\}$$ is a set of $2n$ independent samples drawn from an $N(0,\sigma^2)$ distribution, and since $\max \{|\cos \theta |, |\sin \theta |\} \geq 1/\sqrt{2}$ you are guaranteed that each large outlier gives you two numbers at least one of which might well still be an outlier, since outlying is, like beauty, in the eye of the beholder. Is something just $20\%$ larger than the next smaller value an outlier? or would you insist on $50\%$ larger? I suppose it depends on the scale factors etc.
Is it possible to convert a Rayleigh distribution into a Gaussian distribution?
If $R$ is a Rayleigh random variable and $\Theta \sim U[0,2\pi)$ is independent of $R$, then $X=R\cos \Theta$ and $Y=R \sin \Theta$ are independent zero-mean normal random variables with identical var
Is it possible to convert a Rayleigh distribution into a Gaussian distribution? If $R$ is a Rayleigh random variable and $\Theta \sim U[0,2\pi)$ is independent of $R$, then $X=R\cos \Theta$ and $Y=R \sin \Theta$ are independent zero-mean normal random variables with identical variance $\sigma^2 = \frac{1}{2}E[R^2]$. Thus, if you transform your data set as $$\{r_1, r_2, \ldots, r_n\} \longrightarrow \{r_1\cos \theta_1, r_2\cos \theta_2, \ldots r_n\cos \theta_n\}$$ (similarly for $Y$ but using $\sin \theta_i$) where $\{\theta_i\colon 1 \leq i \leq n\}$ is a data set that you create as a sequence of independent samples drawn from $U[0,2\pi)$,, then the resulting data set is exactly a collection of $n$ samples from a $N(0,\sigma^2)$ distribution. Note that in contrast to the monotone transformations suggested in @Glen_b's answer, the resulting data set has both positive and negative numbers in it. A Rayleigh-distributed data set can have outliers that are very large, but since these will get multiplied by a cosine, which has magnitude less than $1$, they might not be outliers any more unless the cosine has magnitude close to $1$, as noted in Glen_b's comment. Note also that if $\cos \theta_i$ is close to $-1$, then this outlier will still be an outlier but in the other tail. If $E]R^2]$ is quite large, then a Rayleigh-distributed data set can also have very small outliers: sample values that are very close to $0$ while almost all of the other sample values are closer to the (large) sample mean. Such outliers will become very close to the mean when they undergo the transformation that I suggest above. With Glen_b's transformation, such outliers will remain small outliers. In short, the transformed data set does not enjoy the property that outliers in $\{r_i\colon 1 \le i \leq n\}$ are outliers in the transformed data set $\{r_i\cos \theta_i\colon 1 \le i \leq n\}$. If you are willing to have a transformed data set that is twice as large, then the set $$\{r_1\cos \theta_1, r_2\cos \theta_2, \ldots r_n\cos \theta_n\} \cup \{r_1\sin \theta_1, r_2\sin \theta_2, \ldots r_n\sin \theta_n\}$$ is a set of $2n$ independent samples drawn from an $N(0,\sigma^2)$ distribution, and since $\max \{|\cos \theta |, |\sin \theta |\} \geq 1/\sqrt{2}$ you are guaranteed that each large outlier gives you two numbers at least one of which might well still be an outlier, since outlying is, like beauty, in the eye of the beholder. Is something just $20\%$ larger than the next smaller value an outlier? or would you insist on $50\%$ larger? I suppose it depends on the scale factors etc.
Is it possible to convert a Rayleigh distribution into a Gaussian distribution? If $R$ is a Rayleigh random variable and $\Theta \sim U[0,2\pi)$ is independent of $R$, then $X=R\cos \Theta$ and $Y=R \sin \Theta$ are independent zero-mean normal random variables with identical var
44,209
Can you do statistics with 4 data points?
I have a friend who used to work for the US defense department (long time ago, cold war era) and was once asked to answer a question using a single data point. When he insisted that he needed more data he was told that the person who had provided the single data point had been caught and executed for espionage shortly after providing the single data point, so there would be no more data coming. That is when my friend started to learn about Bayesian statistics. I also remember seeing an article several years ago, possibly in the American Statistician, possibly in Chance, that derived a way to compute a confidence interval for a mean based on a single data point (the 95% interval from a value of x was something like -x to 3*x) if you were willing to make certain assumptions (and the usual diagnostics were not of any help with only 1 point). So, yes, you can do valid statistics with very small sample sizes, but you will tend to have low power/precision and large sample properties will not help you, so violations of any assumptions will have a potentially much larger impact.
Can you do statistics with 4 data points?
I have a friend who used to work for the US defense department (long time ago, cold war era) and was once asked to answer a question using a single data point. When he insisted that he needed more da
Can you do statistics with 4 data points? I have a friend who used to work for the US defense department (long time ago, cold war era) and was once asked to answer a question using a single data point. When he insisted that he needed more data he was told that the person who had provided the single data point had been caught and executed for espionage shortly after providing the single data point, so there would be no more data coming. That is when my friend started to learn about Bayesian statistics. I also remember seeing an article several years ago, possibly in the American Statistician, possibly in Chance, that derived a way to compute a confidence interval for a mean based on a single data point (the 95% interval from a value of x was something like -x to 3*x) if you were willing to make certain assumptions (and the usual diagnostics were not of any help with only 1 point). So, yes, you can do valid statistics with very small sample sizes, but you will tend to have low power/precision and large sample properties will not help you, so violations of any assumptions will have a potentially much larger impact.
Can you do statistics with 4 data points? I have a friend who used to work for the US defense department (long time ago, cold war era) and was once asked to answer a question using a single data point. When he insisted that he needed more da
44,210
Can you do statistics with 4 data points?
Short answer: yes, but your results will usually be useless. Long answer: Statistics often involves forming some kind of inference about underlying parameters based on data, with constraints on the probability of a False-Positive and/or of a False-Negative. In a typical test, i.e. testing if a sample came from a given distribution, we put an upper bound (called alpha) on the probability of a Type-I Error (False Positive), mostly for two reasons: In practice that is the only kind of error you can put a bound on, b/c of the nature of your null hypothesis False Positives are usually considered more terrible than False Negatives (a corollary of Occam's Razor) Holding alpha constant, beta (upper bound of probability of False-Negative) is generally larger for smaller data sets. And when beta is large, your overall probability of producing a Positive is very small, and so your test will almost always return Negative, which is not very different from just accepting your Null Hypothesis from the get-go. In this situtation we say the statistical test is not very powerful.
Can you do statistics with 4 data points?
Short answer: yes, but your results will usually be useless. Long answer: Statistics often involves forming some kind of inference about underlying parameters based on data, with constraints on the pr
Can you do statistics with 4 data points? Short answer: yes, but your results will usually be useless. Long answer: Statistics often involves forming some kind of inference about underlying parameters based on data, with constraints on the probability of a False-Positive and/or of a False-Negative. In a typical test, i.e. testing if a sample came from a given distribution, we put an upper bound (called alpha) on the probability of a Type-I Error (False Positive), mostly for two reasons: In practice that is the only kind of error you can put a bound on, b/c of the nature of your null hypothesis False Positives are usually considered more terrible than False Negatives (a corollary of Occam's Razor) Holding alpha constant, beta (upper bound of probability of False-Negative) is generally larger for smaller data sets. And when beta is large, your overall probability of producing a Positive is very small, and so your test will almost always return Negative, which is not very different from just accepting your Null Hypothesis from the get-go. In this situtation we say the statistical test is not very powerful.
Can you do statistics with 4 data points? Short answer: yes, but your results will usually be useless. Long answer: Statistics often involves forming some kind of inference about underlying parameters based on data, with constraints on the pr
44,211
Can you do statistics with 4 data points?
I helped with a geological project where the researchers had a single data point, accompanied by a very reliable uncertainty bound. They were interested in testing a geological model (a set of differential equations describing the evolution of tectonic plates) which made a very specific prediction for the value of that single datum. Given its uncertainty distribution, we could straightforwardly calculate a p.value, given the model is true, and reject the null hypothesis convincingly. So, in that case, I would argue that we successfully 'did statistics' with a single data point (and its uncertainty).
Can you do statistics with 4 data points?
I helped with a geological project where the researchers had a single data point, accompanied by a very reliable uncertainty bound. They were interested in testing a geological model (a set of differe
Can you do statistics with 4 data points? I helped with a geological project where the researchers had a single data point, accompanied by a very reliable uncertainty bound. They were interested in testing a geological model (a set of differential equations describing the evolution of tectonic plates) which made a very specific prediction for the value of that single datum. Given its uncertainty distribution, we could straightforwardly calculate a p.value, given the model is true, and reject the null hypothesis convincingly. So, in that case, I would argue that we successfully 'did statistics' with a single data point (and its uncertainty).
Can you do statistics with 4 data points? I helped with a geological project where the researchers had a single data point, accompanied by a very reliable uncertainty bound. They were interested in testing a geological model (a set of differe
44,212
Why is Hedonic Regression used instead of Linear Regression
There is no package for hedonic regression because it isn't a specific kind of regression but a specific application of regression. Linear regression is used. It's called hedonic regression to highlight the method of price estimating and interpretation. You might want to check this question out for more details on modelling prices.
Why is Hedonic Regression used instead of Linear Regression
There is no package for hedonic regression because it isn't a specific kind of regression but a specific application of regression. Linear regression is used. It's called hedonic regression to highl
Why is Hedonic Regression used instead of Linear Regression There is no package for hedonic regression because it isn't a specific kind of regression but a specific application of regression. Linear regression is used. It's called hedonic regression to highlight the method of price estimating and interpretation. You might want to check this question out for more details on modelling prices.
Why is Hedonic Regression used instead of Linear Regression There is no package for hedonic regression because it isn't a specific kind of regression but a specific application of regression. Linear regression is used. It's called hedonic regression to highl
44,213
Why is Hedonic Regression used instead of Linear Regression
It's called hedonic regression because it is used to remove 'hedonic' product features (i.e. features that consumers 'like' or get pleasure from), from the price. The hypothesis is that remaining price changes from period to period are caused by inflation. It is useful where the same product is not sold from period to period - for example the set of houses sold each quarter will be different, with different characteristics (such as size) that have an influence on the price. Typically for a price index you would fit a linear model with a mix of continous (e.g. size in square meters) and categorical variables (e.g. number of bathrooms) to represent product features, and then use residuals in the index in place of the raw prices. You can also explicitly fit some sort of time-trend to the data as part of the model, especially if you are interested in underlying inflation, and you can use dummy variables to estimate effects of economic shocks, etc.
Why is Hedonic Regression used instead of Linear Regression
It's called hedonic regression because it is used to remove 'hedonic' product features (i.e. features that consumers 'like' or get pleasure from), from the price. The hypothesis is that remaining pri
Why is Hedonic Regression used instead of Linear Regression It's called hedonic regression because it is used to remove 'hedonic' product features (i.e. features that consumers 'like' or get pleasure from), from the price. The hypothesis is that remaining price changes from period to period are caused by inflation. It is useful where the same product is not sold from period to period - for example the set of houses sold each quarter will be different, with different characteristics (such as size) that have an influence on the price. Typically for a price index you would fit a linear model with a mix of continous (e.g. size in square meters) and categorical variables (e.g. number of bathrooms) to represent product features, and then use residuals in the index in place of the raw prices. You can also explicitly fit some sort of time-trend to the data as part of the model, especially if you are interested in underlying inflation, and you can use dummy variables to estimate effects of economic shocks, etc.
Why is Hedonic Regression used instead of Linear Regression It's called hedonic regression because it is used to remove 'hedonic' product features (i.e. features that consumers 'like' or get pleasure from), from the price. The hypothesis is that remaining pri
44,214
What have to be normally distributed: groups or whole sample?
Generally it is the residuals that need to be normally distributed. This implies that each group is normally distributed, but you can do the diagnostics on the residuals (values minus group mean) as a whole rather than group by group. It is possible (and even common) that the data will be approximately normal within each group, but since the group means differ the overall dataset will be quite non-normal, but you can still use normal theory tests for this case. Note that the real question is not "exactly normal", but rather "normal enough for the given problem". With small datasets the question of normality is the most important, but you have low power to detect non-normality (unless it is very extreeme), with large datasets the Central Limit Theorem kicks in so your data does not need to be that normal, but you have high power to detect small departures from normality. So when doing formal tests of normality as a condition for doing t-tests or anova you are either in the situation where you have a meaningless answer to a meaningful question, or you have a meaningful answer to a meaningless question (there may be some middle size where both are meaningful, but I expect that the middle range is really where both are meaningless). So, no just because a small sample size does not reject the null does not mean that it is safe to use normal theory methods. Knowledge about the source of the data and some diagnostic plots are likely to be more useful in that decision, or if you are worried about non-normality just go straight to the non-parametric tests. If you really feel the need for a p-value testing exact normality then you can use the SnowsPenultimateNormalityTest function in the TeachingDemos package for R (but be sure to read the help page). Another option for testing "normal enough" if you need more than the diagnostic plots is to use the methodology in: Buja, A., Cook, D. Hofmann, H., Lawrence, M. Lee, E.-K., Swayne, D.F and Wickham, H. (2009) Statistical Inference for exploratory data analysis and model diagnostics Phil. Trans. R. Soc. A 2009 367, 4361-4383 doi: 10.1098/rsta.2009.0120 (the vis.test function in the TeachingDemos package of R is one implementation of this). The impartant thing to take away is that knowledge about the process that produced your data is much more important than the output from some program/algorythm written by someone who knows/knew much less about your data and question than you do.
What have to be normally distributed: groups or whole sample?
Generally it is the residuals that need to be normally distributed. This implies that each group is normally distributed, but you can do the diagnostics on the residuals (values minus group mean) as
What have to be normally distributed: groups or whole sample? Generally it is the residuals that need to be normally distributed. This implies that each group is normally distributed, but you can do the diagnostics on the residuals (values minus group mean) as a whole rather than group by group. It is possible (and even common) that the data will be approximately normal within each group, but since the group means differ the overall dataset will be quite non-normal, but you can still use normal theory tests for this case. Note that the real question is not "exactly normal", but rather "normal enough for the given problem". With small datasets the question of normality is the most important, but you have low power to detect non-normality (unless it is very extreeme), with large datasets the Central Limit Theorem kicks in so your data does not need to be that normal, but you have high power to detect small departures from normality. So when doing formal tests of normality as a condition for doing t-tests or anova you are either in the situation where you have a meaningless answer to a meaningful question, or you have a meaningful answer to a meaningless question (there may be some middle size where both are meaningful, but I expect that the middle range is really where both are meaningless). So, no just because a small sample size does not reject the null does not mean that it is safe to use normal theory methods. Knowledge about the source of the data and some diagnostic plots are likely to be more useful in that decision, or if you are worried about non-normality just go straight to the non-parametric tests. If you really feel the need for a p-value testing exact normality then you can use the SnowsPenultimateNormalityTest function in the TeachingDemos package for R (but be sure to read the help page). Another option for testing "normal enough" if you need more than the diagnostic plots is to use the methodology in: Buja, A., Cook, D. Hofmann, H., Lawrence, M. Lee, E.-K., Swayne, D.F and Wickham, H. (2009) Statistical Inference for exploratory data analysis and model diagnostics Phil. Trans. R. Soc. A 2009 367, 4361-4383 doi: 10.1098/rsta.2009.0120 (the vis.test function in the TeachingDemos package of R is one implementation of this). The impartant thing to take away is that knowledge about the process that produced your data is much more important than the output from some program/algorythm written by someone who knows/knew much less about your data and question than you do.
What have to be normally distributed: groups or whole sample? Generally it is the residuals that need to be normally distributed. This implies that each group is normally distributed, but you can do the diagnostics on the residuals (values minus group mean) as
44,215
What have to be normally distributed: groups or whole sample?
@GregSnow has a really excellent answer here, which I would like to augment with 2 small points. First, while he's right that only the normality of the residuals matters, we can ask the question 'matters for what'? Everyone who has taken stats 101 leaves with the impression that normality is crucial, and that's not really true. The Gauss-Markov theorem tells us that our data do not have to be normal; they simply should be symmetrical and homogeneous. The normality of the residuals is only relevant for the confidence intervals / p-values to be accurate, and even then, only really necessary when sample sizes are small (as @GregSnow points out). When homogeneity of variance obtains, the estimates will be unbiased and efficient whether the residuals are normally distributed or not. My second small addition is that non-parametric tests may not be required with small samples and non-normal residuals--bootstrapping is also a viable option.
What have to be normally distributed: groups or whole sample?
@GregSnow has a really excellent answer here, which I would like to augment with 2 small points. First, while he's right that only the normality of the residuals matters, we can ask the question 'mat
What have to be normally distributed: groups or whole sample? @GregSnow has a really excellent answer here, which I would like to augment with 2 small points. First, while he's right that only the normality of the residuals matters, we can ask the question 'matters for what'? Everyone who has taken stats 101 leaves with the impression that normality is crucial, and that's not really true. The Gauss-Markov theorem tells us that our data do not have to be normal; they simply should be symmetrical and homogeneous. The normality of the residuals is only relevant for the confidence intervals / p-values to be accurate, and even then, only really necessary when sample sizes are small (as @GregSnow points out). When homogeneity of variance obtains, the estimates will be unbiased and efficient whether the residuals are normally distributed or not. My second small addition is that non-parametric tests may not be required with small samples and non-normal residuals--bootstrapping is also a viable option.
What have to be normally distributed: groups or whole sample? @GregSnow has a really excellent answer here, which I would like to augment with 2 small points. First, while he's right that only the normality of the residuals matters, we can ask the question 'mat
44,216
A mathematical formula for K-fold cross-validation prediction error?
There are formulae for computing the leave-one-out cross-validation error in closed form for many models, including least-squares regression, but as far as I am aware there isn't a general formula for k-fold cross-validation (or at least it may be possible but the computational advantage is too small to be worthwhile). The formula in the book isn't saying very much it is just saying that the cross-validation error is the average of the loss function (L) evaluated using models trained on different subsets of the data. The superscript $-\kappa(i)$ just means "model $f$ is trained without the training patterns in the same partition of the dataset as pattern $i$". Sometimes writing things in formal mathematical notation makes things less ambiguous, but it doesn't necessarily make it any easier to understand than the text - I think this is one of those occasions.
A mathematical formula for K-fold cross-validation prediction error?
There are formulae for computing the leave-one-out cross-validation error in closed form for many models, including least-squares regression, but as far as I am aware there isn't a general formula for
A mathematical formula for K-fold cross-validation prediction error? There are formulae for computing the leave-one-out cross-validation error in closed form for many models, including least-squares regression, but as far as I am aware there isn't a general formula for k-fold cross-validation (or at least it may be possible but the computational advantage is too small to be worthwhile). The formula in the book isn't saying very much it is just saying that the cross-validation error is the average of the loss function (L) evaluated using models trained on different subsets of the data. The superscript $-\kappa(i)$ just means "model $f$ is trained without the training patterns in the same partition of the dataset as pattern $i$". Sometimes writing things in formal mathematical notation makes things less ambiguous, but it doesn't necessarily make it any easier to understand than the text - I think this is one of those occasions.
A mathematical formula for K-fold cross-validation prediction error? There are formulae for computing the leave-one-out cross-validation error in closed form for many models, including least-squares regression, but as far as I am aware there isn't a general formula for
44,217
A mathematical formula for K-fold cross-validation prediction error?
The reason people do cross-validation is that there is no mathematical formula to accurately get at the same thing except under very restrictive conditions. And note that k-fold cross-validation does not have adequate precision in most cases, so you have to repeat k-fold cross-validation often 50-100 times (and average the performance metric) to get accurate, precise estimates of model performance. There is certainly no mathematical formula for that.
A mathematical formula for K-fold cross-validation prediction error?
The reason people do cross-validation is that there is no mathematical formula to accurately get at the same thing except under very restrictive conditions. And note that k-fold cross-validation does
A mathematical formula for K-fold cross-validation prediction error? The reason people do cross-validation is that there is no mathematical formula to accurately get at the same thing except under very restrictive conditions. And note that k-fold cross-validation does not have adequate precision in most cases, so you have to repeat k-fold cross-validation often 50-100 times (and average the performance metric) to get accurate, precise estimates of model performance. There is certainly no mathematical formula for that.
A mathematical formula for K-fold cross-validation prediction error? The reason people do cross-validation is that there is no mathematical formula to accurately get at the same thing except under very restrictive conditions. And note that k-fold cross-validation does
44,218
A mathematical formula for K-fold cross-validation prediction error?
The truth is that cross-validation is simply a heuristic for model selection. If what you are really looking for is obtaining a theoretically-backed estimate of your generalization prediction, cross-validation can only give a good estimate of it but there are no guarantees. A better fit for that would be learning theoretical frameworks such as the PAC-Bayes setting. However those frameworks have their own short-comings, mostly related to the fact that bounds tend to be to loose/general (for example a bound telling you that you're not going to predict wrong more than 100% of the time). However some people have tried to formalize the cross-validation heuristic. You may want to take a look at the references in this post from John Langford. http://hunch.net/?p=29
A mathematical formula for K-fold cross-validation prediction error?
The truth is that cross-validation is simply a heuristic for model selection. If what you are really looking for is obtaining a theoretically-backed estimate of your generalization prediction, cross-
A mathematical formula for K-fold cross-validation prediction error? The truth is that cross-validation is simply a heuristic for model selection. If what you are really looking for is obtaining a theoretically-backed estimate of your generalization prediction, cross-validation can only give a good estimate of it but there are no guarantees. A better fit for that would be learning theoretical frameworks such as the PAC-Bayes setting. However those frameworks have their own short-comings, mostly related to the fact that bounds tend to be to loose/general (for example a bound telling you that you're not going to predict wrong more than 100% of the time). However some people have tried to formalize the cross-validation heuristic. You may want to take a look at the references in this post from John Langford. http://hunch.net/?p=29
A mathematical formula for K-fold cross-validation prediction error? The truth is that cross-validation is simply a heuristic for model selection. If what you are really looking for is obtaining a theoretically-backed estimate of your generalization prediction, cross-
44,219
A mathematical formula for K-fold cross-validation prediction error?
I think that what the person was asking the question needs is simply a formula that is more explanatory, or a full-blown explanation of the formula. I'm posting this for the sake of others looking for an answer. Here is how I understand it. Start with a less abstract loss function, say the MSE. Once you divide your data set into K subsets, you calculate the MSE where the test set is one of the subsets k and the function f^(-k)(x_i) is calculated over the training set made of all the points minus subset k. You get MSE(k)=K/N*sum_{all points in subset k} (y_j - f^(-k)(x_i))^2. Note that to obtain the average you divide by N/K which is the number of points in subset k. 3. Now you take the average over all K subsets, and you obtain: MSE = 1/K * sum_k MSE(k) K and K simplify and MSE becomes simply MSE = 1/N * sum_{all points!} (y_j - f^(-k)(x_i))^2 Note that each point is counted exactly once. That's why instead of f^(-k) you can write like Hastie et al. "f^(-k(i))". THe extension to a generic loss function should be trivial. Hope this clarifies.
A mathematical formula for K-fold cross-validation prediction error?
I think that what the person was asking the question needs is simply a formula that is more explanatory, or a full-blown explanation of the formula. I'm posting this for the sake of others looking for
A mathematical formula for K-fold cross-validation prediction error? I think that what the person was asking the question needs is simply a formula that is more explanatory, or a full-blown explanation of the formula. I'm posting this for the sake of others looking for an answer. Here is how I understand it. Start with a less abstract loss function, say the MSE. Once you divide your data set into K subsets, you calculate the MSE where the test set is one of the subsets k and the function f^(-k)(x_i) is calculated over the training set made of all the points minus subset k. You get MSE(k)=K/N*sum_{all points in subset k} (y_j - f^(-k)(x_i))^2. Note that to obtain the average you divide by N/K which is the number of points in subset k. 3. Now you take the average over all K subsets, and you obtain: MSE = 1/K * sum_k MSE(k) K and K simplify and MSE becomes simply MSE = 1/N * sum_{all points!} (y_j - f^(-k)(x_i))^2 Note that each point is counted exactly once. That's why instead of f^(-k) you can write like Hastie et al. "f^(-k(i))". THe extension to a generic loss function should be trivial. Hope this clarifies.
A mathematical formula for K-fold cross-validation prediction error? I think that what the person was asking the question needs is simply a formula that is more explanatory, or a full-blown explanation of the formula. I'm posting this for the sake of others looking for
44,220
What is the distribution of the Binomial distribution parameter $p$ given a sample k and n?
From a bayesian point of view the distribution of p with k empirical successes and n trials is the Beta-Distribution, in detail $p\sim Beta(\alpha,\beta)$ with $\alpha=k+1$ and $\beta=n-k+1$. It represents the unnormalized density $prob(p|data)$, i.e. the unormalized probability that the unknown parameter is $p$ given the data (successes and trials) you have seen so far. Edit: Let n be arbitrary but fixed. Then the posterior density can be derived via Bayes theorem $prob(p|k)=\frac{prob(k|p)*prob(p)}{prob(k)}\propto prob(k|p)\propto p^k(1-p)^{n-k}$. A uniform prior $prob(p)$ is assumed here, the normalizing constant $prob(k)$ is skipped since it does not depend on p. Hence "unnormalized". The distribution of $prob(p|k)$ given a fixed n (i.e. $prob(p|k,n)$) is the Betadistribution as specified above. For example: The r-package binom uses the Betadistribution for calculating confidence intervals. See the methods biom.confint i.e. binom.bayes
What is the distribution of the Binomial distribution parameter $p$ given a sample k and n?
From a bayesian point of view the distribution of p with k empirical successes and n trials is the Beta-Distribution, in detail $p\sim Beta(\alpha,\beta)$ with $\alpha=k+1$ and $\beta=n-k+1$. It repre
What is the distribution of the Binomial distribution parameter $p$ given a sample k and n? From a bayesian point of view the distribution of p with k empirical successes and n trials is the Beta-Distribution, in detail $p\sim Beta(\alpha,\beta)$ with $\alpha=k+1$ and $\beta=n-k+1$. It represents the unnormalized density $prob(p|data)$, i.e. the unormalized probability that the unknown parameter is $p$ given the data (successes and trials) you have seen so far. Edit: Let n be arbitrary but fixed. Then the posterior density can be derived via Bayes theorem $prob(p|k)=\frac{prob(k|p)*prob(p)}{prob(k)}\propto prob(k|p)\propto p^k(1-p)^{n-k}$. A uniform prior $prob(p)$ is assumed here, the normalizing constant $prob(k)$ is skipped since it does not depend on p. Hence "unnormalized". The distribution of $prob(p|k)$ given a fixed n (i.e. $prob(p|k,n)$) is the Betadistribution as specified above. For example: The r-package binom uses the Betadistribution for calculating confidence intervals. See the methods biom.confint i.e. binom.bayes
What is the distribution of the Binomial distribution parameter $p$ given a sample k and n? From a bayesian point of view the distribution of p with k empirical successes and n trials is the Beta-Distribution, in detail $p\sim Beta(\alpha,\beta)$ with $\alpha=k+1$ and $\beta=n-k+1$. It repre
44,221
What is the distribution of the Binomial distribution parameter $p$ given a sample k and n?
The sample proportion $\hat{p}=k/n$ has a scaled Binomial distribution. That is $k\sim\text{Binomial}(n,p)$ which is scaled by the sample size $n$. I don't think it has any other name.
What is the distribution of the Binomial distribution parameter $p$ given a sample k and n?
The sample proportion $\hat{p}=k/n$ has a scaled Binomial distribution. That is $k\sim\text{Binomial}(n,p)$ which is scaled by the sample size $n$. I don't think it has any other name.
What is the distribution of the Binomial distribution parameter $p$ given a sample k and n? The sample proportion $\hat{p}=k/n$ has a scaled Binomial distribution. That is $k\sim\text{Binomial}(n,p)$ which is scaled by the sample size $n$. I don't think it has any other name.
What is the distribution of the Binomial distribution parameter $p$ given a sample k and n? The sample proportion $\hat{p}=k/n$ has a scaled Binomial distribution. That is $k\sim\text{Binomial}(n,p)$ which is scaled by the sample size $n$. I don't think it has any other name.
44,222
Uncorrected pairwise p-values for one-way ANOVA?
For the multcomp package, see the help page for glht; you want to use the "Tukey" option; this does not actually use the Tukey correction, it just sets up all pairwise comparisons. In the example section there's an example that does exactly what you want. This calculates the estimates and se's for each comparison but doesn't do p-values; for that you need summary.glht; on the help page for that, notice in particular the test parameter, that allows you to set the actual test that is run. For doing multiply-adjusted p-values, you use the adjusted function for this parameter, and to not multiply-adjust, you use test=adjusted("none") (which isn't mention specifically in the help page, though it does say it takes any of the methods in p.adjust, which is where you'd find none.) You can also compute the estimates and se's by hand using matrix multiplication, and then get the p-values however you want; this is what the glht function is doing behind the scenes. To get the matrices you need to start you'd use coef and vcov. I didn't put complete code as you say it's for a class project (thanks for being honest, by the way!) and the policy here is to provide helpful hints but not solutions.
Uncorrected pairwise p-values for one-way ANOVA?
For the multcomp package, see the help page for glht; you want to use the "Tukey" option; this does not actually use the Tukey correction, it just sets up all pairwise comparisons. In the example sec
Uncorrected pairwise p-values for one-way ANOVA? For the multcomp package, see the help page for glht; you want to use the "Tukey" option; this does not actually use the Tukey correction, it just sets up all pairwise comparisons. In the example section there's an example that does exactly what you want. This calculates the estimates and se's for each comparison but doesn't do p-values; for that you need summary.glht; on the help page for that, notice in particular the test parameter, that allows you to set the actual test that is run. For doing multiply-adjusted p-values, you use the adjusted function for this parameter, and to not multiply-adjust, you use test=adjusted("none") (which isn't mention specifically in the help page, though it does say it takes any of the methods in p.adjust, which is where you'd find none.) You can also compute the estimates and se's by hand using matrix multiplication, and then get the p-values however you want; this is what the glht function is doing behind the scenes. To get the matrices you need to start you'd use coef and vcov. I didn't put complete code as you say it's for a class project (thanks for being honest, by the way!) and the policy here is to provide helpful hints but not solutions.
Uncorrected pairwise p-values for one-way ANOVA? For the multcomp package, see the help page for glht; you want to use the "Tukey" option; this does not actually use the Tukey correction, it just sets up all pairwise comparisons. In the example sec
44,223
Uncorrected pairwise p-values for one-way ANOVA?
You can use pairwise.t.test() with one of the available options for multiple comparison correction in the p.adjust.method= argument; see help(p.adjust) for more information on the available option for single-step and step-down methods (e.g., BH for FDR or bonf for Bonferroni). Of note, you can directly give p.adjust() a vector of raw p-values and it will give you the corrected p-values. So, I would suggest to run something like pairwise.t.test(time, breed, p.adjust.method ="none") # uncorrected p-value pairwise.t.test(time, breed, p.adjust.method ="bonf") # Bonferroni p-value The first command gives you t-test-based p-values without controlling for FWER or FDR. You can then use whatever command you like to get corrected p-values.
Uncorrected pairwise p-values for one-way ANOVA?
You can use pairwise.t.test() with one of the available options for multiple comparison correction in the p.adjust.method= argument; see help(p.adjust) for more information on the available option for
Uncorrected pairwise p-values for one-way ANOVA? You can use pairwise.t.test() with one of the available options for multiple comparison correction in the p.adjust.method= argument; see help(p.adjust) for more information on the available option for single-step and step-down methods (e.g., BH for FDR or bonf for Bonferroni). Of note, you can directly give p.adjust() a vector of raw p-values and it will give you the corrected p-values. So, I would suggest to run something like pairwise.t.test(time, breed, p.adjust.method ="none") # uncorrected p-value pairwise.t.test(time, breed, p.adjust.method ="bonf") # Bonferroni p-value The first command gives you t-test-based p-values without controlling for FWER or FDR. You can then use whatever command you like to get corrected p-values.
Uncorrected pairwise p-values for one-way ANOVA? You can use pairwise.t.test() with one of the available options for multiple comparison correction in the p.adjust.method= argument; see help(p.adjust) for more information on the available option for
44,224
Uncorrected pairwise p-values for one-way ANOVA?
library(multcomp) df = mtcars df$am = as.factor(df$am) m1 <- aov(mpg ~ am, data= df) ht = glht(m1, linfct = mcp(am = "Tukey")) summary(ht, test = adjusted("none")) # Linear Hypotheses: # Estimate Std. Error t value Pr(>|t|) # 1 - 0 == 0 7.245 1.764 4.106 0.000285 ***
Uncorrected pairwise p-values for one-way ANOVA?
library(multcomp) df = mtcars df$am = as.factor(df$am) m1 <- aov(mpg ~ am, data= df) ht = glht(m1, linfct = mcp(am = "Tukey")) summary(ht, test = adjusted("none")) # Linear Hypotheses: # Es
Uncorrected pairwise p-values for one-way ANOVA? library(multcomp) df = mtcars df$am = as.factor(df$am) m1 <- aov(mpg ~ am, data= df) ht = glht(m1, linfct = mcp(am = "Tukey")) summary(ht, test = adjusted("none")) # Linear Hypotheses: # Estimate Std. Error t value Pr(>|t|) # 1 - 0 == 0 7.245 1.764 4.106 0.000285 ***
Uncorrected pairwise p-values for one-way ANOVA? library(multcomp) df = mtcars df$am = as.factor(df$am) m1 <- aov(mpg ~ am, data= df) ht = glht(m1, linfct = mcp(am = "Tukey")) summary(ht, test = adjusted("none")) # Linear Hypotheses: # Es
44,225
Identify probability distributions
The short answer is that you can't. The longer answer is that you really need to think about what you are trying to accomplish and what question(s) you are trying to answer. Tests on distributions are not designed to prove a particular distribution, but to disprove (they are not perfect for that, you still have type I and type II errors). But, often establishing an exact distribution is less important than finding a reasonable approximation. With round-off error and machine precision, you can not tell the difference between whether the data came from a normal distribution or another distribution that is only slightly different from the normal without an infinite amount of data (and still maybe not then due to the round-off). But treating such data as normal is probably still reasonable. The CLT tells us that we can often model using the normal distribution even when the data is clearly not from a normal distribution (provided we are modeling the behavior of the sample mean, not the population). What is more important than the statistical tests and proofs is knowledge of the science that generated the data. Is a particular distribution (and the assumptions that go with it) reasonable from the science? I prefer a visual test rather than the exact test for looking at distributions, generate data from the hypothesized distribution and create several plots, one with the original data, the rest with the generated data, then see if you can pick out which is different (the vis.test function in the TeachingDemos package for R does this). If you can't tell which is different then the hypothesized distribution is probably "close enough". Even if you can tell the difference you may decide that the differences are not that important. If you want to generate new data from a distribution similar to your existing data then you can take bootstrap samples, or bootstrap samples plus some random noise (this is sampling from the kernel density estimate), or you can do a logspline fit and generate from that distribution (see the logspline package for R as one tool for this).
Identify probability distributions
The short answer is that you can't. The longer answer is that you really need to think about what you are trying to accomplish and what question(s) you are trying to answer. Tests on distributions are
Identify probability distributions The short answer is that you can't. The longer answer is that you really need to think about what you are trying to accomplish and what question(s) you are trying to answer. Tests on distributions are not designed to prove a particular distribution, but to disprove (they are not perfect for that, you still have type I and type II errors). But, often establishing an exact distribution is less important than finding a reasonable approximation. With round-off error and machine precision, you can not tell the difference between whether the data came from a normal distribution or another distribution that is only slightly different from the normal without an infinite amount of data (and still maybe not then due to the round-off). But treating such data as normal is probably still reasonable. The CLT tells us that we can often model using the normal distribution even when the data is clearly not from a normal distribution (provided we are modeling the behavior of the sample mean, not the population). What is more important than the statistical tests and proofs is knowledge of the science that generated the data. Is a particular distribution (and the assumptions that go with it) reasonable from the science? I prefer a visual test rather than the exact test for looking at distributions, generate data from the hypothesized distribution and create several plots, one with the original data, the rest with the generated data, then see if you can pick out which is different (the vis.test function in the TeachingDemos package for R does this). If you can't tell which is different then the hypothesized distribution is probably "close enough". Even if you can tell the difference you may decide that the differences are not that important. If you want to generate new data from a distribution similar to your existing data then you can take bootstrap samples, or bootstrap samples plus some random noise (this is sampling from the kernel density estimate), or you can do a logspline fit and generate from that distribution (see the logspline package for R as one tool for this).
Identify probability distributions The short answer is that you can't. The longer answer is that you really need to think about what you are trying to accomplish and what question(s) you are trying to answer. Tests on distributions are
44,226
Identify probability distributions
The only way to "prove" that data comes from a certain distribution (without an infinite number of samples) is to know precisely how that data is generated. For example, if you know that the data came from the magnitude of a circular bivariate normal random variable, it has a Rician distribution. Or if the data came from the time between events in a Poisson process, then it has an exponential distribution. Lacking a precise definition of the generating process, there are a number of empirical measures you can use to determine the underlying distribution. First, look at the data itself: Is it discrete or continuous? Is it supported on (-inf,inf), [0,inf),(0,1), or another interval? This knowledge can be used to narrow down the possible univariate parametric distributions that could fit your data. Examples include the Gaussian distribution, Cauchy, Exponential, Gamma, Generalized Extreme Value, Rician, Wrapped Cauchy, Von Mises, Binomial, and Beta. Once you have determined the support of the distribution, test the potential univariate distributions with an information criterion - such as Akaike information criterion (AIC) or Bayesian information criterion (BIC). These balance the number of parameters in a given distribution with the likelihood of the data fitting a given distribution. Visually check the best-scoring distribution(s) to see if they appear to fit the data. An alternative is to construct a kernel density estimate of the data. This is basically a sophisticated version of creating a histogram of the data, where a small Gaussian (or other) distribution is placed at each data point, and the estimated distribution is constructed from the sum of these. For more information, see Kernel Density Estimation. This has the advantage of being able to fit arbitrary distributions in the data, but sampling from this distribution has a large computational cost, especially with large data sets. Another option is to construct a Gaussian Mixture Model (GMM) from the data, where a small number of Gaussian distributions are used to approximate the underlying distribution. For more information, see Mixture Models. The method appropriate for your application depends on the application itself. If you can determine the distribution from the generating process, great, estimate the parameters and your done! If not, the next-best scenario is finding a univariate parametric distribution that accurately describes the data. Lacking that, mixture models, KDEs, or other methods can be used to approximate the distribution.
Identify probability distributions
The only way to "prove" that data comes from a certain distribution (without an infinite number of samples) is to know precisely how that data is generated. For example, if you know that the data cam
Identify probability distributions The only way to "prove" that data comes from a certain distribution (without an infinite number of samples) is to know precisely how that data is generated. For example, if you know that the data came from the magnitude of a circular bivariate normal random variable, it has a Rician distribution. Or if the data came from the time between events in a Poisson process, then it has an exponential distribution. Lacking a precise definition of the generating process, there are a number of empirical measures you can use to determine the underlying distribution. First, look at the data itself: Is it discrete or continuous? Is it supported on (-inf,inf), [0,inf),(0,1), or another interval? This knowledge can be used to narrow down the possible univariate parametric distributions that could fit your data. Examples include the Gaussian distribution, Cauchy, Exponential, Gamma, Generalized Extreme Value, Rician, Wrapped Cauchy, Von Mises, Binomial, and Beta. Once you have determined the support of the distribution, test the potential univariate distributions with an information criterion - such as Akaike information criterion (AIC) or Bayesian information criterion (BIC). These balance the number of parameters in a given distribution with the likelihood of the data fitting a given distribution. Visually check the best-scoring distribution(s) to see if they appear to fit the data. An alternative is to construct a kernel density estimate of the data. This is basically a sophisticated version of creating a histogram of the data, where a small Gaussian (or other) distribution is placed at each data point, and the estimated distribution is constructed from the sum of these. For more information, see Kernel Density Estimation. This has the advantage of being able to fit arbitrary distributions in the data, but sampling from this distribution has a large computational cost, especially with large data sets. Another option is to construct a Gaussian Mixture Model (GMM) from the data, where a small number of Gaussian distributions are used to approximate the underlying distribution. For more information, see Mixture Models. The method appropriate for your application depends on the application itself. If you can determine the distribution from the generating process, great, estimate the parameters and your done! If not, the next-best scenario is finding a univariate parametric distribution that accurately describes the data. Lacking that, mixture models, KDEs, or other methods can be used to approximate the distribution.
Identify probability distributions The only way to "prove" that data comes from a certain distribution (without an infinite number of samples) is to know precisely how that data is generated. For example, if you know that the data cam
44,227
Identify probability distributions
If you're trying to do Exploratory Data Analysis, you could use some graphical techniques. I can suggest chapter 1.3.4 in the NIST handbook. In particular, any of the probability graphs might be insightful (e.g. Probability Plot Correlation Coefficient Plot, Quantile-Quantile Plot, etc.). For a number of common distributions, you could try fitting to the Tukey-Lambda distribution, and extracting the distribution information from the fitted value of the lambda shape parameter.
Identify probability distributions
If you're trying to do Exploratory Data Analysis, you could use some graphical techniques. I can suggest chapter 1.3.4 in the NIST handbook. In particular, any of the probability graphs might be insig
Identify probability distributions If you're trying to do Exploratory Data Analysis, you could use some graphical techniques. I can suggest chapter 1.3.4 in the NIST handbook. In particular, any of the probability graphs might be insightful (e.g. Probability Plot Correlation Coefficient Plot, Quantile-Quantile Plot, etc.). For a number of common distributions, you could try fitting to the Tukey-Lambda distribution, and extracting the distribution information from the fitted value of the lambda shape parameter.
Identify probability distributions If you're trying to do Exploratory Data Analysis, you could use some graphical techniques. I can suggest chapter 1.3.4 in the NIST handbook. In particular, any of the probability graphs might be insig
44,228
How to fit a model to self-reported number of friend interactions over a 20 day period?
First off, your response variable is discrete. The Cauchy distribution is continuous. Second, your response variable is non-negative. The Cauchy distribution with the parameters you specified puts about 1/5 of its mass on negative values. Whatever you have been reading about the QQ norm plot is false. Points falling close to the line is evidence of normality, not evidence in favor of being Cauchy distributed (EDIT: Disregard these last 2 sentences; a QQ Cauchy plot - not a QQ norm plot - was used, which is fine.) The Poisson distribution, used for modeling count data, is inappropriate since the variance is much larger than the mean. The Binomial distribution is also inappropriate since theoretically, your response variable has no upper bound. I'd look into the negative binomial distribution. As a final note, your data does not necessarily have to come from a well known, "named" distribution. It may have come from a mixture of distributions, or may have a "true" distribution whose mass function is not a nice transformation of x to P(X=x). Don't try too hard to "force" a distribution to the data.
How to fit a model to self-reported number of friend interactions over a 20 day period?
First off, your response variable is discrete. The Cauchy distribution is continuous. Second, your response variable is non-negative. The Cauchy distribution with the parameters you specified puts abo
How to fit a model to self-reported number of friend interactions over a 20 day period? First off, your response variable is discrete. The Cauchy distribution is continuous. Second, your response variable is non-negative. The Cauchy distribution with the parameters you specified puts about 1/5 of its mass on negative values. Whatever you have been reading about the QQ norm plot is false. Points falling close to the line is evidence of normality, not evidence in favor of being Cauchy distributed (EDIT: Disregard these last 2 sentences; a QQ Cauchy plot - not a QQ norm plot - was used, which is fine.) The Poisson distribution, used for modeling count data, is inappropriate since the variance is much larger than the mean. The Binomial distribution is also inappropriate since theoretically, your response variable has no upper bound. I'd look into the negative binomial distribution. As a final note, your data does not necessarily have to come from a well known, "named" distribution. It may have come from a mixture of distributions, or may have a "true" distribution whose mass function is not a nice transformation of x to P(X=x). Don't try too hard to "force" a distribution to the data.
How to fit a model to self-reported number of friend interactions over a 20 day period? First off, your response variable is discrete. The Cauchy distribution is continuous. Second, your response variable is non-negative. The Cauchy distribution with the parameters you specified puts abo
44,229
How to fit a model to self-reported number of friend interactions over a 20 day period?
Agree with HairyBeast (+1) that Cauchy is not appropriate here (it's symmetric for one thing) and that negative binomial might well be better. Disagree about QQ-plot though. You can do a QQ-plot for any distribution, not just normal. What you say about interpretation of a QQ-plot is correct, but note that 2 of your points lie very far indeed from the straight line. On the Cauchy's lack of moments: this doesn't affect sampling. Once you know the parameters of the distribution sampling from it is easy (as the quantile function has a closed form) and the lack of moments is irrelevant. But the fact that the Cauchy distribution doesn't even have a mean does indicate that it's inappropriate here, as clearly it is meaningful to ask what's the expected number of friends with whom a person has a conversation in a 20-day period.
How to fit a model to self-reported number of friend interactions over a 20 day period?
Agree with HairyBeast (+1) that Cauchy is not appropriate here (it's symmetric for one thing) and that negative binomial might well be better. Disagree about QQ-plot though. You can do a QQ-plot for a
How to fit a model to self-reported number of friend interactions over a 20 day period? Agree with HairyBeast (+1) that Cauchy is not appropriate here (it's symmetric for one thing) and that negative binomial might well be better. Disagree about QQ-plot though. You can do a QQ-plot for any distribution, not just normal. What you say about interpretation of a QQ-plot is correct, but note that 2 of your points lie very far indeed from the straight line. On the Cauchy's lack of moments: this doesn't affect sampling. Once you know the parameters of the distribution sampling from it is easy (as the quantile function has a closed form) and the lack of moments is irrelevant. But the fact that the Cauchy distribution doesn't even have a mean does indicate that it's inappropriate here, as clearly it is meaningful to ask what's the expected number of friends with whom a person has a conversation in a 20-day period.
How to fit a model to self-reported number of friend interactions over a 20 day period? Agree with HairyBeast (+1) that Cauchy is not appropriate here (it's symmetric for one thing) and that negative binomial might well be better. Disagree about QQ-plot though. You can do a QQ-plot for a
44,230
Is it possible to use machine learning as a method for learning stats, rather than vice-versa?
I really wouldn't suggest using machine learning in order to learn statistics. The mathematics employed in machine learning is often different because there's a real emphasis on the computational algorithm. Even treatment of the same concept will be different. A simple example of this would be to compare the treatment of linear regression between a basic statistics textbook and a machine learning textbook. Most machine learning texts give a heavy treatment to concepts like "gradient descent" and other optimzation techniques, while a statistics textbook will typically just cover ordinary least squares (if even that). Lastly, machine learning generally doesn't cover the same material when it comes to things like model comparison, sampling, etc. So while some of the basic models are the same, the conceptual frameworks can be very different.
Is it possible to use machine learning as a method for learning stats, rather than vice-versa?
I really wouldn't suggest using machine learning in order to learn statistics. The mathematics employed in machine learning is often different because there's a real emphasis on the computational alg
Is it possible to use machine learning as a method for learning stats, rather than vice-versa? I really wouldn't suggest using machine learning in order to learn statistics. The mathematics employed in machine learning is often different because there's a real emphasis on the computational algorithm. Even treatment of the same concept will be different. A simple example of this would be to compare the treatment of linear regression between a basic statistics textbook and a machine learning textbook. Most machine learning texts give a heavy treatment to concepts like "gradient descent" and other optimzation techniques, while a statistics textbook will typically just cover ordinary least squares (if even that). Lastly, machine learning generally doesn't cover the same material when it comes to things like model comparison, sampling, etc. So while some of the basic models are the same, the conceptual frameworks can be very different.
Is it possible to use machine learning as a method for learning stats, rather than vice-versa? I really wouldn't suggest using machine learning in order to learn statistics. The mathematics employed in machine learning is often different because there's a real emphasis on the computational alg
44,231
Is it possible to use machine learning as a method for learning stats, rather than vice-versa?
It's like that old joke. When asked for directions the philosopher said "Well, if I wanted to go there, I wouldn't start from here ..." While I think each "culture" should be open to learning from the other, they have different ways of looking at the world. I think the problem with learning statistics through studying machine learning algorithms is that, whilst ML algorithms start with statistical concepts, statistics doesn't start with algorithms, but probability models.
Is it possible to use machine learning as a method for learning stats, rather than vice-versa?
It's like that old joke. When asked for directions the philosopher said "Well, if I wanted to go there, I wouldn't start from here ..." While I think each "culture" should be open to learning from the
Is it possible to use machine learning as a method for learning stats, rather than vice-versa? It's like that old joke. When asked for directions the philosopher said "Well, if I wanted to go there, I wouldn't start from here ..." While I think each "culture" should be open to learning from the other, they have different ways of looking at the world. I think the problem with learning statistics through studying machine learning algorithms is that, whilst ML algorithms start with statistical concepts, statistics doesn't start with algorithms, but probability models.
Is it possible to use machine learning as a method for learning stats, rather than vice-versa? It's like that old joke. When asked for directions the philosopher said "Well, if I wanted to go there, I wouldn't start from here ..." While I think each "culture" should be open to learning from the
44,232
Is it possible to use machine learning as a method for learning stats, rather than vice-versa?
Depends on what you mean. I've gotten deeper and deeper into statistics based on exposure to machine learning. (I had previously been more of a general AI guy, and hadn't had good experience with statistics, but gained greater understanding and appreciation of statistics as time has gone on.) So it's certainly a useful gateway. I've been mostly self-taught in statistics, however, and that leaves a lot of holes. I understand and use some fairly advanced techniques, but I wouldn't have to get too far off of the path to get stymied, while someone with a firmer statistical foundation would not. And I think that would apply in your scenario of using Machine Learning as the way to learn statistics: your knowledge would be fragile.
Is it possible to use machine learning as a method for learning stats, rather than vice-versa?
Depends on what you mean. I've gotten deeper and deeper into statistics based on exposure to machine learning. (I had previously been more of a general AI guy, and hadn't had good experience with stat
Is it possible to use machine learning as a method for learning stats, rather than vice-versa? Depends on what you mean. I've gotten deeper and deeper into statistics based on exposure to machine learning. (I had previously been more of a general AI guy, and hadn't had good experience with statistics, but gained greater understanding and appreciation of statistics as time has gone on.) So it's certainly a useful gateway. I've been mostly self-taught in statistics, however, and that leaves a lot of holes. I understand and use some fairly advanced techniques, but I wouldn't have to get too far off of the path to get stymied, while someone with a firmer statistical foundation would not. And I think that would apply in your scenario of using Machine Learning as the way to learn statistics: your knowledge would be fragile.
Is it possible to use machine learning as a method for learning stats, rather than vice-versa? Depends on what you mean. I've gotten deeper and deeper into statistics based on exposure to machine learning. (I had previously been more of a general AI guy, and hadn't had good experience with stat
44,233
Is it possible to use machine learning as a method for learning stats, rather than vice-versa?
I really dont think so, as there are fundamental aspects in statistics that are simply overlooked in machine learning. For instance, in statistics, when fitting a model to data, the discrpeancy function that is used (e.g., G^2, RMSEA) is essential because they have different statistical properties. In machine learning, it just doesnt matter, so it is not covered at all. Of course one could argue that you could learn those things later, but IMHO, it is better to undestand and care about some issues, and possibly in the future not care about them, then the other way around. cheers
Is it possible to use machine learning as a method for learning stats, rather than vice-versa?
I really dont think so, as there are fundamental aspects in statistics that are simply overlooked in machine learning. For instance, in statistics, when fitting a model to data, the discrpeancy functi
Is it possible to use machine learning as a method for learning stats, rather than vice-versa? I really dont think so, as there are fundamental aspects in statistics that are simply overlooked in machine learning. For instance, in statistics, when fitting a model to data, the discrpeancy function that is used (e.g., G^2, RMSEA) is essential because they have different statistical properties. In machine learning, it just doesnt matter, so it is not covered at all. Of course one could argue that you could learn those things later, but IMHO, it is better to undestand and care about some issues, and possibly in the future not care about them, then the other way around. cheers
Is it possible to use machine learning as a method for learning stats, rather than vice-versa? I really dont think so, as there are fundamental aspects in statistics that are simply overlooked in machine learning. For instance, in statistics, when fitting a model to data, the discrpeancy functi
44,234
Is it possible to use machine learning as a method for learning stats, rather than vice-versa?
I think that learning machine learning requires only an elementary subset of statistics; too much may be dangerous, since some intuitions are in conflict. Still, the answer to the question can it be reversed is no.
Is it possible to use machine learning as a method for learning stats, rather than vice-versa?
I think that learning machine learning requires only an elementary subset of statistics; too much may be dangerous, since some intuitions are in conflict. Still, the answer to the question can it be r
Is it possible to use machine learning as a method for learning stats, rather than vice-versa? I think that learning machine learning requires only an elementary subset of statistics; too much may be dangerous, since some intuitions are in conflict. Still, the answer to the question can it be reversed is no.
Is it possible to use machine learning as a method for learning stats, rather than vice-versa? I think that learning machine learning requires only an elementary subset of statistics; too much may be dangerous, since some intuitions are in conflict. Still, the answer to the question can it be r
44,235
Relationship between z-score and the normal distribution [duplicate]
The ``normal distribution'' is an entire family of different distributions. We use the notation $\textbf{Normal}(\mu,\sigma^2)$ to indicate what type of normal we get. If you pick a certain choice for $\mu$ and you pick another choice (positive) for $\sigma$, then you get a different type of Normal. Here are some pictures taken from Wikipedia: If you vary $\mu$ you are varying where the center of the distribution. If you vary $\sigma$ you are varying how spread out the distribution is. The "standard normal distribution", is the one where $\mu=0$ and $\sigma = 1$. Since there is an infinite family of normal distributions it would be annoying to have different functions/calculators for each one. So it is convenient to convert all normal distributions into the "standard normal" form. If $x_1,x_2,...,x_n$ are samples from some normal distribution you replace each $x_i$ in that list by, $$ x_i \mapsto \frac{x_i - (\text{sample mean})}{(\text{sample deviation})}$$ This is known as "calculating the z-score for each $x_i$". By doing this process you have transformed your original data set $x_1,...,x_n$ into a new data set $z_1,...,z_n$, but in such a way so that the new data set follows a normal distribution of type $\text{Normal}(0,1)$.
Relationship between z-score and the normal distribution [duplicate]
The ``normal distribution'' is an entire family of different distributions. We use the notation $\textbf{Normal}(\mu,\sigma^2)$ to indicate what type of normal we get. If you pick a certain choice for
Relationship between z-score and the normal distribution [duplicate] The ``normal distribution'' is an entire family of different distributions. We use the notation $\textbf{Normal}(\mu,\sigma^2)$ to indicate what type of normal we get. If you pick a certain choice for $\mu$ and you pick another choice (positive) for $\sigma$, then you get a different type of Normal. Here are some pictures taken from Wikipedia: If you vary $\mu$ you are varying where the center of the distribution. If you vary $\sigma$ you are varying how spread out the distribution is. The "standard normal distribution", is the one where $\mu=0$ and $\sigma = 1$. Since there is an infinite family of normal distributions it would be annoying to have different functions/calculators for each one. So it is convenient to convert all normal distributions into the "standard normal" form. If $x_1,x_2,...,x_n$ are samples from some normal distribution you replace each $x_i$ in that list by, $$ x_i \mapsto \frac{x_i - (\text{sample mean})}{(\text{sample deviation})}$$ This is known as "calculating the z-score for each $x_i$". By doing this process you have transformed your original data set $x_1,...,x_n$ into a new data set $z_1,...,z_n$, but in such a way so that the new data set follows a normal distribution of type $\text{Normal}(0,1)$.
Relationship between z-score and the normal distribution [duplicate] The ``normal distribution'' is an entire family of different distributions. We use the notation $\textbf{Normal}(\mu,\sigma^2)$ to indicate what type of normal we get. If you pick a certain choice for
44,236
Relationship between z-score and the normal distribution [duplicate]
There is no relationship. The (sample) z-score is defined as $$ z_i = \frac{ x_i - \bar x } {s} $$ where $i$ indexes observations $\{x\}$, $\bar x$ is the sample mean, and $s$ is the sample standard deviation. There is nothing in this definition which states that the data has to be normally distributed, or that you can get normally distributed data by applying this transformation. The z-score represents the number of standard deviations that a data is from the mean. You may be getting mixed up with a z-test. In a z-test, we assume that under the null hypothesis, the test statistic of interest (e.g. a sample mean) has a normal distribution. The z-test procedure can be found here.
Relationship between z-score and the normal distribution [duplicate]
There is no relationship. The (sample) z-score is defined as $$ z_i = \frac{ x_i - \bar x } {s} $$ where $i$ indexes observations $\{x\}$, $\bar x$ is the sample mean, and $s$ is the sample standard d
Relationship between z-score and the normal distribution [duplicate] There is no relationship. The (sample) z-score is defined as $$ z_i = \frac{ x_i - \bar x } {s} $$ where $i$ indexes observations $\{x\}$, $\bar x$ is the sample mean, and $s$ is the sample standard deviation. There is nothing in this definition which states that the data has to be normally distributed, or that you can get normally distributed data by applying this transformation. The z-score represents the number of standard deviations that a data is from the mean. You may be getting mixed up with a z-test. In a z-test, we assume that under the null hypothesis, the test statistic of interest (e.g. a sample mean) has a normal distribution. The z-test procedure can be found here.
Relationship between z-score and the normal distribution [duplicate] There is no relationship. The (sample) z-score is defined as $$ z_i = \frac{ x_i - \bar x } {s} $$ where $i$ indexes observations $\{x\}$, $\bar x$ is the sample mean, and $s$ is the sample standard d
44,237
Relationship between z-score and the normal distribution [duplicate]
I think there is some confusion here due to the word "normalization". In this context, normalization means that the data are transformed to have zero mean and unit standard deviation. The transformed data will also be dimensionless, i.e. lacking physical units. Z-score normalization does not mean that the data become normally distributed. The transformed data are "normal" only in the sense of having zero mean and unit standard deviation.
Relationship between z-score and the normal distribution [duplicate]
I think there is some confusion here due to the word "normalization". In this context, normalization means that the data are transformed to have zero mean and unit standard deviation. The transformed
Relationship between z-score and the normal distribution [duplicate] I think there is some confusion here due to the word "normalization". In this context, normalization means that the data are transformed to have zero mean and unit standard deviation. The transformed data will also be dimensionless, i.e. lacking physical units. Z-score normalization does not mean that the data become normally distributed. The transformed data are "normal" only in the sense of having zero mean and unit standard deviation.
Relationship between z-score and the normal distribution [duplicate] I think there is some confusion here due to the word "normalization". In this context, normalization means that the data are transformed to have zero mean and unit standard deviation. The transformed
44,238
Weak law vs strong law of large numbers - intuition
After a second read of your question, I found that there are two pairs of concepts need clarification. First, the an event happens vs. the probability of an event happens. Second, convergence in probability vs convergence almost surely. 1. $A$ happens vs. The probability of $A$ happens Let $(\Omega, \mathscr{F}, P)$ be a probability space and let $A$ be an event (i.e., $A \in \mathscr{F}$), your post seems to imply the following logic: If $P(A) > 0$ (even when $P(A)$ is very small), then $A$ happens. This is a conceptual misunderstanding, which complements another common misunderstanding as follows: If $P(A) = 0$, then $A$ cannot happen. Both logics are wrong in that whether $A$ happens is random and cannot be inferred from the magnitude of $P(A)$. Instead, whether $A$ happens depends on every specific outcome of the underlying experiment or observation, which is usually denoted by $\omega$. Therefore, technically speaking, whether $A$ happens or not is a binary random variable $\Omega \to \{0, 1\}$, defined by $I_A(\omega)$, meaning if $\omega \in A$, then $A$ happens, otherwise $A$ does not happen. To put it in another way, knowing whether $A$ happens is "outcome-wise" -- without knowing information of a specific outcome $\omega$, whether $A$ happens is inconclusive. By contrast, the probability of $A$ happens, denoted by $P(A)$, is an overall deterministic measurement of the likelihood that $A$ happens, which is assigned (or can be derived based on the axioms of probability measure) by the experimenter in advance. In abstract sense, once the probability space has been set up and the event $A$ of interest is picked up, then $P(A)$ is certainly known. In particular, $P(A)$ does not depend on any specific outcome $\omega$. By the same token, knowing $P(A)$ does not convey any message of a specific outcome $\omega$, i.e., whether $A$ happens or not. To illustrate, consider the classical probability space $((0, 1], \mathscr{B}, \lambda)$, where $\mathscr{B}$ is Borel $\sigma$-field on $(0, 1]$ and $\lambda$ is Lebesgue measure. This probability space can be used to model the observational experiment that if a radioactive substance has emitted a single $\alpha$-particle during a unit interval of time, for example. First consider the event $A = (0, 1/2]$. Then, by the setup of this probability space, the probability that $A$ happens (i.e., the emission occurs in the time interval $(0, 1/2]$) is $P(A) = \lambda((0, 1/2]) = 1/2 > 0$. However, only with $P(A) = 1/2$, nothing can be said on "whether $A$ happens" unless the specific emission instant $\omega$ has been observed: if $\omega = 0.25$, then $A$ happens; if $\omega = 0.6$, then $A$ does not happen -- so it is completely random. And no matter what $\omega$ was actually observed, the deterministic probability $P(A)$ does not change. Next consider the event $A = \mathbb{Q} \cap (0, 1]$. Again, by the setup of the probability space, we have $P(A) = 0$. However, this does not imply $A$ never happens. What determines whether $A$ happens is again the realized emission time: if $\omega = 0.5$, then $A$ happens; if $\omega = \sqrt{2}/2$, then $A$ does not happen. Final word: although the distinction between "$A$ happens" and "$P(A)$" is subtle, in probability and statistics, it is only the "$P(A)$" that is of the primary interest. On the other hand, it is very often to see statements "$A$ happens with probability $1$", which is actually a rephrase of "$P(A) = 1$". 2. Convergence in probability vs. Convergence almost surely For generality, we can discuss it for any sequence of random variables $\{Y_n\}$ and a limit $Y$ and treat $\bar{X}_n$ and $\mu$ as a special case. $Y_n$ converges to $Y$ in probability means: for any $\epsilon > 0$, \begin{align} \lim_{n \to \infty}P[|Y_n - Y| > \epsilon] = 0. \tag{1} \end{align} While $Y_n$ converges to $Y$ almost surely (or "with probability $1$") means: for any $\epsilon > 0$, \begin{align} P[|Y_n - Y| > \epsilon \;\text{ i.o.}] = 0. \tag{2} \end{align} The notation "i.o." means "infinitely often" (to be elaborated later). While $(1)$ is the original definition of convergence in probability, $(2)$ is an equivalent statement of the more primitive definition of almost surely convergence: $P\left[\lim\limits_{n \to \infty}Y_n = Y\right] = 1$ or $P\left[\left[\lim\limits_{n \to \infty}Y_n = Y\right]^c\right] = 0$ (for a proof of the equivalence, see Probability and Measure by Patrick Billingsley, p. 70). While this definition is easier to understand and closer to the literal meaning of "almost surely/with probability $1$", it is the definition $(2)$ that is more intuitive for comparing the two concepts under consideration. By definition, for any sequence of events $\{B_n\}$, the event $[B_n \text{ i.o.}]$ is another way of writing the limit superior of $\{B_n\}$, denoted by $\limsup_n B_n$, which is defined as $\cap_{n = 1}^\infty\cup_{k = n}^\infty B_k$. This definition illustrates the notation "i.o. (infinitely often)": $\omega$ lies in $\limsup_n B_n$ if and only if $\omega$ lies in infinitely many of the $B_n$. It can be shown by axioms of probability measure that \begin{align} \limsup_n P(B_n) \leq P\left(\limsup_n B_n\right) = P[B_n \text{ i.o.}]. \tag{3} \end{align} In view of $(3)$, if $(2)$ holds, then $(1)$ holds automatically, that is, convergence almost surely implies convergence in probability. But the reverse is obviously not always true. With the above setup, let me comment your interpretations: for convergence in probability, you stated: The intuition is that for $n$ larger and larger there is higher probability that $\bar{X}_n$ takes value closer and closer to $\mu$. However, it is still possible that for any $\epsilon > 0$, we have $|\bar{X}_n - \mu| > \epsilon$ occurs an infinite number of times although at infrequent intervals. Both statements are not precise. $(1)$ does not guarantee the monotonicity of how $\bar{X}_n$ approaches $\mu$, so the first statement is wrong. The second statement is somewhat an extrapolation: $(1)$ (i.e., $P[|\bar{X}_n - \mu| > \epsilon] \to 0$) does not tell you anything about how many $|\bar{X}_n - \mu| > \epsilon$ happened (as mentioned in section 1 above, without knowing specific $\omega$, it is impossible to judge if what you stated is right or wrong: $[|\bar{X}_n - \mu| > \epsilon]$ may or may not happen for infinitely many times, it is just inconclusive simply based on the convergence condition), the stake here is the probability of $[|\bar{X}_n - \mu| > \epsilon]$, which tends to negligible as $n$ goes to infinity. So the only conclusion you can make from this is that for all sufficiently large $n$, the probability of the event $[|\bar{X}_n - \mu| > \epsilon]$ can be made arbitrarily small (but there is no monotonicity). For convergence almost surely, you stated: The SLLN claims that as $n \rightarrow \infty$, than $\bar{X}_n \xrightarrow{a.s.} E[X]=\mu$. However, we can still have $|\bar{X}_n-\mu|>\epsilon$, but this will happen a finite number of times. As before, the inaccuracy here is that you interpreted it without touching the keyword "probability". $(2)$ doesn't assert that $[|\bar{X}_n - \mu| > \epsilon \text{ i.o.}]$ is an empty set: $[|\bar{X}_n - \mu| > \epsilon]$ may still happen for infinitely many times -- it is just the probability of it is $0$. Apart from it, what you did get right is that the complement of the event $[|\bar{X}_n - \mu| > \epsilon \text{ i.o.}]$ is the limit inferior event $\liminf_n [|\bar{X}_n - \mu| \leq \epsilon] = \cup_{n = 1}^\infty\cap_{k = n}^\infty[|\bar{X}_k - \mu| \leq \epsilon]$, which means that $[|\bar{X}_n - \mu| > \epsilon]$ happens for only finitely many times. That said, your interpretation on SLLN is correct after appending the qualifier "with probability $1$": $[|\bar{X}_n - \mu| > \epsilon]$ will happen a finite number of times with probability $1$.
Weak law vs strong law of large numbers - intuition
After a second read of your question, I found that there are two pairs of concepts need clarification. First, the an event happens vs. the probability of an event happens. Second, convergence in prob
Weak law vs strong law of large numbers - intuition After a second read of your question, I found that there are two pairs of concepts need clarification. First, the an event happens vs. the probability of an event happens. Second, convergence in probability vs convergence almost surely. 1. $A$ happens vs. The probability of $A$ happens Let $(\Omega, \mathscr{F}, P)$ be a probability space and let $A$ be an event (i.e., $A \in \mathscr{F}$), your post seems to imply the following logic: If $P(A) > 0$ (even when $P(A)$ is very small), then $A$ happens. This is a conceptual misunderstanding, which complements another common misunderstanding as follows: If $P(A) = 0$, then $A$ cannot happen. Both logics are wrong in that whether $A$ happens is random and cannot be inferred from the magnitude of $P(A)$. Instead, whether $A$ happens depends on every specific outcome of the underlying experiment or observation, which is usually denoted by $\omega$. Therefore, technically speaking, whether $A$ happens or not is a binary random variable $\Omega \to \{0, 1\}$, defined by $I_A(\omega)$, meaning if $\omega \in A$, then $A$ happens, otherwise $A$ does not happen. To put it in another way, knowing whether $A$ happens is "outcome-wise" -- without knowing information of a specific outcome $\omega$, whether $A$ happens is inconclusive. By contrast, the probability of $A$ happens, denoted by $P(A)$, is an overall deterministic measurement of the likelihood that $A$ happens, which is assigned (or can be derived based on the axioms of probability measure) by the experimenter in advance. In abstract sense, once the probability space has been set up and the event $A$ of interest is picked up, then $P(A)$ is certainly known. In particular, $P(A)$ does not depend on any specific outcome $\omega$. By the same token, knowing $P(A)$ does not convey any message of a specific outcome $\omega$, i.e., whether $A$ happens or not. To illustrate, consider the classical probability space $((0, 1], \mathscr{B}, \lambda)$, where $\mathscr{B}$ is Borel $\sigma$-field on $(0, 1]$ and $\lambda$ is Lebesgue measure. This probability space can be used to model the observational experiment that if a radioactive substance has emitted a single $\alpha$-particle during a unit interval of time, for example. First consider the event $A = (0, 1/2]$. Then, by the setup of this probability space, the probability that $A$ happens (i.e., the emission occurs in the time interval $(0, 1/2]$) is $P(A) = \lambda((0, 1/2]) = 1/2 > 0$. However, only with $P(A) = 1/2$, nothing can be said on "whether $A$ happens" unless the specific emission instant $\omega$ has been observed: if $\omega = 0.25$, then $A$ happens; if $\omega = 0.6$, then $A$ does not happen -- so it is completely random. And no matter what $\omega$ was actually observed, the deterministic probability $P(A)$ does not change. Next consider the event $A = \mathbb{Q} \cap (0, 1]$. Again, by the setup of the probability space, we have $P(A) = 0$. However, this does not imply $A$ never happens. What determines whether $A$ happens is again the realized emission time: if $\omega = 0.5$, then $A$ happens; if $\omega = \sqrt{2}/2$, then $A$ does not happen. Final word: although the distinction between "$A$ happens" and "$P(A)$" is subtle, in probability and statistics, it is only the "$P(A)$" that is of the primary interest. On the other hand, it is very often to see statements "$A$ happens with probability $1$", which is actually a rephrase of "$P(A) = 1$". 2. Convergence in probability vs. Convergence almost surely For generality, we can discuss it for any sequence of random variables $\{Y_n\}$ and a limit $Y$ and treat $\bar{X}_n$ and $\mu$ as a special case. $Y_n$ converges to $Y$ in probability means: for any $\epsilon > 0$, \begin{align} \lim_{n \to \infty}P[|Y_n - Y| > \epsilon] = 0. \tag{1} \end{align} While $Y_n$ converges to $Y$ almost surely (or "with probability $1$") means: for any $\epsilon > 0$, \begin{align} P[|Y_n - Y| > \epsilon \;\text{ i.o.}] = 0. \tag{2} \end{align} The notation "i.o." means "infinitely often" (to be elaborated later). While $(1)$ is the original definition of convergence in probability, $(2)$ is an equivalent statement of the more primitive definition of almost surely convergence: $P\left[\lim\limits_{n \to \infty}Y_n = Y\right] = 1$ or $P\left[\left[\lim\limits_{n \to \infty}Y_n = Y\right]^c\right] = 0$ (for a proof of the equivalence, see Probability and Measure by Patrick Billingsley, p. 70). While this definition is easier to understand and closer to the literal meaning of "almost surely/with probability $1$", it is the definition $(2)$ that is more intuitive for comparing the two concepts under consideration. By definition, for any sequence of events $\{B_n\}$, the event $[B_n \text{ i.o.}]$ is another way of writing the limit superior of $\{B_n\}$, denoted by $\limsup_n B_n$, which is defined as $\cap_{n = 1}^\infty\cup_{k = n}^\infty B_k$. This definition illustrates the notation "i.o. (infinitely often)": $\omega$ lies in $\limsup_n B_n$ if and only if $\omega$ lies in infinitely many of the $B_n$. It can be shown by axioms of probability measure that \begin{align} \limsup_n P(B_n) \leq P\left(\limsup_n B_n\right) = P[B_n \text{ i.o.}]. \tag{3} \end{align} In view of $(3)$, if $(2)$ holds, then $(1)$ holds automatically, that is, convergence almost surely implies convergence in probability. But the reverse is obviously not always true. With the above setup, let me comment your interpretations: for convergence in probability, you stated: The intuition is that for $n$ larger and larger there is higher probability that $\bar{X}_n$ takes value closer and closer to $\mu$. However, it is still possible that for any $\epsilon > 0$, we have $|\bar{X}_n - \mu| > \epsilon$ occurs an infinite number of times although at infrequent intervals. Both statements are not precise. $(1)$ does not guarantee the monotonicity of how $\bar{X}_n$ approaches $\mu$, so the first statement is wrong. The second statement is somewhat an extrapolation: $(1)$ (i.e., $P[|\bar{X}_n - \mu| > \epsilon] \to 0$) does not tell you anything about how many $|\bar{X}_n - \mu| > \epsilon$ happened (as mentioned in section 1 above, without knowing specific $\omega$, it is impossible to judge if what you stated is right or wrong: $[|\bar{X}_n - \mu| > \epsilon]$ may or may not happen for infinitely many times, it is just inconclusive simply based on the convergence condition), the stake here is the probability of $[|\bar{X}_n - \mu| > \epsilon]$, which tends to negligible as $n$ goes to infinity. So the only conclusion you can make from this is that for all sufficiently large $n$, the probability of the event $[|\bar{X}_n - \mu| > \epsilon]$ can be made arbitrarily small (but there is no monotonicity). For convergence almost surely, you stated: The SLLN claims that as $n \rightarrow \infty$, than $\bar{X}_n \xrightarrow{a.s.} E[X]=\mu$. However, we can still have $|\bar{X}_n-\mu|>\epsilon$, but this will happen a finite number of times. As before, the inaccuracy here is that you interpreted it without touching the keyword "probability". $(2)$ doesn't assert that $[|\bar{X}_n - \mu| > \epsilon \text{ i.o.}]$ is an empty set: $[|\bar{X}_n - \mu| > \epsilon]$ may still happen for infinitely many times -- it is just the probability of it is $0$. Apart from it, what you did get right is that the complement of the event $[|\bar{X}_n - \mu| > \epsilon \text{ i.o.}]$ is the limit inferior event $\liminf_n [|\bar{X}_n - \mu| \leq \epsilon] = \cup_{n = 1}^\infty\cap_{k = n}^\infty[|\bar{X}_k - \mu| \leq \epsilon]$, which means that $[|\bar{X}_n - \mu| > \epsilon]$ happens for only finitely many times. That said, your interpretation on SLLN is correct after appending the qualifier "with probability $1$": $[|\bar{X}_n - \mu| > \epsilon]$ will happen a finite number of times with probability $1$.
Weak law vs strong law of large numbers - intuition After a second read of your question, I found that there are two pairs of concepts need clarification. First, the an event happens vs. the probability of an event happens. Second, convergence in prob
44,239
Weak law vs strong law of large numbers - intuition
This is a supplement to Zhanxiong's comprehensive answer that addressed OP's concerns. It would be apt to have a brief recollection of the concepts of almost everywhere convergence and convergence in probability. $\bullet$ Consider a measure space $(X, \boldsymbol{\mathfrak A}, \mu).$ A sequence of $\boldsymbol{\mathfrak A}$-measurable extended real-valued functions $\langle f_n\rangle_{n\in\mathbb N}$ on $D\in \boldsymbol{\mathfrak A}$ converges almost everywhere to $f:=\lim_{n\to\infty} f_n(x)$ if there exists a null set $N\subset D$ such that $f$ exists for all $x\in D\setminus N $ and $f(x)\in \mathbb R$ for all $x\in D\setminus N.$ $\bullet$ $f_n \overset{\textrm{a.e.}}{\to} f$ on $D$ iff $\mu\{D:f_n\nrightarrow f \} = 0.$ Now, by definition, $\{D:\lim_{n\to\infty} f_n = f\} = \bigcap_{m\in\mathbb N}\bigcup_{N\in\mathbb N}\bigcap_{p\in \mathbb N}\left\{D:|f_{N+p}- f|<\frac1m\right\}$; so using De Morgan's law \begin{align}\mu\{D:f_n\nrightarrow f \} &= \mu\left\{D\setminus\bigcap_{m\in\mathbb N}\bigcup_{N\in\mathbb N}\bigcap_{p\in \mathbb N}\left\{D:|f_{N+p}- f|<\frac1m\right\}\right\}\\ &= \mu\left\{\bigcup_{m\in\mathbb N}\bigcap_{N\in\mathbb N}\bigcup_{p\in \mathbb N}\left\{D\setminus\left\{D:|f_{N+p}- f|<\frac1m\right\}\right\}\right\}\\&= \mu\left\{\bigcup_{m\in\mathbb N}\bigcap_{N\in\mathbb N}\bigcup_{p\in \mathbb N}\left\{D:|f_{N+p}- f|\geq\frac1m\right\}\right\} .\tag 1\label 1\end{align} As countable union of null sets is null, from $\eqref 1$ dictates that for every $m,$ $$\mu\left\{\bigcap_{N\in\mathbb N}\bigcup_{n > N}\left\{D:|f_{n}- f|\geq\frac1m\right\}\right\} = 0.$$ That is, $$f_n \overset{\textrm{a.e.}}{\to} f~\textrm{on}~D\iff \mu\left\{\limsup_{n\to \infty}\left\{D:|f_{n}- f|\geq\frac1m\right\}\right\} = 0~~~\forall m\in \mathbb N.\tag 2\label 2 $$ $\bullet$ If $\mu(D)<\infty,$ by continuity property, $\eqref 2$ can be modified to $$f_n \overset{\textrm{a.e.}}{\to} f~\textrm{on}~D\iff \lim_{n\to \infty}\mu\left\{D:|f_{n}- f|\geq\frac1m\right\} = 0~\forall m\in \mathbb N.\tag 3\label 3$$ $\bullet$ $\langle f_n\rangle_{n\in\mathbb N}$ converges in measure to $f$ on $D$ if for every $\varepsilon >0, ~\eta >0,$ there exists $N_{\varepsilon,\eta}\in \mathbb N$ such that for $n\geq N_{\varepsilon,\eta} $ $$\mu\{D:|f_{n}- f|\geq \varepsilon\}<\eta,\tag 4$$ which is nothing but the re-statement of $\lim_{n\to\infty}\mu\{D:|f_{n}- f|\geq \varepsilon\} = 0$ for every $\varepsilon >0.$ $\bullet$ From $\eqref 3,$ it is clear that for $\mu(D)<\infty,$ almost everywhere convergence implies convergence in measure. This is always true for probability measures. $\bullet$ What are these two types of convergences trying to convey? It is clear almost everywhere/almost surely convergence is related with pointwise convergence. That is for a sequence of random variables $X_n$ on $\Omega,$ $$\mathbb P\left[\lim_{n\to \infty} X_n(\omega) = X(\omega)\right] = 1.$$ $\bullet$ Convergence in probability means $$\lim_{n\to\infty}\mathbb P[|X_n-X|<\varepsilon] = 1. $$ The sequence of probabilities $\langle\mathbb P[|X_n-X|<\varepsilon] \rangle_{n\in\mathbb N}$ is of concern here. Convergence in probability requires that for any $\varepsilon > 0$ the sequence of functions must be within an $\varepsilon$-band of the function $X$ over a set of points from the sample space whose probability increases to one as $n \to\infty.$ References: $\rm [I]$ Real Analysis: Theory of Measure and Integration, J. Yeh, World Scientific, $2014, $ sec. $1\S6.$ $\rm[II]$ Introduction to Statistical Limit Theory, Alan M. Polansky, Taylor and Francis, $2011,$ sec. $3.2-3.3.$
Weak law vs strong law of large numbers - intuition
This is a supplement to Zhanxiong's comprehensive answer that addressed OP's concerns. It would be apt to have a brief recollection of the concepts of almost everywhere convergence and convergence in
Weak law vs strong law of large numbers - intuition This is a supplement to Zhanxiong's comprehensive answer that addressed OP's concerns. It would be apt to have a brief recollection of the concepts of almost everywhere convergence and convergence in probability. $\bullet$ Consider a measure space $(X, \boldsymbol{\mathfrak A}, \mu).$ A sequence of $\boldsymbol{\mathfrak A}$-measurable extended real-valued functions $\langle f_n\rangle_{n\in\mathbb N}$ on $D\in \boldsymbol{\mathfrak A}$ converges almost everywhere to $f:=\lim_{n\to\infty} f_n(x)$ if there exists a null set $N\subset D$ such that $f$ exists for all $x\in D\setminus N $ and $f(x)\in \mathbb R$ for all $x\in D\setminus N.$ $\bullet$ $f_n \overset{\textrm{a.e.}}{\to} f$ on $D$ iff $\mu\{D:f_n\nrightarrow f \} = 0.$ Now, by definition, $\{D:\lim_{n\to\infty} f_n = f\} = \bigcap_{m\in\mathbb N}\bigcup_{N\in\mathbb N}\bigcap_{p\in \mathbb N}\left\{D:|f_{N+p}- f|<\frac1m\right\}$; so using De Morgan's law \begin{align}\mu\{D:f_n\nrightarrow f \} &= \mu\left\{D\setminus\bigcap_{m\in\mathbb N}\bigcup_{N\in\mathbb N}\bigcap_{p\in \mathbb N}\left\{D:|f_{N+p}- f|<\frac1m\right\}\right\}\\ &= \mu\left\{\bigcup_{m\in\mathbb N}\bigcap_{N\in\mathbb N}\bigcup_{p\in \mathbb N}\left\{D\setminus\left\{D:|f_{N+p}- f|<\frac1m\right\}\right\}\right\}\\&= \mu\left\{\bigcup_{m\in\mathbb N}\bigcap_{N\in\mathbb N}\bigcup_{p\in \mathbb N}\left\{D:|f_{N+p}- f|\geq\frac1m\right\}\right\} .\tag 1\label 1\end{align} As countable union of null sets is null, from $\eqref 1$ dictates that for every $m,$ $$\mu\left\{\bigcap_{N\in\mathbb N}\bigcup_{n > N}\left\{D:|f_{n}- f|\geq\frac1m\right\}\right\} = 0.$$ That is, $$f_n \overset{\textrm{a.e.}}{\to} f~\textrm{on}~D\iff \mu\left\{\limsup_{n\to \infty}\left\{D:|f_{n}- f|\geq\frac1m\right\}\right\} = 0~~~\forall m\in \mathbb N.\tag 2\label 2 $$ $\bullet$ If $\mu(D)<\infty,$ by continuity property, $\eqref 2$ can be modified to $$f_n \overset{\textrm{a.e.}}{\to} f~\textrm{on}~D\iff \lim_{n\to \infty}\mu\left\{D:|f_{n}- f|\geq\frac1m\right\} = 0~\forall m\in \mathbb N.\tag 3\label 3$$ $\bullet$ $\langle f_n\rangle_{n\in\mathbb N}$ converges in measure to $f$ on $D$ if for every $\varepsilon >0, ~\eta >0,$ there exists $N_{\varepsilon,\eta}\in \mathbb N$ such that for $n\geq N_{\varepsilon,\eta} $ $$\mu\{D:|f_{n}- f|\geq \varepsilon\}<\eta,\tag 4$$ which is nothing but the re-statement of $\lim_{n\to\infty}\mu\{D:|f_{n}- f|\geq \varepsilon\} = 0$ for every $\varepsilon >0.$ $\bullet$ From $\eqref 3,$ it is clear that for $\mu(D)<\infty,$ almost everywhere convergence implies convergence in measure. This is always true for probability measures. $\bullet$ What are these two types of convergences trying to convey? It is clear almost everywhere/almost surely convergence is related with pointwise convergence. That is for a sequence of random variables $X_n$ on $\Omega,$ $$\mathbb P\left[\lim_{n\to \infty} X_n(\omega) = X(\omega)\right] = 1.$$ $\bullet$ Convergence in probability means $$\lim_{n\to\infty}\mathbb P[|X_n-X|<\varepsilon] = 1. $$ The sequence of probabilities $\langle\mathbb P[|X_n-X|<\varepsilon] \rangle_{n\in\mathbb N}$ is of concern here. Convergence in probability requires that for any $\varepsilon > 0$ the sequence of functions must be within an $\varepsilon$-band of the function $X$ over a set of points from the sample space whose probability increases to one as $n \to\infty.$ References: $\rm [I]$ Real Analysis: Theory of Measure and Integration, J. Yeh, World Scientific, $2014, $ sec. $1\S6.$ $\rm[II]$ Introduction to Statistical Limit Theory, Alan M. Polansky, Taylor and Francis, $2011,$ sec. $3.2-3.3.$
Weak law vs strong law of large numbers - intuition This is a supplement to Zhanxiong's comprehensive answer that addressed OP's concerns. It would be apt to have a brief recollection of the concepts of almost everywhere convergence and convergence in
44,240
Deduce the logistic regression formula
There are several ways how the logistic function can occur as an expression that is derived based on some underlying principle. Derivation as Bayes factor The formula occurs when one computes the Bayes factor where one assumes that the groups are normal distributed. $$\frac{P(Y = 1 | X=x)}{P(Y = 0 | X=x)} = \frac{P(Y = 1)}{P(Y = 0)} \frac{\frac{1}{\sqrt{2\pi\sigma_1^2}}\text{exp}\left(-\frac{(x-\mu_1)^2}{2\sigma_1^2}\right)}{\frac{1}{\sqrt{2\pi\sigma_0^2}}\text{exp}\left(-\frac{(x-\mu_0)^2}{2\sigma_0^2}\right)} = \text{exp}\left(a + bx + cx^2 \right)$$ where $a$, $b$ and $c$ are functions of the prior ratio $P(Y = 1)/P(Y = 0)$ and of the means $\mu_1$, $\mu_0$ and of the standard deviations $\sigma_1$ and $\sigma_0$. If the standard deviations are the same then the quadratic term is zero. Derivation as natural or canonical parameter Logistic regression is often used for binary data and models the probability parameter $p$ for a Bernoulli distributed variable. For the binomial distribution the inverse of the logistic function is the logit function which is the natural parameter of the Bernoulli and binomial distribution. If we write a distribution in the form of an exponential family $$f(y|\theta) = h(y) \text{exp}\left(\eta(\theta) T(y) - A(\theta) \right)$$ Then we get for the Bernoulli distribution $$\begin{array}{rcl} \theta &=& p\\ \eta(\theta) = \eta(p)& = &\text{log}\left( \frac{p}{1-p} \right)\\ T(y)& =& y\\ A(\theta) &= &-\text{log}(1-p)\\ h(y)& = &1 \end{array}$$ $$f(y|\theta) = \text{exp}\left(\text{log}\left( \frac{p}{1-p} \right) y + \text{log}(1-p) \right) = p^y (1-p)^{1-y}$$ and the logit function $\eta = \text{log}\left( \frac{p}{1-p} \right)$ is the natural parameter. What is "natural" about the natural parameterization of an exponential family and the natural parameter space? Relation to Boltzmann distribution and maximum entropy The logistic function can originate from an exponential function for different outcomes $$p(y;x) \propto \text{exp}(f(y,x))$$ and with the normalisation using the sum $\sum_{\forall y} p(y;x)$ it becomes a logistic function $$p(y;x) = \frac{\text{exp}(f(y,x))}{\text{other stuff}+\text{exp}(f(y,x))}$$ The connection with entropy is in the exponential function $p(y;x) \propto \text{exp}(f(y,x))$ which is similar to the Boltzmann distribution. See for more: Logistic regression and maximum entropy Maximum Entropy and Multinomial Logistic Function Derivation as physical model The logistic function also occurs as the solution of a differential equation $$f^\prime(x) = f(x) \left(1-f(x)\right)$$ This occurs in growth models.
Deduce the logistic regression formula
There are several ways how the logistic function can occur as an expression that is derived based on some underlying principle. Derivation as Bayes factor The formula occurs when one computes the Baye
Deduce the logistic regression formula There are several ways how the logistic function can occur as an expression that is derived based on some underlying principle. Derivation as Bayes factor The formula occurs when one computes the Bayes factor where one assumes that the groups are normal distributed. $$\frac{P(Y = 1 | X=x)}{P(Y = 0 | X=x)} = \frac{P(Y = 1)}{P(Y = 0)} \frac{\frac{1}{\sqrt{2\pi\sigma_1^2}}\text{exp}\left(-\frac{(x-\mu_1)^2}{2\sigma_1^2}\right)}{\frac{1}{\sqrt{2\pi\sigma_0^2}}\text{exp}\left(-\frac{(x-\mu_0)^2}{2\sigma_0^2}\right)} = \text{exp}\left(a + bx + cx^2 \right)$$ where $a$, $b$ and $c$ are functions of the prior ratio $P(Y = 1)/P(Y = 0)$ and of the means $\mu_1$, $\mu_0$ and of the standard deviations $\sigma_1$ and $\sigma_0$. If the standard deviations are the same then the quadratic term is zero. Derivation as natural or canonical parameter Logistic regression is often used for binary data and models the probability parameter $p$ for a Bernoulli distributed variable. For the binomial distribution the inverse of the logistic function is the logit function which is the natural parameter of the Bernoulli and binomial distribution. If we write a distribution in the form of an exponential family $$f(y|\theta) = h(y) \text{exp}\left(\eta(\theta) T(y) - A(\theta) \right)$$ Then we get for the Bernoulli distribution $$\begin{array}{rcl} \theta &=& p\\ \eta(\theta) = \eta(p)& = &\text{log}\left( \frac{p}{1-p} \right)\\ T(y)& =& y\\ A(\theta) &= &-\text{log}(1-p)\\ h(y)& = &1 \end{array}$$ $$f(y|\theta) = \text{exp}\left(\text{log}\left( \frac{p}{1-p} \right) y + \text{log}(1-p) \right) = p^y (1-p)^{1-y}$$ and the logit function $\eta = \text{log}\left( \frac{p}{1-p} \right)$ is the natural parameter. What is "natural" about the natural parameterization of an exponential family and the natural parameter space? Relation to Boltzmann distribution and maximum entropy The logistic function can originate from an exponential function for different outcomes $$p(y;x) \propto \text{exp}(f(y,x))$$ and with the normalisation using the sum $\sum_{\forall y} p(y;x)$ it becomes a logistic function $$p(y;x) = \frac{\text{exp}(f(y,x))}{\text{other stuff}+\text{exp}(f(y,x))}$$ The connection with entropy is in the exponential function $p(y;x) \propto \text{exp}(f(y,x))$ which is similar to the Boltzmann distribution. See for more: Logistic regression and maximum entropy Maximum Entropy and Multinomial Logistic Function Derivation as physical model The logistic function also occurs as the solution of a differential equation $$f^\prime(x) = f(x) \left(1-f(x)\right)$$ This occurs in growth models.
Deduce the logistic regression formula There are several ways how the logistic function can occur as an expression that is derived based on some underlying principle. Derivation as Bayes factor The formula occurs when one computes the Baye
44,241
Deduce the logistic regression formula
The logistic regression model is an instance of Generalized Linear Models (GLM) and arises as follows. Suppose we observe random variables that can take only zeros and ones, that is, let us have a sample $Y_1,\ldots, Y_n$, where $Y_i$ is a binary random variable. Suppose also that the elements of the sample are independent of each other, and each of them follows a Bernoulli distribution with success probability $p_i$. Mathematically this can be expressed by $$ Y_i\,\overset{\textrm{iid}}{\sim}\,\text{Ber}(p_i),\quad i=1,\ldots,n. $$ Now, for some good reason, you believe that the $p_i$s may not necessarily be equal and that they depend on some features that you observe or that you have control over. Let these features be $X_i = (X_{i1},\ldots, X_{ip})$, for $i=1,\ldots,n$. Suppose that a linear relationship between the probabilities $p_i$ and the $X_i$ is fine, say $$ p_i = \psi(X_i^\top\beta),\tag{*} $$ where $\beta = (\beta_1,\ldots,\beta_p)$ are the unknown coefficients that determine such a relation and $\psi(x) = x$ is the identity function. However, you see right away that this representation is flawed because you have no guarantees that $X_i^\top \beta$ will be valid probabilities, i.e. will be in (0,1). To overcome this issue, you have to use a suitable $\psi$ in (*) that guarantees this condition. One choice is to take $\psi(x) = e^{x}/(1+e^x)$ and the relation becomes $$ p_i = \frac{e^{X_i\beta}}{1+e^{X_i\beta}}\, $$ or equivalently $$ \text{logit}(p_i) = \log\left(\frac{p_i}{1-p_i}\right) = X_i\beta\,\tag{**} $$ The equation (**), or its equivalent version, is one of the reasons why this model is called logistic regression. By the way, this specific $\psi(x)$ is the cumulative distribution function of a standard logistic random variable. Other choices for $\psi$ are possible (i.e. the probit function which leads to the probit regression), although there are some special reasons for using the logit function. This is meant as an intuitive explanation but if you need more mathematical details, please refer to (the bible of) GLM, i.e. McCullagh & Nelder (1983) Generalized Linear Models, 2nd edition, CRC Press, doi).
Deduce the logistic regression formula
The logistic regression model is an instance of Generalized Linear Models (GLM) and arises as follows. Suppose we observe random variables that can take only zeros and ones, that is, let us have a sam
Deduce the logistic regression formula The logistic regression model is an instance of Generalized Linear Models (GLM) and arises as follows. Suppose we observe random variables that can take only zeros and ones, that is, let us have a sample $Y_1,\ldots, Y_n$, where $Y_i$ is a binary random variable. Suppose also that the elements of the sample are independent of each other, and each of them follows a Bernoulli distribution with success probability $p_i$. Mathematically this can be expressed by $$ Y_i\,\overset{\textrm{iid}}{\sim}\,\text{Ber}(p_i),\quad i=1,\ldots,n. $$ Now, for some good reason, you believe that the $p_i$s may not necessarily be equal and that they depend on some features that you observe or that you have control over. Let these features be $X_i = (X_{i1},\ldots, X_{ip})$, for $i=1,\ldots,n$. Suppose that a linear relationship between the probabilities $p_i$ and the $X_i$ is fine, say $$ p_i = \psi(X_i^\top\beta),\tag{*} $$ where $\beta = (\beta_1,\ldots,\beta_p)$ are the unknown coefficients that determine such a relation and $\psi(x) = x$ is the identity function. However, you see right away that this representation is flawed because you have no guarantees that $X_i^\top \beta$ will be valid probabilities, i.e. will be in (0,1). To overcome this issue, you have to use a suitable $\psi$ in (*) that guarantees this condition. One choice is to take $\psi(x) = e^{x}/(1+e^x)$ and the relation becomes $$ p_i = \frac{e^{X_i\beta}}{1+e^{X_i\beta}}\, $$ or equivalently $$ \text{logit}(p_i) = \log\left(\frac{p_i}{1-p_i}\right) = X_i\beta\,\tag{**} $$ The equation (**), or its equivalent version, is one of the reasons why this model is called logistic regression. By the way, this specific $\psi(x)$ is the cumulative distribution function of a standard logistic random variable. Other choices for $\psi$ are possible (i.e. the probit function which leads to the probit regression), although there are some special reasons for using the logit function. This is meant as an intuitive explanation but if you need more mathematical details, please refer to (the bible of) GLM, i.e. McCullagh & Nelder (1983) Generalized Linear Models, 2nd edition, CRC Press, doi).
Deduce the logistic regression formula The logistic regression model is an instance of Generalized Linear Models (GLM) and arises as follows. Suppose we observe random variables that can take only zeros and ones, that is, let us have a sam
44,242
Why do we need Multi-Level Models when we have Logistic Regression?
As another comment notes - multilevel regression and logistic regression are not mutually exclusive, and in fact it might be that the best model to run is a mutlilevel logit model! In this case, the key issue is whether or not you want to consider "school" as a variable or a unit of analysis. But first, this question conflates two separate questions about regression modeling that don't have much to do with one another. The first question is - what "flavor" of regression model should I use, based on the way my dependent variable is measured. Normal "OLS" regression assumes that the dependent variable is continuous and has a more or less normal-ish distribution. But if your dependent variable is binary - for example "did you graduate or not?" then an OLS model isn't really appropriate. Instead you want to use a logit (or logistic) regression model. This type of model is specifically set up to analyze binary dependent variables - it tells you the extent to which a one unit increase in a particular independent variable changes the probability of getting a "1" on the binary dependent variable, holding all other variables constant. Totally sperate from that entire discussion, we have the question of what to do when you have observations that are "nested" in other groups, and where some variables are at a different "level" than others. So in this case you have students who are nested in schools, and some variables (like gender, or graduation) refer the characteristics of students while other variables (like school size, public/private) refer to characteristics of the school, so that every student who went to school #345 will have identical values for those variables. As you allude to this messes with the assumption that observations are independent which is common to "single level" version of ALL types of regression analysis, including logit, OLS, tobit etc. Making whatever type of model you are running a "multilevel" model is one particular way to deal with this issue, although there are actually a bunch of different kinds of multilevel models. In this case what the student was probably proposing is a model that allows the intercept term to vary randomly (that is, according to a normal curve) at the school level - what's called a random intercept model. This sort of approach can work on an OLS or a logit model, although the implementation is a bit different in each case. However, there is one feature of this approach that may be problematic, and might be the source of your confusion. In a multilevel model you don't actually ANALYZE the effect of being in one "group" (school in this case) vs the other. The model assumes that, in general, school level intercepts vary randomly around an overall intercept and just estimates the variance of that normal curve using the data available. So it won't actually tell you if students at school A are more likely to graduate at school B, because it's not thinking about school as a variable but as another unit of analysis (like people). You can, however, use a method called empirical bayes estimation to try and figure out which schools do better or worse, based on the model you just ran. An alternative to a multilevel model would be a "fixed effects" model that just includes a dummy variable for each school. This model treats school like a variable and it will tell you how each school does in comparison to some reference school (although for various reasons the empirical bayes approach I discussed above might be better for this question). But a fixed effects model might end up with big standard errors, and it won't allow you to include school level variables (like school size) that might tell you WHY some schools do better than others. So to answer the question "what type of model should I use" you need to answer two separate questions: How is the dependent variable measured? If it's binary, use a logit model. If it's continuous use OLS. If it's something else...use another type of model (ologit, tobit, negative binomial etc) How are you going to deal with the fact that students are nested in schools? if you want to treat "school" like a variable, you can use a fixed effects model. If you want to include school level variables in the model, then you might explore a random intercept model.
Why do we need Multi-Level Models when we have Logistic Regression?
As another comment notes - multilevel regression and logistic regression are not mutually exclusive, and in fact it might be that the best model to run is a mutlilevel logit model! In this case, the k
Why do we need Multi-Level Models when we have Logistic Regression? As another comment notes - multilevel regression and logistic regression are not mutually exclusive, and in fact it might be that the best model to run is a mutlilevel logit model! In this case, the key issue is whether or not you want to consider "school" as a variable or a unit of analysis. But first, this question conflates two separate questions about regression modeling that don't have much to do with one another. The first question is - what "flavor" of regression model should I use, based on the way my dependent variable is measured. Normal "OLS" regression assumes that the dependent variable is continuous and has a more or less normal-ish distribution. But if your dependent variable is binary - for example "did you graduate or not?" then an OLS model isn't really appropriate. Instead you want to use a logit (or logistic) regression model. This type of model is specifically set up to analyze binary dependent variables - it tells you the extent to which a one unit increase in a particular independent variable changes the probability of getting a "1" on the binary dependent variable, holding all other variables constant. Totally sperate from that entire discussion, we have the question of what to do when you have observations that are "nested" in other groups, and where some variables are at a different "level" than others. So in this case you have students who are nested in schools, and some variables (like gender, or graduation) refer the characteristics of students while other variables (like school size, public/private) refer to characteristics of the school, so that every student who went to school #345 will have identical values for those variables. As you allude to this messes with the assumption that observations are independent which is common to "single level" version of ALL types of regression analysis, including logit, OLS, tobit etc. Making whatever type of model you are running a "multilevel" model is one particular way to deal with this issue, although there are actually a bunch of different kinds of multilevel models. In this case what the student was probably proposing is a model that allows the intercept term to vary randomly (that is, according to a normal curve) at the school level - what's called a random intercept model. This sort of approach can work on an OLS or a logit model, although the implementation is a bit different in each case. However, there is one feature of this approach that may be problematic, and might be the source of your confusion. In a multilevel model you don't actually ANALYZE the effect of being in one "group" (school in this case) vs the other. The model assumes that, in general, school level intercepts vary randomly around an overall intercept and just estimates the variance of that normal curve using the data available. So it won't actually tell you if students at school A are more likely to graduate at school B, because it's not thinking about school as a variable but as another unit of analysis (like people). You can, however, use a method called empirical bayes estimation to try and figure out which schools do better or worse, based on the model you just ran. An alternative to a multilevel model would be a "fixed effects" model that just includes a dummy variable for each school. This model treats school like a variable and it will tell you how each school does in comparison to some reference school (although for various reasons the empirical bayes approach I discussed above might be better for this question). But a fixed effects model might end up with big standard errors, and it won't allow you to include school level variables (like school size) that might tell you WHY some schools do better than others. So to answer the question "what type of model should I use" you need to answer two separate questions: How is the dependent variable measured? If it's binary, use a logit model. If it's continuous use OLS. If it's something else...use another type of model (ologit, tobit, negative binomial etc) How are you going to deal with the fact that students are nested in schools? if you want to treat "school" like a variable, you can use a fixed effects model. If you want to include school level variables in the model, then you might explore a random intercept model.
Why do we need Multi-Level Models when we have Logistic Regression? As another comment notes - multilevel regression and logistic regression are not mutually exclusive, and in fact it might be that the best model to run is a mutlilevel logit model! In this case, the k
44,243
Why do we need Multi-Level Models when we have Logistic Regression?
To address you final comment - "If this is really the case - why not just fit a whole bunch of individual models for each combination of factors within the independent variables? I understand that this might result in fitting a large number of models, but aren't modern computers strong enough to do this?" It is possible to treat a clustered dataset like this, running an individual model separately for each cluster. However, this approach has several disadvantages. First, fitting a series of individual models instead of using the whole data in a multilevel model, sample size and thus statistical power is drastically reduced. Second, using a multilevel model, you get an overall coefficient that estimates (in a simple case of y ~ x) the average relationship between x and y while addressing the clustering of data. If you run a bunch of individual models, you have a bunch of individual coefficients with no simple way to combine them to gain an understanding of an overall y ~ x relationship in your total dataset. Third, running individual models you don't get information about what kind of role the cluster plays in y ~ x relationship (with a multilevel model you can see whether cluster-specific slope variance is significant and compare different clusters' slopes). Fourth, using a multilevel random slope model you still get cluster-specific coefficients for the relationship between x and y.
Why do we need Multi-Level Models when we have Logistic Regression?
To address you final comment - "If this is really the case - why not just fit a whole bunch of individual models for each combination of factors within the independent variables? I understand that thi
Why do we need Multi-Level Models when we have Logistic Regression? To address you final comment - "If this is really the case - why not just fit a whole bunch of individual models for each combination of factors within the independent variables? I understand that this might result in fitting a large number of models, but aren't modern computers strong enough to do this?" It is possible to treat a clustered dataset like this, running an individual model separately for each cluster. However, this approach has several disadvantages. First, fitting a series of individual models instead of using the whole data in a multilevel model, sample size and thus statistical power is drastically reduced. Second, using a multilevel model, you get an overall coefficient that estimates (in a simple case of y ~ x) the average relationship between x and y while addressing the clustering of data. If you run a bunch of individual models, you have a bunch of individual coefficients with no simple way to combine them to gain an understanding of an overall y ~ x relationship in your total dataset. Third, running individual models you don't get information about what kind of role the cluster plays in y ~ x relationship (with a multilevel model you can see whether cluster-specific slope variance is significant and compare different clusters' slopes). Fourth, using a multilevel random slope model you still get cluster-specific coefficients for the relationship between x and y.
Why do we need Multi-Level Models when we have Logistic Regression? To address you final comment - "If this is really the case - why not just fit a whole bunch of individual models for each combination of factors within the independent variables? I understand that thi
44,244
Why do we need Multi-Level Models when we have Logistic Regression?
Multilevel models provide us with a few benefits when compared to logistic regression. Here are a few I can think of without being too pedantic: Shrinkage Suppose you are estimating the mean/proportion of a response variable per group. Sometimes a group can have a mean too high just because that group has fewer samples on it (just think of thumbs-up reviews on a product that is not very popular on an e-commerce website). You know you can't trust the review number on those instances, so instead of removing them from the analysis, you "shrink" the estimates towards the gran mean/proportion in an "if I don't trust your estimate because of your sample size I consider you close to the gran estimate" rationale. This shrinking effect will happen for all of the parameters you estimate, ie: per group intercepts and slopes. Variance components Whenever we try to fit models to test a statistical hypothesis, the goal is to have as little variance around the estimates of parameters of interest so we can test them, have p-values, etc. Adding covariates, for example, if they help explain part of the variability of the response variable together with the parameters of interest will usually aid in reducing the variability around the estimates of the parameters of interest. In multilevel models, we get "extra" variance parameters, each for the groups of random slopes/effects and intercepts, since those have distributions tied to them as well. This helps us distribute explainable variance of the response variable toward those new components in a way that allows for that type of justification of "grouped observations are usually similar" meaning they have their own variance component. Usually less prediction error Now, this is due to the shrinkage and variance components we have in those models. Usually, since we make the parameters closer to the grand mean, we have less quadratic error overall. The read more about this type of relationship between shrinkage and prediction error, search for Stein's Paradox. Allow for finding interesting between patterns in groups Now again due to the shrinkage and individual groups parameters, we can have some discussions like: "even though variable X effect is overall tied to such and such changes in the response variable, we can see that in group A the effect is zero (or even opposite) to the overall trend". Some further reading I think you will be interested in reading a bit more about those modeling techniques. And from your question, I think you will be able to follow those texts with no trouble at all. Gelman et al's text has some really nice examples of the type of conclusions you can get from the multilevel models and does a superb job of explaining the math around those. Singer et al's text has some nice intro chapters explaining the why's and how to perform exploratory/descriptive analysis around those Multilevel models.
Why do we need Multi-Level Models when we have Logistic Regression?
Multilevel models provide us with a few benefits when compared to logistic regression. Here are a few I can think of without being too pedantic: Shrinkage Suppose you are estimating the mean/proportio
Why do we need Multi-Level Models when we have Logistic Regression? Multilevel models provide us with a few benefits when compared to logistic regression. Here are a few I can think of without being too pedantic: Shrinkage Suppose you are estimating the mean/proportion of a response variable per group. Sometimes a group can have a mean too high just because that group has fewer samples on it (just think of thumbs-up reviews on a product that is not very popular on an e-commerce website). You know you can't trust the review number on those instances, so instead of removing them from the analysis, you "shrink" the estimates towards the gran mean/proportion in an "if I don't trust your estimate because of your sample size I consider you close to the gran estimate" rationale. This shrinking effect will happen for all of the parameters you estimate, ie: per group intercepts and slopes. Variance components Whenever we try to fit models to test a statistical hypothesis, the goal is to have as little variance around the estimates of parameters of interest so we can test them, have p-values, etc. Adding covariates, for example, if they help explain part of the variability of the response variable together with the parameters of interest will usually aid in reducing the variability around the estimates of the parameters of interest. In multilevel models, we get "extra" variance parameters, each for the groups of random slopes/effects and intercepts, since those have distributions tied to them as well. This helps us distribute explainable variance of the response variable toward those new components in a way that allows for that type of justification of "grouped observations are usually similar" meaning they have their own variance component. Usually less prediction error Now, this is due to the shrinkage and variance components we have in those models. Usually, since we make the parameters closer to the grand mean, we have less quadratic error overall. The read more about this type of relationship between shrinkage and prediction error, search for Stein's Paradox. Allow for finding interesting between patterns in groups Now again due to the shrinkage and individual groups parameters, we can have some discussions like: "even though variable X effect is overall tied to such and such changes in the response variable, we can see that in group A the effect is zero (or even opposite) to the overall trend". Some further reading I think you will be interested in reading a bit more about those modeling techniques. And from your question, I think you will be able to follow those texts with no trouble at all. Gelman et al's text has some really nice examples of the type of conclusions you can get from the multilevel models and does a superb job of explaining the math around those. Singer et al's text has some nice intro chapters explaining the why's and how to perform exploratory/descriptive analysis around those Multilevel models.
Why do we need Multi-Level Models when we have Logistic Regression? Multilevel models provide us with a few benefits when compared to logistic regression. Here are a few I can think of without being too pedantic: Shrinkage Suppose you are estimating the mean/proportio
44,245
Why do we need Multi-Level Models when we have Logistic Regression?
A couple quick points to add on to what has already been said: Multilevel models are not mutually exclusive from logistic regression. You can have a multilevel logistic regression model. If you have the ability to do some basic simulation, I would highly recommend it to understand multilevel models (or statistical models in general). This can be done relatively simply in software such as R. The general idea is that you have to set up a model to simulate observed data similar to that you're seeing in the dataset of interest. It forces you to think differently about what parts are systematic ("the fixed effects" you mentioned) and what parts are random ("random effects"). The utility of a multi-level model becomes apparent very quickly
Why do we need Multi-Level Models when we have Logistic Regression?
A couple quick points to add on to what has already been said: Multilevel models are not mutually exclusive from logistic regression. You can have a multilevel logistic regression model. If you hav
Why do we need Multi-Level Models when we have Logistic Regression? A couple quick points to add on to what has already been said: Multilevel models are not mutually exclusive from logistic regression. You can have a multilevel logistic regression model. If you have the ability to do some basic simulation, I would highly recommend it to understand multilevel models (or statistical models in general). This can be done relatively simply in software such as R. The general idea is that you have to set up a model to simulate observed data similar to that you're seeing in the dataset of interest. It forces you to think differently about what parts are systematic ("the fixed effects" you mentioned) and what parts are random ("random effects"). The utility of a multi-level model becomes apparent very quickly
Why do we need Multi-Level Models when we have Logistic Regression? A couple quick points to add on to what has already been said: Multilevel models are not mutually exclusive from logistic regression. You can have a multilevel logistic regression model. If you hav
44,246
Why do we need Multi-Level Models when we have Logistic Regression?
Standard Logistic Regression All of the answers here are great. I just wanted to add a visual example because it is often illustrative of why this can matter. Using R as an example in case you may want to look at this yourself, we can load these libraries and data: #### Load Libraries #### library(datarium) library(tidyverse) library(lmerTest) #### Load Data #### hdp <- read.csv("https://stats.idre.ucla.edu/stat/data/hdp.csv") hdp <- hdp %>% mutate(DID = factor(DID)) %>% filter(DID %in% 1:20) %>% as_tibble() hdp Printing the data will look like this, information on many metrics predicting cancer remission: # A tibble: 454 × 27 tumorsize co2 pain wound mobil…¹ ntumors nmorp…² remis…³ lungc…⁴ <dbl> <dbl> <int> <int> <int> <int> <int> <int> <dbl> 1 68.0 1.53 4 4 2 0 0 0 0.801 2 64.7 1.68 2 3 2 0 0 0 0.326 3 51.6 1.53 6 3 2 0 0 0 0.565 4 86.4 1.45 3 3 2 0 0 0 0.848 5 53.4 1.57 3 4 2 0 0 0 0.886 6 51.7 1.42 4 5 2 0 0 0 0.701 7 78.9 1.71 3 4 2 0 0 0 0.891 8 69.8 1.53 3 3 3 0 0 0 0.661 9 62.9 1.54 4 4 3 2 0 0 0.909 10 71.8 1.59 5 4 3 0 0 0 0.959 If we fit a regular logistic regression for the overall effect of a patient's length of stay at a hospital and its predictiveness of cancer remission: #### Logistic Regression #### glm.fit <- glm(remission ~ LengthofStay, data = hdp, family = binomial) summary(glm.fit) We will see that there is a general effect of cancer remission decrease based on length of stay, though its impact is fairly weak: Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) -0.3546 0.5584 -0.635 0.525 LengthofStay -0.1376 0.1012 -1.359 0.174 This can be visualized with the following plot. A plot that looks like an "S" in its curve is typically strong, whereas a flat or semi-flat line is less predictive of the outcome: #### Plot Overall Trend #### hdp %>% ggplot(aes(x=LengthofStay, y=remission))+ geom_point()+ stat_smooth(method="glm", se=FALSE, method.args = list(family=binomial), color = "steelblue", size = 2)+ labs(x="Length of Stay", y="Cancer Remission", title = "Overal Trend of Cancer Remission by Length of Stay") GLMM Logistic Regression What if there is annoying noise related to which doctor was seeing each patient? Does it impact the outcome? We can fit a model with a doctor's identifier (DID) as a random intercept to see if there is some variance in outcomes based on this "random noise" from each doctor. We can also fit a random slope for length of stay per doctor, as patients may be with doctors for various lengths of time that differ between doctors, so we can tease this random variance out as well. glmm.fit <- glmer(remission ~ LengthofStay + (1 + LengthofStay| DID), data = hdp, family = binomial, control = glmerControl(optimizer = "bobyqa")) summary(glmm.fit) From the summary, we can in fact see some differences...the outcome varies by doctor by more than 2.5 standard deviations and there is a negative intercept-slope correlation. We also see that the effect of the predictor is slightly stronger, though still not statistically significant: Random effects: Groups Name Variance Std.Dev. Corr DID (Intercept) 6.7623 2.6004 LengthofStay 0.0423 0.2057 -0.64 Number of obs: 454, groups: DID, 20 Fixed effects: Estimate Std. Error z value Pr(>|z|) (Intercept) -0.6443 1.0467 -0.616 0.538 LengthofStay -0.1722 0.1630 -1.056 0.291 If we plot this, we can see some dramatic differences between doctors. Some have had no patients go into remission, some have very little impact on the outcome, some have a strong impact on the outcome (indicated by a strong S shape in the curves), and others had all their patients go into remission (gasp). #### Plot by Doctor Trend #### hdp %>% ggplot(aes(x=LengthofStay, y=remission))+ geom_point()+ stat_smooth(method="glm", se=FALSE, method.args = list(family=binomial), size = 2, color = "steelblue")+ facet_wrap(~DID)+ labs(x="Length of Stay", y="Cancer Remission", title = "By-Doctor Cancer Remission Based on Length of Stay") By teasing apart the random variance here, we have removed this randomness and figured out more of where the fixed effect is going. Since you are likely learning R for mixed models, you can play around with the other variables in this data and see if its useful for learning. I recommend using the full dataset for that purpose, as I have made some modifications for this example. A Final Caveat All of this is to say that GLMMs can provide interesting and better predictions, but that doesn't always mean you should use them or they are always better ways of modeling regressions. There is a great summary article on the potential pitfalls of GLMMs that can be read through here: On the unnecessary ubiquity of hierarchical linear modeling Psychol Methods . 2017 Mar;22(1):114-140. doi: 10.1037/met0000078. Epub 2016 May 5. PMID: 27149401 DOI: 10.1037/met0000078
Why do we need Multi-Level Models when we have Logistic Regression?
Standard Logistic Regression All of the answers here are great. I just wanted to add a visual example because it is often illustrative of why this can matter. Using R as an example in case you may wan
Why do we need Multi-Level Models when we have Logistic Regression? Standard Logistic Regression All of the answers here are great. I just wanted to add a visual example because it is often illustrative of why this can matter. Using R as an example in case you may want to look at this yourself, we can load these libraries and data: #### Load Libraries #### library(datarium) library(tidyverse) library(lmerTest) #### Load Data #### hdp <- read.csv("https://stats.idre.ucla.edu/stat/data/hdp.csv") hdp <- hdp %>% mutate(DID = factor(DID)) %>% filter(DID %in% 1:20) %>% as_tibble() hdp Printing the data will look like this, information on many metrics predicting cancer remission: # A tibble: 454 × 27 tumorsize co2 pain wound mobil…¹ ntumors nmorp…² remis…³ lungc…⁴ <dbl> <dbl> <int> <int> <int> <int> <int> <int> <dbl> 1 68.0 1.53 4 4 2 0 0 0 0.801 2 64.7 1.68 2 3 2 0 0 0 0.326 3 51.6 1.53 6 3 2 0 0 0 0.565 4 86.4 1.45 3 3 2 0 0 0 0.848 5 53.4 1.57 3 4 2 0 0 0 0.886 6 51.7 1.42 4 5 2 0 0 0 0.701 7 78.9 1.71 3 4 2 0 0 0 0.891 8 69.8 1.53 3 3 3 0 0 0 0.661 9 62.9 1.54 4 4 3 2 0 0 0.909 10 71.8 1.59 5 4 3 0 0 0 0.959 If we fit a regular logistic regression for the overall effect of a patient's length of stay at a hospital and its predictiveness of cancer remission: #### Logistic Regression #### glm.fit <- glm(remission ~ LengthofStay, data = hdp, family = binomial) summary(glm.fit) We will see that there is a general effect of cancer remission decrease based on length of stay, though its impact is fairly weak: Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) -0.3546 0.5584 -0.635 0.525 LengthofStay -0.1376 0.1012 -1.359 0.174 This can be visualized with the following plot. A plot that looks like an "S" in its curve is typically strong, whereas a flat or semi-flat line is less predictive of the outcome: #### Plot Overall Trend #### hdp %>% ggplot(aes(x=LengthofStay, y=remission))+ geom_point()+ stat_smooth(method="glm", se=FALSE, method.args = list(family=binomial), color = "steelblue", size = 2)+ labs(x="Length of Stay", y="Cancer Remission", title = "Overal Trend of Cancer Remission by Length of Stay") GLMM Logistic Regression What if there is annoying noise related to which doctor was seeing each patient? Does it impact the outcome? We can fit a model with a doctor's identifier (DID) as a random intercept to see if there is some variance in outcomes based on this "random noise" from each doctor. We can also fit a random slope for length of stay per doctor, as patients may be with doctors for various lengths of time that differ between doctors, so we can tease this random variance out as well. glmm.fit <- glmer(remission ~ LengthofStay + (1 + LengthofStay| DID), data = hdp, family = binomial, control = glmerControl(optimizer = "bobyqa")) summary(glmm.fit) From the summary, we can in fact see some differences...the outcome varies by doctor by more than 2.5 standard deviations and there is a negative intercept-slope correlation. We also see that the effect of the predictor is slightly stronger, though still not statistically significant: Random effects: Groups Name Variance Std.Dev. Corr DID (Intercept) 6.7623 2.6004 LengthofStay 0.0423 0.2057 -0.64 Number of obs: 454, groups: DID, 20 Fixed effects: Estimate Std. Error z value Pr(>|z|) (Intercept) -0.6443 1.0467 -0.616 0.538 LengthofStay -0.1722 0.1630 -1.056 0.291 If we plot this, we can see some dramatic differences between doctors. Some have had no patients go into remission, some have very little impact on the outcome, some have a strong impact on the outcome (indicated by a strong S shape in the curves), and others had all their patients go into remission (gasp). #### Plot by Doctor Trend #### hdp %>% ggplot(aes(x=LengthofStay, y=remission))+ geom_point()+ stat_smooth(method="glm", se=FALSE, method.args = list(family=binomial), size = 2, color = "steelblue")+ facet_wrap(~DID)+ labs(x="Length of Stay", y="Cancer Remission", title = "By-Doctor Cancer Remission Based on Length of Stay") By teasing apart the random variance here, we have removed this randomness and figured out more of where the fixed effect is going. Since you are likely learning R for mixed models, you can play around with the other variables in this data and see if its useful for learning. I recommend using the full dataset for that purpose, as I have made some modifications for this example. A Final Caveat All of this is to say that GLMMs can provide interesting and better predictions, but that doesn't always mean you should use them or they are always better ways of modeling regressions. There is a great summary article on the potential pitfalls of GLMMs that can be read through here: On the unnecessary ubiquity of hierarchical linear modeling Psychol Methods . 2017 Mar;22(1):114-140. doi: 10.1037/met0000078. Epub 2016 May 5. PMID: 27149401 DOI: 10.1037/met0000078
Why do we need Multi-Level Models when we have Logistic Regression? Standard Logistic Regression All of the answers here are great. I just wanted to add a visual example because it is often illustrative of why this can matter. Using R as an example in case you may wan
44,247
Alternatives to scatterplot for visualisation for large samples
I would begin by considering a transformation - very like to be useful for the Y-axis, and possibly for the X too. Log if there are no zeroes or negative values, square root if there are no negative values (zeroes are fine), cube root if there are negative values. After transformation, you could consider: A scatterplot with some jitter and possibly transparency (probably not great). A violin or semi-violin plot. A hexbin plot (quite likely the best option).
Alternatives to scatterplot for visualisation for large samples
I would begin by considering a transformation - very like to be useful for the Y-axis, and possibly for the X too. Log if there are no zeroes or negative values, square root if there are no negative v
Alternatives to scatterplot for visualisation for large samples I would begin by considering a transformation - very like to be useful for the Y-axis, and possibly for the X too. Log if there are no zeroes or negative values, square root if there are no negative values (zeroes are fine), cube root if there are negative values. After transformation, you could consider: A scatterplot with some jitter and possibly transparency (probably not great). A violin or semi-violin plot. A hexbin plot (quite likely the best option).
Alternatives to scatterplot for visualisation for large samples I would begin by considering a transformation - very like to be useful for the Y-axis, and possibly for the X too. Log if there are no zeroes or negative values, square root if there are no negative v
44,248
Alternatives to scatterplot for visualisation for large samples
You could indicate the density of points with a heatmap, e.g., using a black-body radiation palette. Alternatively, use a grayscale. Or use a hexbinplot, which pretty much does the grayscaling for you.
Alternatives to scatterplot for visualisation for large samples
You could indicate the density of points with a heatmap, e.g., using a black-body radiation palette. Alternatively, use a grayscale. Or use a hexbinplot, which pretty much does the grayscaling for you
Alternatives to scatterplot for visualisation for large samples You could indicate the density of points with a heatmap, e.g., using a black-body radiation palette. Alternatively, use a grayscale. Or use a hexbinplot, which pretty much does the grayscaling for you.
Alternatives to scatterplot for visualisation for large samples You could indicate the density of points with a heatmap, e.g., using a black-body radiation palette. Alternatively, use a grayscale. Or use a hexbinplot, which pretty much does the grayscaling for you
44,249
Alternatives to scatterplot for visualisation for large samples
Binscatter plots are designed for this exact problem: visualizing two-way relationships in huge datasets. See here for R and python packages and some references. The name says it all. Binscatter procedure partitions the data domain into bins and plots only sample averages in the bins rather than all data points. Main advantage of binscatter is the ease with which it handles additional covariates. So, roughly speaking, visualizing n-way relationships. See here for an overview and some examples.
Alternatives to scatterplot for visualisation for large samples
Binscatter plots are designed for this exact problem: visualizing two-way relationships in huge datasets. See here for R and python packages and some references. The name says it all. Binscatter proce
Alternatives to scatterplot for visualisation for large samples Binscatter plots are designed for this exact problem: visualizing two-way relationships in huge datasets. See here for R and python packages and some references. The name says it all. Binscatter procedure partitions the data domain into bins and plots only sample averages in the bins rather than all data points. Main advantage of binscatter is the ease with which it handles additional covariates. So, roughly speaking, visualizing n-way relationships. See here for an overview and some examples.
Alternatives to scatterplot for visualisation for large samples Binscatter plots are designed for this exact problem: visualizing two-way relationships in huge datasets. See here for R and python packages and some references. The name says it all. Binscatter proce
44,250
Practical implication of failing to reject a null hypothesis
Here is a discussion of a simple version of your question. Suppose the dosages are normal. And you have looked at 30 bottles sampled before the faulty filling may have begun and 30 after. Then 'Before' dosages may have been $X_i \sim\mathsf{Norm}(50, 2),$ $i=1,2,\dots,30,$ and 'After' dosages $Y_i \sim\mathsf{Norm}(52, 2),$ $i =1,2,\dots,30,$ so that the actual over-filling amount we wish to detect is 2g. Then a Welch two-sample t test will detect the fault in about 97% of such experiments. That is, the power of my proposed test is about 97%, as found by looking at 100,000 simulated Welch t tests below. set.seed(2022) pv = replicate(10^5, t.test(rnorm(30, 50, 2), rnorm(30, 52, 2))$p.val) mean(pv <= .05) [1] 0.96828 Notes: (1) I used the Welch t test because I can only guess whether the standard deviation of the filling amounts is the same before and after the difficulty arose. (2) I am interested in detecting an effect of size 2 (which is the standard deviation of filling amounts). (3) The null hypothesis is rejected if the P-value of the test is smaller than $0.05.$ (4) The numeric vector pv contains 100,000 P-values of Welch tests; the logical vector pv <= .05 contains 100,000 TRUEs and FALSEs; and its mean is its proportion of TRUEs.
Practical implication of failing to reject a null hypothesis
Here is a discussion of a simple version of your question. Suppose the dosages are normal. And you have looked at 30 bottles sampled before the faulty filling may have begun and 30 after. Then 'Before
Practical implication of failing to reject a null hypothesis Here is a discussion of a simple version of your question. Suppose the dosages are normal. And you have looked at 30 bottles sampled before the faulty filling may have begun and 30 after. Then 'Before' dosages may have been $X_i \sim\mathsf{Norm}(50, 2),$ $i=1,2,\dots,30,$ and 'After' dosages $Y_i \sim\mathsf{Norm}(52, 2),$ $i =1,2,\dots,30,$ so that the actual over-filling amount we wish to detect is 2g. Then a Welch two-sample t test will detect the fault in about 97% of such experiments. That is, the power of my proposed test is about 97%, as found by looking at 100,000 simulated Welch t tests below. set.seed(2022) pv = replicate(10^5, t.test(rnorm(30, 50, 2), rnorm(30, 52, 2))$p.val) mean(pv <= .05) [1] 0.96828 Notes: (1) I used the Welch t test because I can only guess whether the standard deviation of the filling amounts is the same before and after the difficulty arose. (2) I am interested in detecting an effect of size 2 (which is the standard deviation of filling amounts). (3) The null hypothesis is rejected if the P-value of the test is smaller than $0.05.$ (4) The numeric vector pv contains 100,000 P-values of Welch tests; the logical vector pv <= .05 contains 100,000 TRUEs and FALSEs; and its mean is its proportion of TRUEs.
Practical implication of failing to reject a null hypothesis Here is a discussion of a simple version of your question. Suppose the dosages are normal. And you have looked at 30 bottles sampled before the faulty filling may have begun and 30 after. Then 'Before
44,251
Practical implication of failing to reject a null hypothesis
If you approached the problem this way, then you made a mistake! What you could have done is calculate the sample size required to detect a difference of practical importance. You know it isn’t filling exactly 50, and you have some tolerable difference from that value. Maybe you can tolerate 49-51, or maybe you can tolerate 49.99-50.01. Then, if you fail to reject the null hypothesis, you know that you adequately powered your investigation to detect important differences and didn’t just fail to reject due to an inadequate sample size (e.g., it’s easy to fail to reject if you make two observations). This approach requires you to phrase that tolerance in terms of the standard deviation. If this is not viable, then you can do a true equivalence test.
Practical implication of failing to reject a null hypothesis
If you approached the problem this way, then you made a mistake! What you could have done is calculate the sample size required to detect a difference of practical importance. You know it isn’t fillin
Practical implication of failing to reject a null hypothesis If you approached the problem this way, then you made a mistake! What you could have done is calculate the sample size required to detect a difference of practical importance. You know it isn’t filling exactly 50, and you have some tolerable difference from that value. Maybe you can tolerate 49-51, or maybe you can tolerate 49.99-50.01. Then, if you fail to reject the null hypothesis, you know that you adequately powered your investigation to detect important differences and didn’t just fail to reject due to an inadequate sample size (e.g., it’s easy to fail to reject if you make two observations). This approach requires you to phrase that tolerance in terms of the standard deviation. If this is not viable, then you can do a true equivalence test.
Practical implication of failing to reject a null hypothesis If you approached the problem this way, then you made a mistake! What you could have done is calculate the sample size required to detect a difference of practical importance. You know it isn’t fillin
44,252
Practical implication of failing to reject a null hypothesis
This seems like a situation where the failure is relying on null hypothesis significance testing in the first place. Monitoring that a machine is well calibrated is an estimation problem. You might do better to control accuracy (margin of error) of the dosage rather than the type I error. A type I error in this situation is unnecessarily stopping the production line for maintenance. A type II error is continuing to manufacture medicine with the wrong dosage. The cost of a false negative is much higher than a false positive because, if the dose doesn't match the label, patients could be given incorrect treatment. This example also seems somewhat naive because drug manufacturing is regulated*. The FDA might not accept the failure to reject a null hypothesis as sufficient evidence of no mis-calibration. Current Good Manufacturing Practice (CGMP) Regulations
Practical implication of failing to reject a null hypothesis
This seems like a situation where the failure is relying on null hypothesis significance testing in the first place. Monitoring that a machine is well calibrated is an estimation problem. You might do
Practical implication of failing to reject a null hypothesis This seems like a situation where the failure is relying on null hypothesis significance testing in the first place. Monitoring that a machine is well calibrated is an estimation problem. You might do better to control accuracy (margin of error) of the dosage rather than the type I error. A type I error in this situation is unnecessarily stopping the production line for maintenance. A type II error is continuing to manufacture medicine with the wrong dosage. The cost of a false negative is much higher than a false positive because, if the dose doesn't match the label, patients could be given incorrect treatment. This example also seems somewhat naive because drug manufacturing is regulated*. The FDA might not accept the failure to reject a null hypothesis as sufficient evidence of no mis-calibration. Current Good Manufacturing Practice (CGMP) Regulations
Practical implication of failing to reject a null hypothesis This seems like a situation where the failure is relying on null hypothesis significance testing in the first place. Monitoring that a machine is well calibrated is an estimation problem. You might do
44,253
Testing difference between coefficients of nonlinear regression models
Define a new variable red in your data set that is 1 for the red points and 0 for the blue points. Then include an extra coefficient c in your regression equation: 1−1/(1+(x/(a+c*red))^b) c denotes the offset between the curve fitted to the blue and the red points. If c is significantly different from zero then you can consider the two response curves different. Also, consult the drc package in R.
Testing difference between coefficients of nonlinear regression models
Define a new variable red in your data set that is 1 for the red points and 0 for the blue points. Then include an extra coefficient c in your regression equation: 1−1/(1+(x/(a+c*red))^b) c denotes th
Testing difference between coefficients of nonlinear regression models Define a new variable red in your data set that is 1 for the red points and 0 for the blue points. Then include an extra coefficient c in your regression equation: 1−1/(1+(x/(a+c*red))^b) c denotes the offset between the curve fitted to the blue and the red points. If c is significantly different from zero then you can consider the two response curves different. Also, consult the drc package in R.
Testing difference between coefficients of nonlinear regression models Define a new variable red in your data set that is 1 for the red points and 0 for the blue points. Then include an extra coefficient c in your regression equation: 1−1/(1+(x/(a+c*red))^b) c denotes th
44,254
Testing difference between coefficients of nonlinear regression models
I would probably approach this using an approximate permutation test. The general idea is that, if the data comes from the same function (note that this would assume $a_1 = a_2$ AND $b_1 = b_2$ for the two sets of data, as well as that the random components of the two datasets were drawn from the same distribution), which subset (blue or red in your case) of the data any given data point is assigned to is irrelevant. Consequently, we can scramble the assignments, calculate the differences in the red and blue parameter estimates, and repeat this over and over to get an estimate of how plausibly large the difference would be in the two parameter estimates if the null hypothesis were true. In more statistical terms, we can compute a permutation p-value from the fraction of permutation samples that generate estimates as large or larger than the one we calculated using the original data. Two of the advantages of permutation tests are that they are distribution-free, only requiring that the observations be exchangeable under the null hypothesis, and that you can use any test statistic you want - you aren't limited to ones for which a distribution under the null hypothesis is known or can be calculated. They are also asymptotically most powerful conditional upon the data. Here's a demonstration, using constructed data that seems to more-or-less mimic yours. First, constructing the data: # Create data; 50 observations for each of sample 1 and 2 x1 <- ceiling(10*runif(50)) x2 <- ceiling(10*runif(50)) a1 <- 4; b1 <- 8 a2 <- 5; b2 <- 6 func <- function(x, a, b) { p <- 1 - 1/(1 + (x/a)^b) y <- rbeta(length(p), p*15, (1-p)*15) y } df1 <- data.frame(y = func(x1, a1, b1), x = x1) df2 <- data.frame(y = func(x2, a2, b2), x = x2) df_H0 <- rbind(df1, df2) The constructed data looks like this: plot(y~x, data=df1, col="blue", pch=19, cex=1.25, main="Sample points") points(y~x, data=df2, col="red", bg="red", pch=24, cex=1.25) Next, we calculate the difference between the parameter estimates of $a$ on the two samples: fm <- as.formula("y ~ 1 - 1/(1+ (x/a)^b)") m1 <- nls(fm, data=df1, start=list(a=5, b=5)) m2 <- nls(fm, data=df2, start=list(a=5, b=5)) stat_21 <- m2$m$getPars()[1] - m1$m$getPars()[1] stat_21 a 1.153752 Now for the permutation calculations: boot_21 <- rep(0, 1000) for (i in seq_along(boot_21)) { indx1 <- sample(nrow(df_H0))[1:nrow(df1)] m1 <- nls(fm, data=df_H0[indx1,], start=list(a=5, b=5)) m2 <- nls(fm, data=df_H0[-indx1,], start=list(a=5, b=5)) boot_21[i] <- as.numeric(m2$m$getPars()[1] - m1$m$getPars()[1]) } hist(boot_21) abline(v=stat_21) This gives us the following plot: with the vertical bar at the far right equal to the actual statistic. The permutation p-value is: mean(abs(boot_21) >= stat_21) [1] 0 which means that not one of our 1,000 permutation samples had as large a difference in the parameter estimates as we actually observed.
Testing difference between coefficients of nonlinear regression models
I would probably approach this using an approximate permutation test. The general idea is that, if the data comes from the same function (note that this would assume $a_1 = a_2$ AND $b_1 = b_2$ for th
Testing difference between coefficients of nonlinear regression models I would probably approach this using an approximate permutation test. The general idea is that, if the data comes from the same function (note that this would assume $a_1 = a_2$ AND $b_1 = b_2$ for the two sets of data, as well as that the random components of the two datasets were drawn from the same distribution), which subset (blue or red in your case) of the data any given data point is assigned to is irrelevant. Consequently, we can scramble the assignments, calculate the differences in the red and blue parameter estimates, and repeat this over and over to get an estimate of how plausibly large the difference would be in the two parameter estimates if the null hypothesis were true. In more statistical terms, we can compute a permutation p-value from the fraction of permutation samples that generate estimates as large or larger than the one we calculated using the original data. Two of the advantages of permutation tests are that they are distribution-free, only requiring that the observations be exchangeable under the null hypothesis, and that you can use any test statistic you want - you aren't limited to ones for which a distribution under the null hypothesis is known or can be calculated. They are also asymptotically most powerful conditional upon the data. Here's a demonstration, using constructed data that seems to more-or-less mimic yours. First, constructing the data: # Create data; 50 observations for each of sample 1 and 2 x1 <- ceiling(10*runif(50)) x2 <- ceiling(10*runif(50)) a1 <- 4; b1 <- 8 a2 <- 5; b2 <- 6 func <- function(x, a, b) { p <- 1 - 1/(1 + (x/a)^b) y <- rbeta(length(p), p*15, (1-p)*15) y } df1 <- data.frame(y = func(x1, a1, b1), x = x1) df2 <- data.frame(y = func(x2, a2, b2), x = x2) df_H0 <- rbind(df1, df2) The constructed data looks like this: plot(y~x, data=df1, col="blue", pch=19, cex=1.25, main="Sample points") points(y~x, data=df2, col="red", bg="red", pch=24, cex=1.25) Next, we calculate the difference between the parameter estimates of $a$ on the two samples: fm <- as.formula("y ~ 1 - 1/(1+ (x/a)^b)") m1 <- nls(fm, data=df1, start=list(a=5, b=5)) m2 <- nls(fm, data=df2, start=list(a=5, b=5)) stat_21 <- m2$m$getPars()[1] - m1$m$getPars()[1] stat_21 a 1.153752 Now for the permutation calculations: boot_21 <- rep(0, 1000) for (i in seq_along(boot_21)) { indx1 <- sample(nrow(df_H0))[1:nrow(df1)] m1 <- nls(fm, data=df_H0[indx1,], start=list(a=5, b=5)) m2 <- nls(fm, data=df_H0[-indx1,], start=list(a=5, b=5)) boot_21[i] <- as.numeric(m2$m$getPars()[1] - m1$m$getPars()[1]) } hist(boot_21) abline(v=stat_21) This gives us the following plot: with the vertical bar at the far right equal to the actual statistic. The permutation p-value is: mean(abs(boot_21) >= stat_21) [1] 0 which means that not one of our 1,000 permutation samples had as large a difference in the parameter estimates as we actually observed.
Testing difference between coefficients of nonlinear regression models I would probably approach this using an approximate permutation test. The general idea is that, if the data comes from the same function (note that this would assume $a_1 = a_2$ AND $b_1 = b_2$ for th
44,255
Testing difference between coefficients of nonlinear regression models
I feel a bit bad by overcrowding the comments section with pedantic notes and questions about the origins of the noise in the data. So I will make up for it with an answer that is a bit more decent than those little comments. This answer will demonstrate how a straightforward (non linear) least squares fit (which can also be done with glm*) will be overestimating the significance of the difference between the two compounds. The reason that this overestimation happens is because the noise is not homogeneous whereas the model that is used to compute the p-value assumes that all points have the same noise. Effectively it is mostly the few points around the midpoint that make a large difference between models. Consequently, the effective degrees of freedom is much less than what the computations assume. This makes the permutation test from the answer by @jbowman a more robust method. The problem of the permutation test is that you need a sufficient amount of relevant data points in order for the test to be powerful. In addition the permutation test is not immune to the situation where the datapoints are correlated due to particular experimental procedures that make the errors not independent. Some other method like using a Bayesian model that models the entire process and incorporates all errors could be better. The bottomline is that there is no single solution that can be applied to al these type of curves. You can not give a set of data to a statistician along with a function and no other information. It is important to know where the data comes from and how it has been generated. This needs to be incorporated into the statistical model. In this example we generate data points, not by adding noise to the curve, but by changing the parameters for each data point. $$a \sim \text{Unif}(4,6) \qquad b = 3 \\ y = 1- \frac{1}{1+(x/a)^b}$$ then we would get a plot like this for generating two times 80 datapoints. The variability in the curve is not like noise added to some 'true' value but but is because of variations in the curves themselves being different each time. This could correspond with variations in the (bacterial?) cells that are used. Each of them is different and may behave according to a different coefficient $a$ and $b$. The consequence is that the noise is not homogeneous. It is mostly around the middle $x=5$ where the largest variation occurs. If we repeat this simulation $10^4$ times and compute the p-values with a glm model or non-linear least squares fit, then the distribution of p-values look like this So you do not get a homogeneous distribution of p-values and the models overestimate the probability that a certain discrepancy occurs. The reason is because the variation mostly occurs in a few point whereas the computation of the p-value assumes that it occurs evenly in all points. This overestimates the degrees of freedom. Especially the inclusion of the point $x=0$ is completely useless because a change in the coefficients has no effect on the value of the outcome. Sample code: sigmoid = function(x,a=5,b=3) { 1-(1+(x/a)^b)^-1 } simulate_test = function(plot = TRUE) { ### create data x = rep(0:15,10) y = sigmoid(x, a = runif(length(x),4,6)) compound = c(rep(0,16*5), rep(1,16*5)) ### make a plot if desired if (plot == TRUE) { plot(x, y, pch = 21, col = 1, bg = 0 + compound * 2, cex = 0.7) } ### Perform fitting ### ### we can do the fitting with nls but the lines below shows that glm works as well ### For glm points with x=0 need to be removed because we use log(x), but these do not add information anyway modnls = nls(y ~ sigmoid(x,a+c*compound,b), start = c(a=5,b=3,c=0), control = nls.control(minFactor = 10^-4,warnOnly = TRUE)) modglm = glm(y[-which(x==0)] ~ log(x[-which(x==0)]) + compound[-which(x==0)], family = gaussian(link = "logit")) #lines below demonstrate how you would get the (same) coefficients with the two methods glm vs nls #coefficients(modnls) #coefficients(modglm) #exp(-modglm$coefficients[1]/modglm$coefficients[2]) #exp((-modglm$coefficients[1]-modglm$coefficients[3])/modglm$coefficients[2])-exp(-modglm$coefficients[1]/modglm$coefficients[2]) return(list(nls_p = summary(modnls)$coefficients[3,4], glm_p = summary(modglm)$coefficients[3,4])) } set.seed(1) x = replicate(10^4, as.numeric(simulate_test(plot = FALSE))) x = list(nls_p = x[1,], glm_p = x[2,]) hist(x$glm_p, breaks = seq(0,1,0.01)) hist(x$nls_p, breaks = seq(0,1,0.01)) simulate_test(plot = TRUE) *The fit can also be done with with a generalized linear model because we can find a link function such that the converted values are a linear function of the regressors: $\log \left(\frac{y}{1-y}\right) = b \log(x) - b \log(a)$. This is demonstrated in the code. There is a slight difference between the coefficients and estimates because of computational errors, and of p-values because the glm model has to use $\log(x)$ and exclude the value $x=0$. But these values wit $x=0$ add no information anyway and make the glm model actually more precise than the nls model.
Testing difference between coefficients of nonlinear regression models
I feel a bit bad by overcrowding the comments section with pedantic notes and questions about the origins of the noise in the data. So I will make up for it with an answer that is a bit more decent th
Testing difference between coefficients of nonlinear regression models I feel a bit bad by overcrowding the comments section with pedantic notes and questions about the origins of the noise in the data. So I will make up for it with an answer that is a bit more decent than those little comments. This answer will demonstrate how a straightforward (non linear) least squares fit (which can also be done with glm*) will be overestimating the significance of the difference between the two compounds. The reason that this overestimation happens is because the noise is not homogeneous whereas the model that is used to compute the p-value assumes that all points have the same noise. Effectively it is mostly the few points around the midpoint that make a large difference between models. Consequently, the effective degrees of freedom is much less than what the computations assume. This makes the permutation test from the answer by @jbowman a more robust method. The problem of the permutation test is that you need a sufficient amount of relevant data points in order for the test to be powerful. In addition the permutation test is not immune to the situation where the datapoints are correlated due to particular experimental procedures that make the errors not independent. Some other method like using a Bayesian model that models the entire process and incorporates all errors could be better. The bottomline is that there is no single solution that can be applied to al these type of curves. You can not give a set of data to a statistician along with a function and no other information. It is important to know where the data comes from and how it has been generated. This needs to be incorporated into the statistical model. In this example we generate data points, not by adding noise to the curve, but by changing the parameters for each data point. $$a \sim \text{Unif}(4,6) \qquad b = 3 \\ y = 1- \frac{1}{1+(x/a)^b}$$ then we would get a plot like this for generating two times 80 datapoints. The variability in the curve is not like noise added to some 'true' value but but is because of variations in the curves themselves being different each time. This could correspond with variations in the (bacterial?) cells that are used. Each of them is different and may behave according to a different coefficient $a$ and $b$. The consequence is that the noise is not homogeneous. It is mostly around the middle $x=5$ where the largest variation occurs. If we repeat this simulation $10^4$ times and compute the p-values with a glm model or non-linear least squares fit, then the distribution of p-values look like this So you do not get a homogeneous distribution of p-values and the models overestimate the probability that a certain discrepancy occurs. The reason is because the variation mostly occurs in a few point whereas the computation of the p-value assumes that it occurs evenly in all points. This overestimates the degrees of freedom. Especially the inclusion of the point $x=0$ is completely useless because a change in the coefficients has no effect on the value of the outcome. Sample code: sigmoid = function(x,a=5,b=3) { 1-(1+(x/a)^b)^-1 } simulate_test = function(plot = TRUE) { ### create data x = rep(0:15,10) y = sigmoid(x, a = runif(length(x),4,6)) compound = c(rep(0,16*5), rep(1,16*5)) ### make a plot if desired if (plot == TRUE) { plot(x, y, pch = 21, col = 1, bg = 0 + compound * 2, cex = 0.7) } ### Perform fitting ### ### we can do the fitting with nls but the lines below shows that glm works as well ### For glm points with x=0 need to be removed because we use log(x), but these do not add information anyway modnls = nls(y ~ sigmoid(x,a+c*compound,b), start = c(a=5,b=3,c=0), control = nls.control(minFactor = 10^-4,warnOnly = TRUE)) modglm = glm(y[-which(x==0)] ~ log(x[-which(x==0)]) + compound[-which(x==0)], family = gaussian(link = "logit")) #lines below demonstrate how you would get the (same) coefficients with the two methods glm vs nls #coefficients(modnls) #coefficients(modglm) #exp(-modglm$coefficients[1]/modglm$coefficients[2]) #exp((-modglm$coefficients[1]-modglm$coefficients[3])/modglm$coefficients[2])-exp(-modglm$coefficients[1]/modglm$coefficients[2]) return(list(nls_p = summary(modnls)$coefficients[3,4], glm_p = summary(modglm)$coefficients[3,4])) } set.seed(1) x = replicate(10^4, as.numeric(simulate_test(plot = FALSE))) x = list(nls_p = x[1,], glm_p = x[2,]) hist(x$glm_p, breaks = seq(0,1,0.01)) hist(x$nls_p, breaks = seq(0,1,0.01)) simulate_test(plot = TRUE) *The fit can also be done with with a generalized linear model because we can find a link function such that the converted values are a linear function of the regressors: $\log \left(\frac{y}{1-y}\right) = b \log(x) - b \log(a)$. This is demonstrated in the code. There is a slight difference between the coefficients and estimates because of computational errors, and of p-values because the glm model has to use $\log(x)$ and exclude the value $x=0$. But these values wit $x=0$ add no information anyway and make the glm model actually more precise than the nls model.
Testing difference between coefficients of nonlinear regression models I feel a bit bad by overcrowding the comments section with pedantic notes and questions about the origins of the noise in the data. So I will make up for it with an answer that is a bit more decent th
44,256
Correct use of Chi-square and hypothesis testing?
All of your concerns are valid and well articulated. The chi-square test simply provides the weight of the evidence that there is an association between attendance and purchase. Any causality is an extra layer of interpretation that in many instances is unverifiable. There are many causal hypotheses one could entertain. Randomly assigning people to either attend or not attend the event would allow you to make a stronger causal inference argument as to the effect attendance has on making a purchase. This is because through randomization each subject in the study would be equally likely to attend the event (the distribution of subject features is, in the long run, the same between the two groups). Any difference in purchasing behavior could then be attributed to attendance alone. This doesn't mean that all observational studies are useless. It just means that you have to preface every statement with, "Assuming no unmeasured confounders...[insert causal statement here]," or state that the findings show an association without speculating as to the causal nature. I generally do both, starting with the latter and finishing with the former. Addendum: If you have an imbalance in prognostic factors between those who attend and those who do not attend, then for causal inference you have at least a couple of options: 1) adjust the outcome model and interpret the effect of attendance in various subgroups (main effect, interactions). For causal inference you may consider drawing a causal diagram to understand how the covariates should enter the model. 2) Re-weight the observations using IPTWs. This balances the measured prognostic covariates between treatment groups to make the sample appear as though it is the result of a randomized trial. The outcome model can be analyzed using only a main effect for attendance. Causal inference on the effect of attendance is for the entire population. With either approach the causal interpretation of the results will still need to be prefaced with, "Assuming no unmeasured confounders..."
Correct use of Chi-square and hypothesis testing?
All of your concerns are valid and well articulated. The chi-square test simply provides the weight of the evidence that there is an association between attendance and purchase. Any causality is an
Correct use of Chi-square and hypothesis testing? All of your concerns are valid and well articulated. The chi-square test simply provides the weight of the evidence that there is an association between attendance and purchase. Any causality is an extra layer of interpretation that in many instances is unverifiable. There are many causal hypotheses one could entertain. Randomly assigning people to either attend or not attend the event would allow you to make a stronger causal inference argument as to the effect attendance has on making a purchase. This is because through randomization each subject in the study would be equally likely to attend the event (the distribution of subject features is, in the long run, the same between the two groups). Any difference in purchasing behavior could then be attributed to attendance alone. This doesn't mean that all observational studies are useless. It just means that you have to preface every statement with, "Assuming no unmeasured confounders...[insert causal statement here]," or state that the findings show an association without speculating as to the causal nature. I generally do both, starting with the latter and finishing with the former. Addendum: If you have an imbalance in prognostic factors between those who attend and those who do not attend, then for causal inference you have at least a couple of options: 1) adjust the outcome model and interpret the effect of attendance in various subgroups (main effect, interactions). For causal inference you may consider drawing a causal diagram to understand how the covariates should enter the model. 2) Re-weight the observations using IPTWs. This balances the measured prognostic covariates between treatment groups to make the sample appear as though it is the result of a randomized trial. The outcome model can be analyzed using only a main effect for attendance. Causal inference on the effect of attendance is for the entire population. With either approach the causal interpretation of the results will still need to be prefaced with, "Assuming no unmeasured confounders..."
Correct use of Chi-square and hypothesis testing? All of your concerns are valid and well articulated. The chi-square test simply provides the weight of the evidence that there is an association between attendance and purchase. Any causality is an
44,257
Correct use of Chi-square and hypothesis testing?
An alternative version of your chi-squared test is the prop.test procedure in R. You have the proportion of purchasers $\hat p_a = 190/1540 = 0.1234$ among those who attended events and the proportion $\hat p_n = 893/16571 = 0.0593$ among those who did not attend events. The question is whether $\hat p_a$ and $\hat p_n$ are significantly different at the 5% level. The test is shown below. (I declined continuity correction on account of the relatively large sample sizes.) Sometimes the output from prop.test is easier to interpret than output from the (equivalent) chi-squared test. prop.test(c(190,983), c(1540, 16571), cor=F) 2-sample test for equality of proportions without continuity correction data: c(190, 983) out of c(1540, 16571) X-squared = 95.449, df = 1, p-value < 2.2e-16 alternative hypothesis: two.sided 95 percent confidence interval: 0.04724175 0.08087049 sample estimates: prop 1 prop 2 0.1233766 0.0593205 I agree with @GeoffreyJohnson's answer (+1) about a design for making a stronger case. However, the chi-squared test can also be viewed as a test whether the two categorical variables are independent. So properly stated, as you have done, your conclusions from the current data are valid. You have shown a statistical association, not causation. For comparison, I show output from the chisq.test procedure in R (without Yates' correction): TAB = rbind(c(190, 983), c(1350, 15588)) TAB [,1] [,2] [1,] 190 983 [2,] 1350 15588 chisq.test(TAB, cor=F) Pearson's Chi-squared test data: TAB X-squared = 95.449, df = 1, p-value < 2.2e-16
Correct use of Chi-square and hypothesis testing?
An alternative version of your chi-squared test is the prop.test procedure in R. You have the proportion of purchasers $\hat p_a = 190/1540 = 0.1234$ among those who attended events and the proportion
Correct use of Chi-square and hypothesis testing? An alternative version of your chi-squared test is the prop.test procedure in R. You have the proportion of purchasers $\hat p_a = 190/1540 = 0.1234$ among those who attended events and the proportion $\hat p_n = 893/16571 = 0.0593$ among those who did not attend events. The question is whether $\hat p_a$ and $\hat p_n$ are significantly different at the 5% level. The test is shown below. (I declined continuity correction on account of the relatively large sample sizes.) Sometimes the output from prop.test is easier to interpret than output from the (equivalent) chi-squared test. prop.test(c(190,983), c(1540, 16571), cor=F) 2-sample test for equality of proportions without continuity correction data: c(190, 983) out of c(1540, 16571) X-squared = 95.449, df = 1, p-value < 2.2e-16 alternative hypothesis: two.sided 95 percent confidence interval: 0.04724175 0.08087049 sample estimates: prop 1 prop 2 0.1233766 0.0593205 I agree with @GeoffreyJohnson's answer (+1) about a design for making a stronger case. However, the chi-squared test can also be viewed as a test whether the two categorical variables are independent. So properly stated, as you have done, your conclusions from the current data are valid. You have shown a statistical association, not causation. For comparison, I show output from the chisq.test procedure in R (without Yates' correction): TAB = rbind(c(190, 983), c(1350, 15588)) TAB [,1] [,2] [1,] 190 983 [2,] 1350 15588 chisq.test(TAB, cor=F) Pearson's Chi-squared test data: TAB X-squared = 95.449, df = 1, p-value < 2.2e-16
Correct use of Chi-square and hypothesis testing? An alternative version of your chi-squared test is the prop.test procedure in R. You have the proportion of purchasers $\hat p_a = 190/1540 = 0.1234$ among those who attended events and the proportion
44,258
Correct use of Chi-square and hypothesis testing?
On a shallow level, the analysis you've done is good enough to show to the business. This is what matters. Now, "is our marketing good and people buy products because of these events?" is quite different from "should we keep conducting these events, and if so, how many?". Maybe events make people feel better about the company, not the product. Maybe with 10 more events you would sell 3x as much stuff. Maybe you would sell as much with 5x fewer events. Your analysis does show a correlation between events and purchases but does not answer all the questions a business might imply being the same, but posing a totally different and, likely, more complex problem. That makes it your priority to focus on communication and making sure "yes, events are probably good for sales" does not translate to some uncontrollable and immeasurable actions. On the topic of the problem itself - one thing to do next is to classify your clientele. Some are repeated customers, some buy products first and then attend events to get support on them, some are indeed drawn in by the marketing... Understanding this structure better should give you tools to deal with "what should we do" kinds of problems. More broadly, consider some common customer engagement metrics: you mention some of them in your post already, but this is a well-developed area - doing your research first is (nearly) always a good idea ;)
Correct use of Chi-square and hypothesis testing?
On a shallow level, the analysis you've done is good enough to show to the business. This is what matters. Now, "is our marketing good and people buy products because of these events?" is quite differ
Correct use of Chi-square and hypothesis testing? On a shallow level, the analysis you've done is good enough to show to the business. This is what matters. Now, "is our marketing good and people buy products because of these events?" is quite different from "should we keep conducting these events, and if so, how many?". Maybe events make people feel better about the company, not the product. Maybe with 10 more events you would sell 3x as much stuff. Maybe you would sell as much with 5x fewer events. Your analysis does show a correlation between events and purchases but does not answer all the questions a business might imply being the same, but posing a totally different and, likely, more complex problem. That makes it your priority to focus on communication and making sure "yes, events are probably good for sales" does not translate to some uncontrollable and immeasurable actions. On the topic of the problem itself - one thing to do next is to classify your clientele. Some are repeated customers, some buy products first and then attend events to get support on them, some are indeed drawn in by the marketing... Understanding this structure better should give you tools to deal with "what should we do" kinds of problems. More broadly, consider some common customer engagement metrics: you mention some of them in your post already, but this is a well-developed area - doing your research first is (nearly) always a good idea ;)
Correct use of Chi-square and hypothesis testing? On a shallow level, the analysis you've done is good enough to show to the business. This is what matters. Now, "is our marketing good and people buy products because of these events?" is quite differ
44,259
Can I find MLE of probability of X greater than x [duplicate]
As I'm sure you know (or can easily derive), the maximum likelihood estimator of $(\mu,\sigma^2)$ is $$(\hat\mu,\hat\sigma^2) = \left(\bar X, \operatorname{Var}(X)\right)$$ where, as usual, $n\bar X = X_1+X_2+\cdots + X_n$ and, a little unusually, $$\operatorname{Var}(X) = \frac{1}{n}\left((X_1-\bar X)^2 + (X_2-\bar X)^2 + \cdots + (X_n-\bar X)^2\right)$$ (notice the $n$ rather than the $n-1$ in the denominator). A fundamental property of MLEs is that a maximum likelihood estimator of any function $f$ of the parameters equals $f$ applied to the MLEs of the parameters. In this case, letting $\Phi$ be the standard Normal CDF $$f(\mu,\sigma^2) = \Pr(X \gt 12) = 1 - \Phi\left(\frac{12-\mu}{\sqrt{\sigma^2}}\right).$$ Therefore the MLE of $\Pr(X \gt 12)$ is $$\hat f = 1 - \Phi\left(\frac{12-\hat\mu}{\sqrt{\hat\sigma^2}}\right).$$ Because maximum likelihood estimation is a procedure intended for relatively large sample sizes, here is a simulation based on 100,000 samples of size $n=240.$ The parameter was set to $(\mu,\sigma)=(5,3).$ You can see how the estimates are spread roughly evenly around the true value (marked as a red vertical segment), indicating this solution is a reasonable estimator. Further simulations with ever larger sample sizes (I went up to $n=24000$ but limited the simulation to just a thousand iterations to keep the computation time down to a second or two) indicate this solution converges around the true value, as it ought. # # Specify the problem. # mu <- 5 sigma <- 3 threshold <- 12 n <- 240 # # Draw samples. # set.seed(17) n.sim <- 1e5 x <- matrix(rnorm(n.sim*n, mu, sigma), n.sim) # # Compute the MLEs. # mu.hat <- rowMeans(x) sigma2.hat <- rowMeans((x - mu.hat)^2) p.hat <- pnorm((threshold - mu.hat) / sqrt(sigma2.hat), lower.tail = FALSE) # # Plot the MLEs. # hist(p.hat, freq=FALSE, col="#f0f0f0", breaks=50, xlab=expression(hat(f)), cex.lab=1.25, main=expression(paste("Histogram of ", Pr(X>12)))) abline(v = pnorm(threshold, mu, sigma, lower.tail = FALSE), lwd=2, col="#d01010")
Can I find MLE of probability of X greater than x [duplicate]
As I'm sure you know (or can easily derive), the maximum likelihood estimator of $(\mu,\sigma^2)$ is $$(\hat\mu,\hat\sigma^2) = \left(\bar X, \operatorname{Var}(X)\right)$$ where, as usual, $n\bar X =
Can I find MLE of probability of X greater than x [duplicate] As I'm sure you know (or can easily derive), the maximum likelihood estimator of $(\mu,\sigma^2)$ is $$(\hat\mu,\hat\sigma^2) = \left(\bar X, \operatorname{Var}(X)\right)$$ where, as usual, $n\bar X = X_1+X_2+\cdots + X_n$ and, a little unusually, $$\operatorname{Var}(X) = \frac{1}{n}\left((X_1-\bar X)^2 + (X_2-\bar X)^2 + \cdots + (X_n-\bar X)^2\right)$$ (notice the $n$ rather than the $n-1$ in the denominator). A fundamental property of MLEs is that a maximum likelihood estimator of any function $f$ of the parameters equals $f$ applied to the MLEs of the parameters. In this case, letting $\Phi$ be the standard Normal CDF $$f(\mu,\sigma^2) = \Pr(X \gt 12) = 1 - \Phi\left(\frac{12-\mu}{\sqrt{\sigma^2}}\right).$$ Therefore the MLE of $\Pr(X \gt 12)$ is $$\hat f = 1 - \Phi\left(\frac{12-\hat\mu}{\sqrt{\hat\sigma^2}}\right).$$ Because maximum likelihood estimation is a procedure intended for relatively large sample sizes, here is a simulation based on 100,000 samples of size $n=240.$ The parameter was set to $(\mu,\sigma)=(5,3).$ You can see how the estimates are spread roughly evenly around the true value (marked as a red vertical segment), indicating this solution is a reasonable estimator. Further simulations with ever larger sample sizes (I went up to $n=24000$ but limited the simulation to just a thousand iterations to keep the computation time down to a second or two) indicate this solution converges around the true value, as it ought. # # Specify the problem. # mu <- 5 sigma <- 3 threshold <- 12 n <- 240 # # Draw samples. # set.seed(17) n.sim <- 1e5 x <- matrix(rnorm(n.sim*n, mu, sigma), n.sim) # # Compute the MLEs. # mu.hat <- rowMeans(x) sigma2.hat <- rowMeans((x - mu.hat)^2) p.hat <- pnorm((threshold - mu.hat) / sqrt(sigma2.hat), lower.tail = FALSE) # # Plot the MLEs. # hist(p.hat, freq=FALSE, col="#f0f0f0", breaks=50, xlab=expression(hat(f)), cex.lab=1.25, main=expression(paste("Histogram of ", Pr(X>12)))) abline(v = pnorm(threshold, mu, sigma, lower.tail = FALSE), lwd=2, col="#d01010")
Can I find MLE of probability of X greater than x [duplicate] As I'm sure you know (or can easily derive), the maximum likelihood estimator of $(\mu,\sigma^2)$ is $$(\hat\mu,\hat\sigma^2) = \left(\bar X, \operatorname{Var}(X)\right)$$ where, as usual, $n\bar X =
44,260
Meaning of vertical bar | in loss function?
It denotes that the function is parameterized by $\theta$ and the $x_i$ are the inputs to the function. For example $f(x|\theta)=x\cdot \theta$ is the dot product of the input, $x$, and the parameters $\theta$. User @Underminer adds a note about reading: if you wanted to read the symbols $f(x|\theta)$ aloud, you might say "the function $f$ of $x$ given $\theta$." Some other usages are described at Wikipedia's article https://en.wikipedia.org/wiki/Vertical_bar#Mathematics. Incidentally, this was my first Google hit for the search math vertical bar notation.
Meaning of vertical bar | in loss function?
It denotes that the function is parameterized by $\theta$ and the $x_i$ are the inputs to the function. For example $f(x|\theta)=x\cdot \theta$ is the dot product of the input, $x$, and the parameters
Meaning of vertical bar | in loss function? It denotes that the function is parameterized by $\theta$ and the $x_i$ are the inputs to the function. For example $f(x|\theta)=x\cdot \theta$ is the dot product of the input, $x$, and the parameters $\theta$. User @Underminer adds a note about reading: if you wanted to read the symbols $f(x|\theta)$ aloud, you might say "the function $f$ of $x$ given $\theta$." Some other usages are described at Wikipedia's article https://en.wikipedia.org/wiki/Vertical_bar#Mathematics. Incidentally, this was my first Google hit for the search math vertical bar notation.
Meaning of vertical bar | in loss function? It denotes that the function is parameterized by $\theta$ and the $x_i$ are the inputs to the function. For example $f(x|\theta)=x\cdot \theta$ is the dot product of the input, $x$, and the parameters
44,261
Using cross-entropy for regression problems
In a regression problem you have pairs $(x_i, y_i)$. And some true model $q$ that characterizes $q(y|x)$. Let's say you assume that your density $$f_\theta(y|x)= \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left\{-\frac{1}{2\sigma^2}(y_i-\mu_\theta(x_i))^2\right\}$$ and you fix $\sigma^2$ to some value The mean $\mu(x_i)$ is then e.g. modelled via a a neural network (or any other model) Writing the empirical approximation to the cross entropy you get: $$\sum_{i = 1}^n-\log\left( \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left\{-\frac{1}{2\sigma^2}(y_i-\mu_\theta(x_i))^2\right\} \right)$$ $$=\sum_{i = 1}^n-\log\left( \frac{1}{\sqrt{2\pi\sigma^2}}\right) +\frac{1}{2\sigma^2}(y_i-\mu_\theta(x_i))^2$$ If we e.g. set $\sigma^2 = 1$ (i.e. assume we know the variance; we could also model the variance than our neural network had two ouputs, i.e. one for the mean and one for the variance) we get: $$=\sum_{i = 1}^n-\log\left( \frac{1}{\sqrt{2\pi}}\right) +\frac{1}{2}(y_i-\mu_\theta(x_i))^2$$ Minimizing this is equivalent to the minimization of the $L2$ loss. So we have seen that minimizing CE with the assumption of normality is equivalent to the minimization of the $L2$ loss
Using cross-entropy for regression problems
In a regression problem you have pairs $(x_i, y_i)$. And some true model $q$ that characterizes $q(y|x)$. Let's say you assume that your density $$f_\theta(y|x)= \frac{1}{\sqrt{2\pi\sigma^2}} \exp\lef
Using cross-entropy for regression problems In a regression problem you have pairs $(x_i, y_i)$. And some true model $q$ that characterizes $q(y|x)$. Let's say you assume that your density $$f_\theta(y|x)= \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left\{-\frac{1}{2\sigma^2}(y_i-\mu_\theta(x_i))^2\right\}$$ and you fix $\sigma^2$ to some value The mean $\mu(x_i)$ is then e.g. modelled via a a neural network (or any other model) Writing the empirical approximation to the cross entropy you get: $$\sum_{i = 1}^n-\log\left( \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left\{-\frac{1}{2\sigma^2}(y_i-\mu_\theta(x_i))^2\right\} \right)$$ $$=\sum_{i = 1}^n-\log\left( \frac{1}{\sqrt{2\pi\sigma^2}}\right) +\frac{1}{2\sigma^2}(y_i-\mu_\theta(x_i))^2$$ If we e.g. set $\sigma^2 = 1$ (i.e. assume we know the variance; we could also model the variance than our neural network had two ouputs, i.e. one for the mean and one for the variance) we get: $$=\sum_{i = 1}^n-\log\left( \frac{1}{\sqrt{2\pi}}\right) +\frac{1}{2}(y_i-\mu_\theta(x_i))^2$$ Minimizing this is equivalent to the minimization of the $L2$ loss. So we have seen that minimizing CE with the assumption of normality is equivalent to the minimization of the $L2$ loss
Using cross-entropy for regression problems In a regression problem you have pairs $(x_i, y_i)$. And some true model $q$ that characterizes $q(y|x)$. Let's say you assume that your density $$f_\theta(y|x)= \frac{1}{\sqrt{2\pi\sigma^2}} \exp\lef
44,262
Using cross-entropy for regression problems
The mean squared error is the cross-entropy between the data distribution $p^*(x)$ and your Gaussian model distribution $p_{\theta}$. Note that the standard MLE procedure is: $$ \begin{align} \max_{\theta} E_{x \sim p^*}[\log p_{\theta}(x)] &= \min_{\theta} \left(- E_{x \sim p^*}[\log p_{\theta}(x)]\right)\\ &= \min_{\theta} H(p^* \Vert p_{\theta}) \\ &\approx \min_{\theta} \sum_i \frac{1}{2} \left(\Vert x_i - \theta_1\Vert^2/\theta_2^2 - \log 2 \pi \theta_2^2\right) \end{align} $$ Where $H(p^* \Vert p_{\theta})$ denotes the CE and we use a Monte Carlo approximation to the expectation. And as you stated, this is equivalent to minimizing the KL divergence between the data distribution and your model distribution. Commonly the variance $\theta_2$ is fixed and drops out of the objective. Some people get confused because certain textbooks introduce the cross-entropy in terms of the Bernoulli/Categorical distribution (almost all machine learning libraries are guilty of this!), but it applies more generally than the discrete setting.
Using cross-entropy for regression problems
The mean squared error is the cross-entropy between the data distribution $p^*(x)$ and your Gaussian model distribution $p_{\theta}$. Note that the standard MLE procedure is: $$ \begin{align} \max_{\t
Using cross-entropy for regression problems The mean squared error is the cross-entropy between the data distribution $p^*(x)$ and your Gaussian model distribution $p_{\theta}$. Note that the standard MLE procedure is: $$ \begin{align} \max_{\theta} E_{x \sim p^*}[\log p_{\theta}(x)] &= \min_{\theta} \left(- E_{x \sim p^*}[\log p_{\theta}(x)]\right)\\ &= \min_{\theta} H(p^* \Vert p_{\theta}) \\ &\approx \min_{\theta} \sum_i \frac{1}{2} \left(\Vert x_i - \theta_1\Vert^2/\theta_2^2 - \log 2 \pi \theta_2^2\right) \end{align} $$ Where $H(p^* \Vert p_{\theta})$ denotes the CE and we use a Monte Carlo approximation to the expectation. And as you stated, this is equivalent to minimizing the KL divergence between the data distribution and your model distribution. Commonly the variance $\theta_2$ is fixed and drops out of the objective. Some people get confused because certain textbooks introduce the cross-entropy in terms of the Bernoulli/Categorical distribution (almost all machine learning libraries are guilty of this!), but it applies more generally than the discrete setting.
Using cross-entropy for regression problems The mean squared error is the cross-entropy between the data distribution $p^*(x)$ and your Gaussian model distribution $p_{\theta}$. Note that the standard MLE procedure is: $$ \begin{align} \max_{\t
44,263
Why does ordinary least squares have to be linear in the parameters?
What is it about the process of solving OLS that requires the parameters to be linear? Because equations which are nonlinear in their parameters can't be written as $y=X\beta$. OLS estimates $\beta$ in the equation $$ y = X\beta +\epsilon. $$ This is a linear relationship, so when we say that $\hat{\beta} = (X^\top X)^{-1}X^\top y$ is the optimal estimator of $\beta$, what we mean is that it's optimal in the sense that it minimizes $\|y - X\beta\|_2^2$. Minimizing $\|y - X\beta\|_2^2$ is only important if this objective is meaningful for your task; particularly, if the task isn't linear in these parameters, then the fit may be poor. However, one reason that OLS is so flexible is that if you can find a way to represent your data in a linear way, then it is linear in the parameters, otherwise known as basis expansion. A textbook example of a change of basis is using a polynomial basis, so you have $X_\text{polynomial} = [1, x, x^2, x^3, \dots, x^p]$. The model $X_\text{polynomial}\beta$ is linear in its parameters, but viewed as a function of $x$, it's a nonlinear polynomial. What would happen if they were non-linear and we tried to solve using OLS? It won't work very well! This data's deterministic component is given by $$ y = \beta_0 + \beta_1 \sin (\beta_2 x + \beta_3) $$ which is not linear in $\beta$, the parameter vector to be estimated, because you can't write this in the form $y=X\beta$. I also add small, independent 0-mean Gaussian noise to each observation. If we do the naive thing and assume that our output $y$ is a linear function of $x$, then we find a poor fit, in the sense that there is a large discrepancy between the estimated line (red) and the true function (blue). The model finds that the best linear approximation is a decreasing line, completely ignoring the sinusoidal behavior. One way to try to improve the fit is to re-express $x$. Since this looks like something sinusoidal, we might try a sine function. This gives the design matrix $X_\text{sine}=[1, \sin(x)]$. This give a flatter line, but it's still not a satisfying model. Even though the model and the desired function are both sine waves, we're implicitly using $\beta_0 + \beta_1 \sin(1 \times x + 0)$ to approximate $$ y = \beta_0 + \beta_1 \sin (\beta_2 x + \beta_3).$$ This is not a good approximation, because we've fixed $\beta_2=1$ and $\beta_3=0$, so the further the true values are from these assumed values, the poorer this approximation will be. What we really need is a way to recover all of the parameters in the function $$ y = \beta_0 + \beta_1 \sin (\beta_2 x + \beta_3), $$ but this is a nonlinear estimation task, so we need to use the appropriate tools to accommodate the nonlinearity of the $\beta$s. Nonlinear least squares is one method to achieve this, among many others. Code set.seed(13) N <- 1000 x <- runif(N, -pi, pi) f <- function(x) pi + 2 * sin(4 * x) y <- f(x) + rnorm(N,sd=0.5) model <- lm(y ~ x) png("~/Desktop/nonlinear.png") plot(x,y,col="grey") abline(model, col="red", lwd=2, lty="dashed") lines(sort(x), f(sort(x)), lwd=2, col="blue") dev.off() model2 <- lm(y ~ sin(x) ) png("~/Desktop/nonlinear2.png") plot(x,y,col="grey") abline(model2, col="red", lwd=2, lty="dashed") lines(sort(x), f(sort(x)), lwd=2, col="blue") dev.off()
Why does ordinary least squares have to be linear in the parameters?
What is it about the process of solving OLS that requires the parameters to be linear? Because equations which are nonlinear in their parameters can't be written as $y=X\beta$. OLS estimates $\beta$
Why does ordinary least squares have to be linear in the parameters? What is it about the process of solving OLS that requires the parameters to be linear? Because equations which are nonlinear in their parameters can't be written as $y=X\beta$. OLS estimates $\beta$ in the equation $$ y = X\beta +\epsilon. $$ This is a linear relationship, so when we say that $\hat{\beta} = (X^\top X)^{-1}X^\top y$ is the optimal estimator of $\beta$, what we mean is that it's optimal in the sense that it minimizes $\|y - X\beta\|_2^2$. Minimizing $\|y - X\beta\|_2^2$ is only important if this objective is meaningful for your task; particularly, if the task isn't linear in these parameters, then the fit may be poor. However, one reason that OLS is so flexible is that if you can find a way to represent your data in a linear way, then it is linear in the parameters, otherwise known as basis expansion. A textbook example of a change of basis is using a polynomial basis, so you have $X_\text{polynomial} = [1, x, x^2, x^3, \dots, x^p]$. The model $X_\text{polynomial}\beta$ is linear in its parameters, but viewed as a function of $x$, it's a nonlinear polynomial. What would happen if they were non-linear and we tried to solve using OLS? It won't work very well! This data's deterministic component is given by $$ y = \beta_0 + \beta_1 \sin (\beta_2 x + \beta_3) $$ which is not linear in $\beta$, the parameter vector to be estimated, because you can't write this in the form $y=X\beta$. I also add small, independent 0-mean Gaussian noise to each observation. If we do the naive thing and assume that our output $y$ is a linear function of $x$, then we find a poor fit, in the sense that there is a large discrepancy between the estimated line (red) and the true function (blue). The model finds that the best linear approximation is a decreasing line, completely ignoring the sinusoidal behavior. One way to try to improve the fit is to re-express $x$. Since this looks like something sinusoidal, we might try a sine function. This gives the design matrix $X_\text{sine}=[1, \sin(x)]$. This give a flatter line, but it's still not a satisfying model. Even though the model and the desired function are both sine waves, we're implicitly using $\beta_0 + \beta_1 \sin(1 \times x + 0)$ to approximate $$ y = \beta_0 + \beta_1 \sin (\beta_2 x + \beta_3).$$ This is not a good approximation, because we've fixed $\beta_2=1$ and $\beta_3=0$, so the further the true values are from these assumed values, the poorer this approximation will be. What we really need is a way to recover all of the parameters in the function $$ y = \beta_0 + \beta_1 \sin (\beta_2 x + \beta_3), $$ but this is a nonlinear estimation task, so we need to use the appropriate tools to accommodate the nonlinearity of the $\beta$s. Nonlinear least squares is one method to achieve this, among many others. Code set.seed(13) N <- 1000 x <- runif(N, -pi, pi) f <- function(x) pi + 2 * sin(4 * x) y <- f(x) + rnorm(N,sd=0.5) model <- lm(y ~ x) png("~/Desktop/nonlinear.png") plot(x,y,col="grey") abline(model, col="red", lwd=2, lty="dashed") lines(sort(x), f(sort(x)), lwd=2, col="blue") dev.off() model2 <- lm(y ~ sin(x) ) png("~/Desktop/nonlinear2.png") plot(x,y,col="grey") abline(model2, col="red", lwd=2, lty="dashed") lines(sort(x), f(sort(x)), lwd=2, col="blue") dev.off()
Why does ordinary least squares have to be linear in the parameters? What is it about the process of solving OLS that requires the parameters to be linear? Because equations which are nonlinear in their parameters can't be written as $y=X\beta$. OLS estimates $\beta$
44,264
Why prices are usually not stationary, but returns are more likely to be stationary?
The return $Y_t$ represents the increase in the value of the stock as a percentage of its previous value. This return fluctuates a great deal in an economy, but in a properly functioning economy, it does tend to fluctuate around a small positive value. Consequently, the total stock price for a company tends to grow roughly exponentially over time. The same thing can be observed in stock indices that aggregate stocks from a large number of different companies. To see what I am talking about, consider the following chart showing the S&P500 stock index from 1835-2015 (source here). The chart shows the total index; you can see that the index follows roughly exponential growth (i.e., it is roughly linearly increasing when show on the logarithmic scale). Returns fluctuate substantially, but over the long term they give rise to roughly exponential growth.$^\dagger$ The returns over time are arguably stationary, and you can fit the returns reasonably well with stationary time-series models such as ARMA, ARCH, GARCH, etc. Even if these returns are not exactly stationary (e.g., exhibiting long-term cycles or changes) they are certainly much closer to being stationary than the stock price itself, since the latter has roughly exponential growth. $^\dagger$ Note that in the case of a stock index it is a bit more complicated, since underperforming companies leave the index and better performing companies are added, so the return on the index tends to be higher than what you would expect for an individual company.
Why prices are usually not stationary, but returns are more likely to be stationary?
The return $Y_t$ represents the increase in the value of the stock as a percentage of its previous value. This return fluctuates a great deal in an economy, but in a properly functioning economy, it
Why prices are usually not stationary, but returns are more likely to be stationary? The return $Y_t$ represents the increase in the value of the stock as a percentage of its previous value. This return fluctuates a great deal in an economy, but in a properly functioning economy, it does tend to fluctuate around a small positive value. Consequently, the total stock price for a company tends to grow roughly exponentially over time. The same thing can be observed in stock indices that aggregate stocks from a large number of different companies. To see what I am talking about, consider the following chart showing the S&P500 stock index from 1835-2015 (source here). The chart shows the total index; you can see that the index follows roughly exponential growth (i.e., it is roughly linearly increasing when show on the logarithmic scale). Returns fluctuate substantially, but over the long term they give rise to roughly exponential growth.$^\dagger$ The returns over time are arguably stationary, and you can fit the returns reasonably well with stationary time-series models such as ARMA, ARCH, GARCH, etc. Even if these returns are not exactly stationary (e.g., exhibiting long-term cycles or changes) they are certainly much closer to being stationary than the stock price itself, since the latter has roughly exponential growth. $^\dagger$ Note that in the case of a stock index it is a bit more complicated, since underperforming companies leave the index and better performing companies are added, so the return on the index tends to be higher than what you would expect for an individual company.
Why prices are usually not stationary, but returns are more likely to be stationary? The return $Y_t$ represents the increase in the value of the stock as a percentage of its previous value. This return fluctuates a great deal in an economy, but in a properly functioning economy, it
44,265
Why prices are usually not stationary, but returns are more likely to be stationary?
Stock prices can be thought of being a cumulative sum of mean-independent increments due to economic (and other types of) shocks. This is per definition a process with a unit root: $$ X_t=X_{t-1}+\varepsilon_t=(X_{t-2}+\varepsilon_{t-1})+\varepsilon_t=\dots=\sum_{\tau=0}^t\varepsilon_\tau. $$ (After the first equality, the coefficient in front of $X_{t-1}$ is unity; this is the unit root.) Meanwhile, the increments $\varepsilon_\tau$ are mean-independent and "almost stationary", but their scale grows with the level of the stock price (hence not stationary). When you divide them by the level, $\frac{\varepsilon_\tau}{X_{\tau-1}}$, you get an approximately stationary process.
Why prices are usually not stationary, but returns are more likely to be stationary?
Stock prices can be thought of being a cumulative sum of mean-independent increments due to economic (and other types of) shocks. This is per definition a process with a unit root: $$ X_t=X_{t-1}+\va
Why prices are usually not stationary, but returns are more likely to be stationary? Stock prices can be thought of being a cumulative sum of mean-independent increments due to economic (and other types of) shocks. This is per definition a process with a unit root: $$ X_t=X_{t-1}+\varepsilon_t=(X_{t-2}+\varepsilon_{t-1})+\varepsilon_t=\dots=\sum_{\tau=0}^t\varepsilon_\tau. $$ (After the first equality, the coefficient in front of $X_{t-1}$ is unity; this is the unit root.) Meanwhile, the increments $\varepsilon_\tau$ are mean-independent and "almost stationary", but their scale grows with the level of the stock price (hence not stationary). When you divide them by the level, $\frac{\varepsilon_\tau}{X_{\tau-1}}$, you get an approximately stationary process.
Why prices are usually not stationary, but returns are more likely to be stationary? Stock prices can be thought of being a cumulative sum of mean-independent increments due to economic (and other types of) shocks. This is per definition a process with a unit root: $$ X_t=X_{t-1}+\va
44,266
Why prices are usually not stationary, but returns are more likely to be stationary?
This is a generalization but I think it is useful to think of the price of the stock as $$X_t = E_t P_t$$ where $E_t$ is a company's earnings and $P_t$ the multiple of earnings investors are willing to pay for the stock (also known as a P/E ratio). $E_t$ is non-stationary since earnings tend to grow over time due to economic growth and inflation. On the other hand it is somewhat reasonable to assume $P_t$ stationary since the passage of time should not affect the multiple of earnings investors are willing to pay for a stock. Putting this together $X_t$ is non-stationary since it has a time-dependent mean function. Now, looking at returns we can rearrange the equation as $$Y_t=\frac{X_t-X_{t-1}}{X_{t-1}}=\frac{E_tP_t-E_{t-1}P_{t-1}}{E_{t-1}P_{t-1}}=\frac{E_tP_t}{E_{t-1}P_{t-1}}-1$$ In this form it would appear that the fraction $\frac{E_tP_t}{E_{t-1}P_{t-1}}$ does not have a time dependent mean function, since the dependence which $E_t$ has on time is negated by having it on the numerator and denominator of that equation. For example assuming $P_t,E_t$ independent for all $t$, and assuming the expected growth rate of earnings is 2%, we see that $$E[Y_t]=E\Big[\frac{E_tP_t}{E_{t-1}P_{t-1}}-1\Big]=E\Big[\frac{E_t}{E_{t-1}}\Big]E\Big[\frac{P_t}{P_{t-1}}\Big]-1=1.02E\Big[\frac{P_t}{P_{t-1}}\Big]-1$$ Now since $P_t$ is unlikely to have a mean function that is dependent on time, the mean function of $\frac{P_t}{P_{t-1}}$ should also be independent of time leading to $E[Y_t]$ to be independent of time (one of the conditions of stationarity).
Why prices are usually not stationary, but returns are more likely to be stationary?
This is a generalization but I think it is useful to think of the price of the stock as $$X_t = E_t P_t$$ where $E_t$ is a company's earnings and $P_t$ the multiple of earnings investors are willing t
Why prices are usually not stationary, but returns are more likely to be stationary? This is a generalization but I think it is useful to think of the price of the stock as $$X_t = E_t P_t$$ where $E_t$ is a company's earnings and $P_t$ the multiple of earnings investors are willing to pay for the stock (also known as a P/E ratio). $E_t$ is non-stationary since earnings tend to grow over time due to economic growth and inflation. On the other hand it is somewhat reasonable to assume $P_t$ stationary since the passage of time should not affect the multiple of earnings investors are willing to pay for a stock. Putting this together $X_t$ is non-stationary since it has a time-dependent mean function. Now, looking at returns we can rearrange the equation as $$Y_t=\frac{X_t-X_{t-1}}{X_{t-1}}=\frac{E_tP_t-E_{t-1}P_{t-1}}{E_{t-1}P_{t-1}}=\frac{E_tP_t}{E_{t-1}P_{t-1}}-1$$ In this form it would appear that the fraction $\frac{E_tP_t}{E_{t-1}P_{t-1}}$ does not have a time dependent mean function, since the dependence which $E_t$ has on time is negated by having it on the numerator and denominator of that equation. For example assuming $P_t,E_t$ independent for all $t$, and assuming the expected growth rate of earnings is 2%, we see that $$E[Y_t]=E\Big[\frac{E_tP_t}{E_{t-1}P_{t-1}}-1\Big]=E\Big[\frac{E_t}{E_{t-1}}\Big]E\Big[\frac{P_t}{P_{t-1}}\Big]-1=1.02E\Big[\frac{P_t}{P_{t-1}}\Big]-1$$ Now since $P_t$ is unlikely to have a mean function that is dependent on time, the mean function of $\frac{P_t}{P_{t-1}}$ should also be independent of time leading to $E[Y_t]$ to be independent of time (one of the conditions of stationarity).
Why prices are usually not stationary, but returns are more likely to be stationary? This is a generalization but I think it is useful to think of the price of the stock as $$X_t = E_t P_t$$ where $E_t$ is a company's earnings and $P_t$ the multiple of earnings investors are willing t
44,267
Shrinkage priors
I don't quite know your specific use case though I can provide you with a bunch of resources so that you can make your own decision: Michael Betancourt's case study on sparse regressions: https://betanalpha.github.io/assets/case_studies/bayes_sparse_regression.html That is a particularly great resource because he shows the effect of different priors on the same problem. Also he provides the code for the analysis so implementing it yourself is a lot easier And Piironen and Vehtari (2017) has a great discussion about the various choices: https://arxiv.org/abs/1707.01694 The basic points are this: The spike and slab prior can work quite well in practice but can be sensitive to specific choices made for the prior (e.g., slab width). Additionally, the spike and slab prior can be quite computationally intensive if you have a lot of variables. Continuous shrinkage priors (e.g., horseshoe) are computationally easier (e.g., you can implement them in Stan because they are continuous) but in the classic horseshoe there are issues such as the hyperparameter choice is arbitrary and large parameter values are not regularized. This is where the work of Piironen and Vehtari comes in.
Shrinkage priors
I don't quite know your specific use case though I can provide you with a bunch of resources so that you can make your own decision: Michael Betancourt's case study on sparse regressions: https://beta
Shrinkage priors I don't quite know your specific use case though I can provide you with a bunch of resources so that you can make your own decision: Michael Betancourt's case study on sparse regressions: https://betanalpha.github.io/assets/case_studies/bayes_sparse_regression.html That is a particularly great resource because he shows the effect of different priors on the same problem. Also he provides the code for the analysis so implementing it yourself is a lot easier And Piironen and Vehtari (2017) has a great discussion about the various choices: https://arxiv.org/abs/1707.01694 The basic points are this: The spike and slab prior can work quite well in practice but can be sensitive to specific choices made for the prior (e.g., slab width). Additionally, the spike and slab prior can be quite computationally intensive if you have a lot of variables. Continuous shrinkage priors (e.g., horseshoe) are computationally easier (e.g., you can implement them in Stan because they are continuous) but in the classic horseshoe there are issues such as the hyperparameter choice is arbitrary and large parameter values are not regularized. This is where the work of Piironen and Vehtari comes in.
Shrinkage priors I don't quite know your specific use case though I can provide you with a bunch of resources so that you can make your own decision: Michael Betancourt's case study on sparse regressions: https://beta
44,268
Shrinkage priors
You can check the following paper by Sarah Van Erp et al (2019), who discuss different shrinkage priors (below you can see table from their paper). Those priors vary greatly in their shapes, and so amount of shrinkage they provide. Besides discussing pros and cons of those priors, the authors describe a simulation study, where they compare performance of different priors. The results are mixed, for example, depend on if classical regularization, full Bayesian, or empirical Bayesian approach was used. What is also worth mentioning, is that in many cases the differences between different priors were rather small, with some differences when there was more features then samples. In practice this should not makes that big difference, especially when the sample size is large. Choice would be probably rather subjective, based on how much shrinkage would you expect to be needed. You could also make some simulation study, where you would sample data from the priors†, and check performance of the model on this data, by looking on the difference with ground truth values. In such study you would probably need to compare different amount of "false" features to be zeroed-out by shrinkage. † - i.e. simulate data that is similar to what would you expect to see, assuming that you have reasonable, informative priors to achieve this. Van Erp, S., Oberski, D. L., & Mulder, J. (2019). Shrinkage Priors for Bayesian Penalized Regression. Journal of Mathematical Psychology, 89, 31-50. doi:10.1016/j.jmp.2018.12.004 (preprint and supplement: https://osf.io/bf5up/)
Shrinkage priors
You can check the following paper by Sarah Van Erp et al (2019), who discuss different shrinkage priors (below you can see table from their paper). Those priors vary greatly in their shapes, and so a
Shrinkage priors You can check the following paper by Sarah Van Erp et al (2019), who discuss different shrinkage priors (below you can see table from their paper). Those priors vary greatly in their shapes, and so amount of shrinkage they provide. Besides discussing pros and cons of those priors, the authors describe a simulation study, where they compare performance of different priors. The results are mixed, for example, depend on if classical regularization, full Bayesian, or empirical Bayesian approach was used. What is also worth mentioning, is that in many cases the differences between different priors were rather small, with some differences when there was more features then samples. In practice this should not makes that big difference, especially when the sample size is large. Choice would be probably rather subjective, based on how much shrinkage would you expect to be needed. You could also make some simulation study, where you would sample data from the priors†, and check performance of the model on this data, by looking on the difference with ground truth values. In such study you would probably need to compare different amount of "false" features to be zeroed-out by shrinkage. † - i.e. simulate data that is similar to what would you expect to see, assuming that you have reasonable, informative priors to achieve this. Van Erp, S., Oberski, D. L., & Mulder, J. (2019). Shrinkage Priors for Bayesian Penalized Regression. Journal of Mathematical Psychology, 89, 31-50. doi:10.1016/j.jmp.2018.12.004 (preprint and supplement: https://osf.io/bf5up/)
Shrinkage priors You can check the following paper by Sarah Van Erp et al (2019), who discuss different shrinkage priors (below you can see table from their paper). Those priors vary greatly in their shapes, and so a
44,269
Expectation of truncated normal
Let $\phi(\cdot)$ and $\Phi(\cdot)$ be the PDF and CDF of standard normal distribution, as usual. Suppose $\Sigma=\left[\begin{matrix}\sigma_1^2&\rho \sigma_1\sigma_2\\\rho\sigma_1\sigma_2&\sigma_2^2\end{matrix}\right]$ is the dispersion matrix of $(X,Y)$. By definition, \begin{align} E\left[X\mid a<Y<b\right]&=\frac{E\left[XI(a<Y<b)\right]}{P(a<Y<b)} \\&=\frac1{P(a<Y<b)}\iint_{\mathbb R^2} x \mathbf1_{a<y<b}f_{X,Y}(x,y)\,\mathrm{d}x\,\mathrm{d}y \\&=\frac1{P(a<Y<b)}\int_a^b\int_{-\infty}^{\infty} xf_{X,Y}(x,y)\,\mathrm{d}x\,\mathrm{d}y \\&=\frac{1}{P(a<Y<b)}\int_a^b \left\{\int_{-\infty}^{\infty} xf_{X\mid Y}(x\mid y)\,\mathrm{d}x \right\}f_Y(y)\,\mathrm{d}y \\&=\frac{1}{P(a<Y<b)}\int_a^b E\left[X\mid Y=y\right]f_Y(y)\,\mathrm{d}y \end{align} This of course is same as saying $$E\left[X\mid a<Y<b\right]=\int_a^b E\left[X\mid Y=y\right]f_{Y\mid a<Y<b}(y)\,\mathrm{d}y$$ Now $X$ conditioned on $Y=y$ has a $N\left(\frac{\rho\,\sigma_1}{\sigma_2}y,(1-\rho^2)\sigma_1^2\right)$ distribution, so that $$E\left[X\mid Y=y\right]=\frac{\rho\,\sigma_1}{\sigma_2}y$$ In this case, we thus have \begin{align} E\left[X\mid Y>0\right]&=\frac{\rho\,\sigma_1}{\sigma_2}\int_0^\infty \frac{yf_Y(y)}{P(Y>0)}\,\mathrm{d}y \\&=\frac{\rho\,\sigma_1}{\sigma_2}E\left[Y\mid Y>0\right] \end{align} Finally, \begin{align} E\left[Y\mid Y>0\right]&=\frac{1}{P(Y>0)}\int_0^\infty \frac{y}{\sigma_2}\phi\left(\frac{y}{\sigma_2}\right)\mathrm{d}y \\&=2\sigma_2\int_0^\infty t\phi(t)\,\mathrm{d}t \\&=2\sigma_2\int_0^\infty (-\phi'(t))\,\mathrm{d}t \\&=2\sigma_2\,\phi(0) \\&=\sqrt{\frac{2}{\pi}}\sigma_2 \end{align} Hence for $(X,Y)\sim N(\mathbf 0,\Sigma)$, we have the simple formula $$\boxed{E\left[X\mid Y>0\right]=\sqrt{\frac{2}{\pi}}\rho\,\sigma_1}$$ A general formula where the means of $X$ and $Y$ are not zero, and $Y$ ranging from some $a$ to $b$ can also be found in a similar manner. That formula would involve $\phi$ and $\Phi$, whereas for the current one, we get the values at $\phi$ and $\Phi$ directly.
Expectation of truncated normal
Let $\phi(\cdot)$ and $\Phi(\cdot)$ be the PDF and CDF of standard normal distribution, as usual. Suppose $\Sigma=\left[\begin{matrix}\sigma_1^2&\rho \sigma_1\sigma_2\\\rho\sigma_1\sigma_2&\sigma_2^2\
Expectation of truncated normal Let $\phi(\cdot)$ and $\Phi(\cdot)$ be the PDF and CDF of standard normal distribution, as usual. Suppose $\Sigma=\left[\begin{matrix}\sigma_1^2&\rho \sigma_1\sigma_2\\\rho\sigma_1\sigma_2&\sigma_2^2\end{matrix}\right]$ is the dispersion matrix of $(X,Y)$. By definition, \begin{align} E\left[X\mid a<Y<b\right]&=\frac{E\left[XI(a<Y<b)\right]}{P(a<Y<b)} \\&=\frac1{P(a<Y<b)}\iint_{\mathbb R^2} x \mathbf1_{a<y<b}f_{X,Y}(x,y)\,\mathrm{d}x\,\mathrm{d}y \\&=\frac1{P(a<Y<b)}\int_a^b\int_{-\infty}^{\infty} xf_{X,Y}(x,y)\,\mathrm{d}x\,\mathrm{d}y \\&=\frac{1}{P(a<Y<b)}\int_a^b \left\{\int_{-\infty}^{\infty} xf_{X\mid Y}(x\mid y)\,\mathrm{d}x \right\}f_Y(y)\,\mathrm{d}y \\&=\frac{1}{P(a<Y<b)}\int_a^b E\left[X\mid Y=y\right]f_Y(y)\,\mathrm{d}y \end{align} This of course is same as saying $$E\left[X\mid a<Y<b\right]=\int_a^b E\left[X\mid Y=y\right]f_{Y\mid a<Y<b}(y)\,\mathrm{d}y$$ Now $X$ conditioned on $Y=y$ has a $N\left(\frac{\rho\,\sigma_1}{\sigma_2}y,(1-\rho^2)\sigma_1^2\right)$ distribution, so that $$E\left[X\mid Y=y\right]=\frac{\rho\,\sigma_1}{\sigma_2}y$$ In this case, we thus have \begin{align} E\left[X\mid Y>0\right]&=\frac{\rho\,\sigma_1}{\sigma_2}\int_0^\infty \frac{yf_Y(y)}{P(Y>0)}\,\mathrm{d}y \\&=\frac{\rho\,\sigma_1}{\sigma_2}E\left[Y\mid Y>0\right] \end{align} Finally, \begin{align} E\left[Y\mid Y>0\right]&=\frac{1}{P(Y>0)}\int_0^\infty \frac{y}{\sigma_2}\phi\left(\frac{y}{\sigma_2}\right)\mathrm{d}y \\&=2\sigma_2\int_0^\infty t\phi(t)\,\mathrm{d}t \\&=2\sigma_2\int_0^\infty (-\phi'(t))\,\mathrm{d}t \\&=2\sigma_2\,\phi(0) \\&=\sqrt{\frac{2}{\pi}}\sigma_2 \end{align} Hence for $(X,Y)\sim N(\mathbf 0,\Sigma)$, we have the simple formula $$\boxed{E\left[X\mid Y>0\right]=\sqrt{\frac{2}{\pi}}\rho\,\sigma_1}$$ A general formula where the means of $X$ and $Y$ are not zero, and $Y$ ranging from some $a$ to $b$ can also be found in a similar manner. That formula would involve $\phi$ and $\Phi$, whereas for the current one, we get the values at $\phi$ and $\Phi$ directly.
Expectation of truncated normal Let $\phi(\cdot)$ and $\Phi(\cdot)$ be the PDF and CDF of standard normal distribution, as usual. Suppose $\Sigma=\left[\begin{matrix}\sigma_1^2&\rho \sigma_1\sigma_2\\\rho\sigma_1\sigma_2&\sigma_2^2\
44,270
Expectation of truncated normal
Let's generalize the question so that a key idea can be revealed. Let $Y$ and $R$ be independent random variables. Define $$X=f(Y)+R$$ for a specified (measurable) function $f$. For any $a\lt b,$ what is the conditional expectation $$E[X\mid a\le Y \le b]?$$ (This states that $f$ is the regression of $X$ on $Y$ with i.i.d. additive errors.) The independence assumption makes this an easy question to answer, because the random variables $f(Y)$ and $R$ will still be independent, whence (by "taking out what is known") $$E[X\mid a\le Y \le b] = E[f(Y)+R\mid a\le Y \le b] = E[f(Y)\mid a \le Y \le b] + E[R].\tag{*}$$ This is very general. Let's specialize to the case $E[R]=0$ and $f$ is a linear transformation $$f(y) = \alpha\, y$$ for some constant number $\alpha.$ In this case $(*)$ simplifies to $$E[X\mid a\le Y \le b] = \alpha\, E[Y\mid a \le Y \le b].\tag{**}$$ The right hand side has a direct expression when the distribution of $Y,$ $F_Y,$ has a density $f_y,$ for then (by the definitions of conditional probability and expectation) $$E[Y\mid a \le Y \le b] = \frac{1}{F(b)-F(a)}\int_a^b y f_y(y) \mathrm{d}y.$$ The result is now immediate and obvious to anyone who has studied bivariate regression. (A good non-mathematical reference with all the necessary details is Freedman, Pisani, and Purves, Statistics [any edition].) The next section of this post is a review for those who might not have encountered this theory. In the case of the question, where $(x,y)$ is bivariate Normal with mean $(0,0),$ standard deviations $\sigma_x$ and $\sigma_y,$ and correlation $\rho,$ we know that the distribution of $(x,y)$ is the same as the distribution of $(X,Y)$ constructed as above where $Y$ has a Normal$(0,\sigma_y^2)$ distribution and $R$ independently has a Normal$(0,\tau^2)$ distribution (with $\tau$ to be found). The proof of this lies in the observations that Because $Y$ and $R$ are independent, the variance of $X = \rho\,Y+R$ equals $$\rho^2 \operatorname{Var}(Y) +\operatorname{Var}(R) =\rho^2\sigma^2_y + \tau^2.$$ Consequently, if we set $$\tau^2 = \sigma_x^2 - \rho^2\sigma_y^2,$$ the variance of $X$ will equal the variance of $x.$ The covariance $(X,Y)$ is $$\operatorname{Cov}(X,Y) = \operatorname{Cov}(\alpha\,Y+R,Y) = \alpha\operatorname{Var}(Y) = \alpha\,\sigma_y^2.$$ If we set $$\alpha = \rho\frac{\sigma_x}{\sigma_y}$$ then the correlation of $X$ and $Y$ will be $$\rho(X,Y) = \frac{\operatorname{Cov}(X,Y)}{\sigma_x\sigma_y} = \frac{\alpha\,\sigma_y^2}{\sigma_x\sigma_y} = \frac{\rho\frac{\sigma_x}{\sigma_y} \sigma_y^2}{\sigma_x\sigma_y} = \rho.$$ Observations (1) and (2) establish that $(X,Y)$ and $(x,y)$ have the same moments through second order, which means they have identical bivariate Normal distributions. Applying the main result $(**)$ gives $$E[X\mid a\le Y \le b] = \alpha\, E[Y\mid a \le Y \le b] = \rho\frac{\sigma_x}{\sigma_y}E[Y\mid a \le Y \le b].$$ We can go a little further towards simplification by recognizing that $Y/\sigma_y$ is a standard Normal variate. Thus, $$E[X\mid a\le Y \le b] = \rho\,\sigma_x E\left[\frac{Y}{\sigma_y}\mid \frac{a}{\sigma_y} \le \frac{Y}{\sigma_y} \le \frac{b}{\sigma_y} \right].$$ This shows that for fixed $a,b,$ the answer is directly proportional to $\rho\, \sigma_x.$ Evaluating the constant is a matter of manipulating integrals of a standard Normal variable, but doing so is primarily an exercise in Calculus rather than of statistical interest. I will conclude with the expression that I actually began with when solving this problem. Notice that the answer can also be written $$E\left[\frac{X}{\sigma_x}\mid a\le Y \le b\right] = \rho\, E\left[\frac{Y}{\sigma_y}\mid \frac{a}{\sigma_y} \le \frac{Y}{\sigma_y} \le \frac{b}{\sigma_y} \right].$$ The left hand side is the conditional expectation of a standard Normal variate $X/\sigma_x$ while the right hand side is just $\rho$ times the expectation of a truncated standard Normal variate $Y/\sigma_y.$ If you get used to standardizing variables automatically--which amounts to choosing a particularly convenient unit of measurement for them--then simply by visualizing the regression of $X$ against $Y$ you will say to yourself oh yes, since after standardization $X$ is just a multiple $\rho$ of $Y$, then the conditional expectation of $X$ must be $\rho$ times the corresponding expectation of $Y.$ That is the heart of the matter.
Expectation of truncated normal
Let's generalize the question so that a key idea can be revealed. Let $Y$ and $R$ be independent random variables. Define $$X=f(Y)+R$$ for a specified (measurable) function $f$. For any $a\lt b,$ w
Expectation of truncated normal Let's generalize the question so that a key idea can be revealed. Let $Y$ and $R$ be independent random variables. Define $$X=f(Y)+R$$ for a specified (measurable) function $f$. For any $a\lt b,$ what is the conditional expectation $$E[X\mid a\le Y \le b]?$$ (This states that $f$ is the regression of $X$ on $Y$ with i.i.d. additive errors.) The independence assumption makes this an easy question to answer, because the random variables $f(Y)$ and $R$ will still be independent, whence (by "taking out what is known") $$E[X\mid a\le Y \le b] = E[f(Y)+R\mid a\le Y \le b] = E[f(Y)\mid a \le Y \le b] + E[R].\tag{*}$$ This is very general. Let's specialize to the case $E[R]=0$ and $f$ is a linear transformation $$f(y) = \alpha\, y$$ for some constant number $\alpha.$ In this case $(*)$ simplifies to $$E[X\mid a\le Y \le b] = \alpha\, E[Y\mid a \le Y \le b].\tag{**}$$ The right hand side has a direct expression when the distribution of $Y,$ $F_Y,$ has a density $f_y,$ for then (by the definitions of conditional probability and expectation) $$E[Y\mid a \le Y \le b] = \frac{1}{F(b)-F(a)}\int_a^b y f_y(y) \mathrm{d}y.$$ The result is now immediate and obvious to anyone who has studied bivariate regression. (A good non-mathematical reference with all the necessary details is Freedman, Pisani, and Purves, Statistics [any edition].) The next section of this post is a review for those who might not have encountered this theory. In the case of the question, where $(x,y)$ is bivariate Normal with mean $(0,0),$ standard deviations $\sigma_x$ and $\sigma_y,$ and correlation $\rho,$ we know that the distribution of $(x,y)$ is the same as the distribution of $(X,Y)$ constructed as above where $Y$ has a Normal$(0,\sigma_y^2)$ distribution and $R$ independently has a Normal$(0,\tau^2)$ distribution (with $\tau$ to be found). The proof of this lies in the observations that Because $Y$ and $R$ are independent, the variance of $X = \rho\,Y+R$ equals $$\rho^2 \operatorname{Var}(Y) +\operatorname{Var}(R) =\rho^2\sigma^2_y + \tau^2.$$ Consequently, if we set $$\tau^2 = \sigma_x^2 - \rho^2\sigma_y^2,$$ the variance of $X$ will equal the variance of $x.$ The covariance $(X,Y)$ is $$\operatorname{Cov}(X,Y) = \operatorname{Cov}(\alpha\,Y+R,Y) = \alpha\operatorname{Var}(Y) = \alpha\,\sigma_y^2.$$ If we set $$\alpha = \rho\frac{\sigma_x}{\sigma_y}$$ then the correlation of $X$ and $Y$ will be $$\rho(X,Y) = \frac{\operatorname{Cov}(X,Y)}{\sigma_x\sigma_y} = \frac{\alpha\,\sigma_y^2}{\sigma_x\sigma_y} = \frac{\rho\frac{\sigma_x}{\sigma_y} \sigma_y^2}{\sigma_x\sigma_y} = \rho.$$ Observations (1) and (2) establish that $(X,Y)$ and $(x,y)$ have the same moments through second order, which means they have identical bivariate Normal distributions. Applying the main result $(**)$ gives $$E[X\mid a\le Y \le b] = \alpha\, E[Y\mid a \le Y \le b] = \rho\frac{\sigma_x}{\sigma_y}E[Y\mid a \le Y \le b].$$ We can go a little further towards simplification by recognizing that $Y/\sigma_y$ is a standard Normal variate. Thus, $$E[X\mid a\le Y \le b] = \rho\,\sigma_x E\left[\frac{Y}{\sigma_y}\mid \frac{a}{\sigma_y} \le \frac{Y}{\sigma_y} \le \frac{b}{\sigma_y} \right].$$ This shows that for fixed $a,b,$ the answer is directly proportional to $\rho\, \sigma_x.$ Evaluating the constant is a matter of manipulating integrals of a standard Normal variable, but doing so is primarily an exercise in Calculus rather than of statistical interest. I will conclude with the expression that I actually began with when solving this problem. Notice that the answer can also be written $$E\left[\frac{X}{\sigma_x}\mid a\le Y \le b\right] = \rho\, E\left[\frac{Y}{\sigma_y}\mid \frac{a}{\sigma_y} \le \frac{Y}{\sigma_y} \le \frac{b}{\sigma_y} \right].$$ The left hand side is the conditional expectation of a standard Normal variate $X/\sigma_x$ while the right hand side is just $\rho$ times the expectation of a truncated standard Normal variate $Y/\sigma_y.$ If you get used to standardizing variables automatically--which amounts to choosing a particularly convenient unit of measurement for them--then simply by visualizing the regression of $X$ against $Y$ you will say to yourself oh yes, since after standardization $X$ is just a multiple $\rho$ of $Y$, then the conditional expectation of $X$ must be $\rho$ times the corresponding expectation of $Y.$ That is the heart of the matter.
Expectation of truncated normal Let's generalize the question so that a key idea can be revealed. Let $Y$ and $R$ be independent random variables. Define $$X=f(Y)+R$$ for a specified (measurable) function $f$. For any $a\lt b,$ w
44,271
Expectation of truncated normal
I am posting the complete answer for reference: \begin{eqnarray*} E(X|a<Y<b) &= &\int_a^bE(X|Y=y)f_{Y|a<Y<b}(y)dy \\ & = &\rho_{xy}\frac{\sigma_x}{\sigma_y}\int_a^bf_{Y|a<Y<b}(y)dy \\ & = &\rho_{xy}\frac{\sigma_x}{\sigma_y}\sigma_y\frac{\phi(a)-\phi(b)}{\Phi(b)-\Phi(a)} \\ & = &\frac{\sigma_{xy}}{\sigma_y}\frac{\phi(a)-\phi(b)}{\Phi(b)-\Phi(a)} ,\end{eqnarray*} where $\rho_{xy} = E(xy) / (\sigma_x\sigma_y) =\sigma_{xy} / (\sigma_x \sigma_y)$. The second-to-last step is derived from the properties of the univariate truncated normal distribution, easily found on its wikipedia page. A reference for the first step is here With $a=0,b=\infty$ we have $$ E(X,Y>0) = \rho_{xy}\sigma_x\frac{\phi(0)}{\Phi(0)}= \rho_{xy}\sigma_x\cdot \frac{2}{\sqrt{2\pi}}= \frac{\sigma_{xy}}{\sigma_y}\cdot \frac{2}{\sqrt{2\pi}} $$ Thanks for pointing in the right direction.
Expectation of truncated normal
I am posting the complete answer for reference: \begin{eqnarray*} E(X|a<Y<b) &= &\int_a^bE(X|Y=y)f_{Y|a<Y<b}(y)dy \\ & = &\rho_{xy}\frac{\sigma_x}{\sigma_y}\int_a^bf_{Y|a<Y<b}(y)dy \\ & = &\rho_{xy}\f
Expectation of truncated normal I am posting the complete answer for reference: \begin{eqnarray*} E(X|a<Y<b) &= &\int_a^bE(X|Y=y)f_{Y|a<Y<b}(y)dy \\ & = &\rho_{xy}\frac{\sigma_x}{\sigma_y}\int_a^bf_{Y|a<Y<b}(y)dy \\ & = &\rho_{xy}\frac{\sigma_x}{\sigma_y}\sigma_y\frac{\phi(a)-\phi(b)}{\Phi(b)-\Phi(a)} \\ & = &\frac{\sigma_{xy}}{\sigma_y}\frac{\phi(a)-\phi(b)}{\Phi(b)-\Phi(a)} ,\end{eqnarray*} where $\rho_{xy} = E(xy) / (\sigma_x\sigma_y) =\sigma_{xy} / (\sigma_x \sigma_y)$. The second-to-last step is derived from the properties of the univariate truncated normal distribution, easily found on its wikipedia page. A reference for the first step is here With $a=0,b=\infty$ we have $$ E(X,Y>0) = \rho_{xy}\sigma_x\frac{\phi(0)}{\Phi(0)}= \rho_{xy}\sigma_x\cdot \frac{2}{\sqrt{2\pi}}= \frac{\sigma_{xy}}{\sigma_y}\cdot \frac{2}{\sqrt{2\pi}} $$ Thanks for pointing in the right direction.
Expectation of truncated normal I am posting the complete answer for reference: \begin{eqnarray*} E(X|a<Y<b) &= &\int_a^bE(X|Y=y)f_{Y|a<Y<b}(y)dy \\ & = &\rho_{xy}\frac{\sigma_x}{\sigma_y}\int_a^bf_{Y|a<Y<b}(y)dy \\ & = &\rho_{xy}\f
44,272
Does this graph support the assumption of homoscedasticity?
I don't think a graph can necessarily "show" homoscedasticity, but it can indicate to deviations from it. Your plot shows a very obvious trend in residuals vs. predicted. Anytime you see a some sort of a structure in these plots it's a source of concern. Ideally you should see a shapeless cloud of dots without any kind indication of a trend up or down. Yours is clearly downward sloping. It's not good.
Does this graph support the assumption of homoscedasticity?
I don't think a graph can necessarily "show" homoscedasticity, but it can indicate to deviations from it. Your plot shows a very obvious trend in residuals vs. predicted. Anytime you see a some sort o
Does this graph support the assumption of homoscedasticity? I don't think a graph can necessarily "show" homoscedasticity, but it can indicate to deviations from it. Your plot shows a very obvious trend in residuals vs. predicted. Anytime you see a some sort of a structure in these plots it's a source of concern. Ideally you should see a shapeless cloud of dots without any kind indication of a trend up or down. Yours is clearly downward sloping. It's not good.
Does this graph support the assumption of homoscedasticity? I don't think a graph can necessarily "show" homoscedasticity, but it can indicate to deviations from it. Your plot shows a very obvious trend in residuals vs. predicted. Anytime you see a some sort o
44,273
Does this graph support the assumption of homoscedasticity?
I must confess that I've never seen a plot where the fitted values are standardized - usually, we standardize the residuals but not the fitted values. The first thing you should do is draw an imaginary horizontal line through zero in this plot. This line will anchor the plot and really help you understand what is going on. If the observations in the plot are randomly scattered about the horizontal zero line such that the level of the scatter is roughly the same about this line as you move from the left to the right along the line, that would indicate that the linearity and homoscedasticity assumptions are not violated by the data. If, on top of this, most of the standardized residuals fall within +/- 3, then that might support the normality assumption (although, for checking the normality assumption, you are better off to look directly at the distribution of residuals via a histogram or density plot and also at a normal probability plot of residuals). In your plot, it looks like all 3 assumptions are violated by the data. The linearity assumption is violated because the cloud of points shows a systematic downard trend, as pointed out by @Aksakal. The homoscedasticity assumption is violated because the spread of the residuals is not (roughly) the same as you move along the horizontal line going through zero. The normality assumption is violated because the residuals do not form a cloud of points randomly and roughly evenly scattered between -3 and 3.
Does this graph support the assumption of homoscedasticity?
I must confess that I've never seen a plot where the fitted values are standardized - usually, we standardize the residuals but not the fitted values. The first thing you should do is draw an imagina
Does this graph support the assumption of homoscedasticity? I must confess that I've never seen a plot where the fitted values are standardized - usually, we standardize the residuals but not the fitted values. The first thing you should do is draw an imaginary horizontal line through zero in this plot. This line will anchor the plot and really help you understand what is going on. If the observations in the plot are randomly scattered about the horizontal zero line such that the level of the scatter is roughly the same about this line as you move from the left to the right along the line, that would indicate that the linearity and homoscedasticity assumptions are not violated by the data. If, on top of this, most of the standardized residuals fall within +/- 3, then that might support the normality assumption (although, for checking the normality assumption, you are better off to look directly at the distribution of residuals via a histogram or density plot and also at a normal probability plot of residuals). In your plot, it looks like all 3 assumptions are violated by the data. The linearity assumption is violated because the cloud of points shows a systematic downard trend, as pointed out by @Aksakal. The homoscedasticity assumption is violated because the spread of the residuals is not (roughly) the same as you move along the horizontal line going through zero. The normality assumption is violated because the residuals do not form a cloud of points randomly and roughly evenly scattered between -3 and 3.
Does this graph support the assumption of homoscedasticity? I must confess that I've never seen a plot where the fitted values are standardized - usually, we standardize the residuals but not the fitted values. The first thing you should do is draw an imagina
44,274
Does this graph support the assumption of homoscedasticity?
The graph does show that there are issues with this model, but the question is whether or not it shows deviations from the hypothesis of homoscedasticity, and that is not quite clear from the graph. I think it does show some deviation: sigma seems smaller at low values of the predicted variable, but it is hard to tell. The graph does show that the mean of the residuals is going down from right to left (although, as pointed out by whuber, there is some level of optical illusion in this, because of the larger amount of points in the bottom left). So, the distribution of the residuals (specifically, the mean of the distribution) is probably not the same at high and low values of the predictions (can fit a model of the form a*x+b to the residuals and show it in the same plot) . I would not call this a violation of linearity (residuals in non-linear regression models are also expected to have the same mean throughout the application domain), but it does seem to violate the assumption that all residuals are coming from the same distribution. The simplest way to test whether the mean of the residuals has a trend is to look at at ANOVA table of the regression model (this is a bit different from, although related to, doing an ANOVA analysis of the residuals). In Mathematica, the property "ANOVATable" is available for regression models obtained with LinearModelFit and NonlinearModelFit. In fairness, using the standard ANOVA is not quite justified, because the distribution of the residuals does not look normal. There are non-parametric ANOVA methods that could be used (Kruskal-Wallis). Honestly, I think a test is hardly necessary, the trend seems clear to me from the graph. The plot I suggest above will give you a value for the slope. A test like ANOVA (or similar) would give you a p-value to judge whether that slope is significantly different from zero (one cannot expect it to be exactly zero). Back to homoscedasticity, you would need to check that the standard deviation (sigma, for short), not the mean, is the same at different values of the predicted variable. One simple way to do this is to bin the data in a few bins and compute sigma in each bin. Of course, there is some freedom as to how to bin the data (so this simple approach relies on judgement). Instead of computing the sigmas for each bin, you can just do a test on the groups of residuals in each bin. The Bartlett test, for example, takes several samples as its input and decides whether the samples came from distributions with the same sigma (not whether they came from the same distribution). In your case, it looks like there are serious deviations from normality, so the Bartlett test may not be the best, Levene is more robust. In Mathematica, the function VarianceEquivalentTest takes in several samples (which would just be your residuals in different bins) and returns the results of several tests (Bartlett, Levene, Conover, etc.), on whether the samples have the same sigma. I think it will refrain from reporting on a test that does not seem applicable to the data. From your graph, I would be inclined to say that at low values of the predicted variable your sigma looks smaller (same level of spread with more data points usually means lower sigma). But it is not as clear to me as is the trend in the mean, for example (again, even for the trend in the means, it has been suggested that the graph could be deceiving because of the variations in population density). A clear violation of homoscedasticity is a graph with very narrow spread in some parts and very wide in others, and yours does not display that very clearly. But is does not clearly show the opposite either. Another way to test for homoscedasticity directly on the residuals (without binning the data) is to run the Breusch-Pagan test or the White test on the residuals (you will need the residuals AND the predicted values, because these tests check whether sigma seems to be a function of the predicted values). The residuals do show a clear deviation from normality, it even seems clear that they are bimodal. For example, at large values of the predicted variable, the residuals are clearly concentrated around two values, one high and one low. You could run a normality test on the residuals (seems hardly necessary), like Anderson-Darling, Smirnov, etc., but since the residuals seem to be coming from different distributions, these tests are not very meaningful. A test of normality makes sense in a sample that was all taken from the same distribution. In this sense, a test of normality should usually come last, after you have established that all the residuals come from the same distribution. Some people just do a test of normality and nothing else, assuming that if the residuals came from different distributions, most likely a test of normality would fail. There is some truth to that, but it is very shaky statistics. It is like saying that if the body temperature is normal, then the patient is healthy. In general, you want to see evidence that all your residuals are coming from the same distribution. The first thing to check is the mean and sigma. In your case, the mean does not not seem constant to me, but you should check, and for sigma it is just harder to say from your graph (so the short answer to your original question, which this certainly isn't, is that it is hard to tell from your graph). Of course, a distribution is more than just its mean and its sigma, but if those two look good (meaning, if they constant throughout the application domain), then there is reason to celebrate. If the residuals all come from the same distribution, then one would also want for that distribution to be centered around zero, to be unimodal, preferably symmetric, and, ideally, normal. But normality is like the last nice-to-have, not a requirement for a good model. Lastly, remember that the scatter plot of the residuals for a good model can look a bit messy. To a large degree this depends on how uniformly populated the different regions of the model domain are. If one has significant amount of data in one region and very little in others, then there are issues related to leverage of different data points. This is in part why one looks at standardized residuals and studentized residuals. In my mind, a plot of residuals that looks too ideal (a perfectly horizontal, evenly populated rectangle), suggests a fudged model, rather than a good model.
Does this graph support the assumption of homoscedasticity?
The graph does show that there are issues with this model, but the question is whether or not it shows deviations from the hypothesis of homoscedasticity, and that is not quite clear from the graph. I
Does this graph support the assumption of homoscedasticity? The graph does show that there are issues with this model, but the question is whether or not it shows deviations from the hypothesis of homoscedasticity, and that is not quite clear from the graph. I think it does show some deviation: sigma seems smaller at low values of the predicted variable, but it is hard to tell. The graph does show that the mean of the residuals is going down from right to left (although, as pointed out by whuber, there is some level of optical illusion in this, because of the larger amount of points in the bottom left). So, the distribution of the residuals (specifically, the mean of the distribution) is probably not the same at high and low values of the predictions (can fit a model of the form a*x+b to the residuals and show it in the same plot) . I would not call this a violation of linearity (residuals in non-linear regression models are also expected to have the same mean throughout the application domain), but it does seem to violate the assumption that all residuals are coming from the same distribution. The simplest way to test whether the mean of the residuals has a trend is to look at at ANOVA table of the regression model (this is a bit different from, although related to, doing an ANOVA analysis of the residuals). In Mathematica, the property "ANOVATable" is available for regression models obtained with LinearModelFit and NonlinearModelFit. In fairness, using the standard ANOVA is not quite justified, because the distribution of the residuals does not look normal. There are non-parametric ANOVA methods that could be used (Kruskal-Wallis). Honestly, I think a test is hardly necessary, the trend seems clear to me from the graph. The plot I suggest above will give you a value for the slope. A test like ANOVA (or similar) would give you a p-value to judge whether that slope is significantly different from zero (one cannot expect it to be exactly zero). Back to homoscedasticity, you would need to check that the standard deviation (sigma, for short), not the mean, is the same at different values of the predicted variable. One simple way to do this is to bin the data in a few bins and compute sigma in each bin. Of course, there is some freedom as to how to bin the data (so this simple approach relies on judgement). Instead of computing the sigmas for each bin, you can just do a test on the groups of residuals in each bin. The Bartlett test, for example, takes several samples as its input and decides whether the samples came from distributions with the same sigma (not whether they came from the same distribution). In your case, it looks like there are serious deviations from normality, so the Bartlett test may not be the best, Levene is more robust. In Mathematica, the function VarianceEquivalentTest takes in several samples (which would just be your residuals in different bins) and returns the results of several tests (Bartlett, Levene, Conover, etc.), on whether the samples have the same sigma. I think it will refrain from reporting on a test that does not seem applicable to the data. From your graph, I would be inclined to say that at low values of the predicted variable your sigma looks smaller (same level of spread with more data points usually means lower sigma). But it is not as clear to me as is the trend in the mean, for example (again, even for the trend in the means, it has been suggested that the graph could be deceiving because of the variations in population density). A clear violation of homoscedasticity is a graph with very narrow spread in some parts and very wide in others, and yours does not display that very clearly. But is does not clearly show the opposite either. Another way to test for homoscedasticity directly on the residuals (without binning the data) is to run the Breusch-Pagan test or the White test on the residuals (you will need the residuals AND the predicted values, because these tests check whether sigma seems to be a function of the predicted values). The residuals do show a clear deviation from normality, it even seems clear that they are bimodal. For example, at large values of the predicted variable, the residuals are clearly concentrated around two values, one high and one low. You could run a normality test on the residuals (seems hardly necessary), like Anderson-Darling, Smirnov, etc., but since the residuals seem to be coming from different distributions, these tests are not very meaningful. A test of normality makes sense in a sample that was all taken from the same distribution. In this sense, a test of normality should usually come last, after you have established that all the residuals come from the same distribution. Some people just do a test of normality and nothing else, assuming that if the residuals came from different distributions, most likely a test of normality would fail. There is some truth to that, but it is very shaky statistics. It is like saying that if the body temperature is normal, then the patient is healthy. In general, you want to see evidence that all your residuals are coming from the same distribution. The first thing to check is the mean and sigma. In your case, the mean does not not seem constant to me, but you should check, and for sigma it is just harder to say from your graph (so the short answer to your original question, which this certainly isn't, is that it is hard to tell from your graph). Of course, a distribution is more than just its mean and its sigma, but if those two look good (meaning, if they constant throughout the application domain), then there is reason to celebrate. If the residuals all come from the same distribution, then one would also want for that distribution to be centered around zero, to be unimodal, preferably symmetric, and, ideally, normal. But normality is like the last nice-to-have, not a requirement for a good model. Lastly, remember that the scatter plot of the residuals for a good model can look a bit messy. To a large degree this depends on how uniformly populated the different regions of the model domain are. If one has significant amount of data in one region and very little in others, then there are issues related to leverage of different data points. This is in part why one looks at standardized residuals and studentized residuals. In my mind, a plot of residuals that looks too ideal (a perfectly horizontal, evenly populated rectangle), suggests a fudged model, rather than a good model.
Does this graph support the assumption of homoscedasticity? The graph does show that there are issues with this model, but the question is whether or not it shows deviations from the hypothesis of homoscedasticity, and that is not quite clear from the graph. I
44,275
Does this graph support the assumption of homoscedasticity?
Note: I use capital letters to refer to an entire vector, and lower case letters to refer to a specific observation of a vector. Hopefully this isn't confusing. I think the answer ought to be no. I offer an intuitive explanation, as well as some quick and dirty (emphasis on dirty) R code that supports my assertion. The variance of the $Y$ values is increasing with $x$, because even though the range of $Y$ appears to be somewhat constant over the domain of $X$, the average distance of the points from their mean (as a function of $x$) is actually increasing. You can see this because the density of $Y$ in regions between its extents is actually decreasing with increasing $x$, and therefore the average squared deviation (variance) from the mean is increasing. In other words, pretty much all the $y$ values' separation from the mean (conditional on $x$) are "really large" for large $x$, while at smaller $x$, they're anywhere from zero to "really large." Anyway, I wouldn't be surprised if folks find that explanation really confusing. If so, just run the following in R, and observe the resulting plot. set.seed(999) n.lines <- 10 n.points.per.line <- 100 min.intercept <- -3 max.intercept <- 3 x <- vector('numeric') y <- x intercept <- seq(from=min.intercept, to=max.intercept, length.out=n.lines) for (i in 1:n.lines) { min <- -1.5 max <- intercept[i]^2 x.new <- runif(n=n.points.per.line, min=min, max=max) x <- c(x, x.new) y <- c(y, -0.1*x.new+intercept[i]) } ylim <- c(min(y)*1.1, var(y)*3) xlim <- c(min(x)*1.1, max(x)*1.1) xlab <- 'x' ylab <- 'y' plot(x, y, type='p', ylim=ylim, xlim=xlim, ylab=ylab, xlab=xlab) buckets <- ceiling(seq(from=min(x), to=max(x))) var.y <- sapply(buckets, function(i) { y <- y[which(x <= i & x >= (i-1))] var(y) }) par(new=T) plot(x=buckets, y=var.y, col='blue', type='l', ylim=ylim, xlim=xlim, ylab=ylab, xlab=xlab) This is far from exact, but the data look a lot like yours. I bucketed $Y$ into about ten different intervals (based on integer values of $X$) and computed their variance; the blue line shows this in the plot. As you can see, it is increasing with $x$, and therefore the data are not homoscedastic.
Does this graph support the assumption of homoscedasticity?
Note: I use capital letters to refer to an entire vector, and lower case letters to refer to a specific observation of a vector. Hopefully this isn't confusing. I think the answer ought to be no. I of
Does this graph support the assumption of homoscedasticity? Note: I use capital letters to refer to an entire vector, and lower case letters to refer to a specific observation of a vector. Hopefully this isn't confusing. I think the answer ought to be no. I offer an intuitive explanation, as well as some quick and dirty (emphasis on dirty) R code that supports my assertion. The variance of the $Y$ values is increasing with $x$, because even though the range of $Y$ appears to be somewhat constant over the domain of $X$, the average distance of the points from their mean (as a function of $x$) is actually increasing. You can see this because the density of $Y$ in regions between its extents is actually decreasing with increasing $x$, and therefore the average squared deviation (variance) from the mean is increasing. In other words, pretty much all the $y$ values' separation from the mean (conditional on $x$) are "really large" for large $x$, while at smaller $x$, they're anywhere from zero to "really large." Anyway, I wouldn't be surprised if folks find that explanation really confusing. If so, just run the following in R, and observe the resulting plot. set.seed(999) n.lines <- 10 n.points.per.line <- 100 min.intercept <- -3 max.intercept <- 3 x <- vector('numeric') y <- x intercept <- seq(from=min.intercept, to=max.intercept, length.out=n.lines) for (i in 1:n.lines) { min <- -1.5 max <- intercept[i]^2 x.new <- runif(n=n.points.per.line, min=min, max=max) x <- c(x, x.new) y <- c(y, -0.1*x.new+intercept[i]) } ylim <- c(min(y)*1.1, var(y)*3) xlim <- c(min(x)*1.1, max(x)*1.1) xlab <- 'x' ylab <- 'y' plot(x, y, type='p', ylim=ylim, xlim=xlim, ylab=ylab, xlab=xlab) buckets <- ceiling(seq(from=min(x), to=max(x))) var.y <- sapply(buckets, function(i) { y <- y[which(x <= i & x >= (i-1))] var(y) }) par(new=T) plot(x=buckets, y=var.y, col='blue', type='l', ylim=ylim, xlim=xlim, ylab=ylab, xlab=xlab) This is far from exact, but the data look a lot like yours. I bucketed $Y$ into about ten different intervals (based on integer values of $X$) and computed their variance; the blue line shows this in the plot. As you can see, it is increasing with $x$, and therefore the data are not homoscedastic.
Does this graph support the assumption of homoscedasticity? Note: I use capital letters to refer to an entire vector, and lower case letters to refer to a specific observation of a vector. Hopefully this isn't confusing. I think the answer ought to be no. I of
44,276
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis
Not necessarily. You might have high Cronbach's alpha while items are weakly correlated. The reason is that Cronbach's alpha does not only depend on the correlation/covariance of the items, but also the number of items. If the number of items are high enough (which is probably the case in your analysis), you will have high Cronbach's alpha, even though the items are weakly correlated. As a quick example, we can look at the formula of the standardized alpha: $$\alpha_\text{standardized} = \frac{K \bar r}{1 + (K - 1)\bar r}$$ Where $K$ is the number of items and $\bar r$ is the mean correlation among the items. If you have 50 items, an average correlation of 0.15 will give 0.9 alpha. If this is the case, it is not surprising to get poor results from the factor analysis. A critical assessment of Cronbach's alpha: Sijtsma, K., 2009. On the Use, the Misuse, and the Very Limited Usefulness of Cronbach’s Alpha. Psychometrika 74, 107–120.
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis
Not necessarily. You might have high Cronbach's alpha while items are weakly correlated. The reason is that Cronbach's alpha does not only depend on the correlation/covariance of the items, but also t
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis Not necessarily. You might have high Cronbach's alpha while items are weakly correlated. The reason is that Cronbach's alpha does not only depend on the correlation/covariance of the items, but also the number of items. If the number of items are high enough (which is probably the case in your analysis), you will have high Cronbach's alpha, even though the items are weakly correlated. As a quick example, we can look at the formula of the standardized alpha: $$\alpha_\text{standardized} = \frac{K \bar r}{1 + (K - 1)\bar r}$$ Where $K$ is the number of items and $\bar r$ is the mean correlation among the items. If you have 50 items, an average correlation of 0.15 will give 0.9 alpha. If this is the case, it is not surprising to get poor results from the factor analysis. A critical assessment of Cronbach's alpha: Sijtsma, K., 2009. On the Use, the Misuse, and the Very Limited Usefulness of Cronbach’s Alpha. Psychometrika 74, 107–120.
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis Not necessarily. You might have high Cronbach's alpha while items are weakly correlated. The reason is that Cronbach's alpha does not only depend on the correlation/covariance of the items, but also t
44,277
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis
You should not consider Cronbach's alpha along with exploratory Factor analysis. Alpha is from the domain of reliability, specifically, one of measures of item-item homogeneity (interchangeability) within a scale; or more specifically about alpha - how much sufficient a scale is supplied with items. Factor analysis is done to uncover latent traits and to validate a scale which pretend to be based on one factor. See reliability vs validity views. According to classic reliability viewpoint, questionnaire items (which scores are summed or averaged to give the overall scale score) are seen as the repeated measurements of something one and same. Consider just one respondent and a scale comprised of two items. His responses are modelled as: Item1 = T + e' and Item2 = T + e'' T stands for the "true score" of the scale. We do not claim that the true score is the value of some latent trait of factor, though we might. There could be a mixture of factors actually behind the true score; the question what is behind it is beyond the scope of reliability. Suffice to think there is something "true" that the questionnaire measures. The fact that T is the same symbol in both equations says that it is the same value in both, characterizing our concrete respondent's posession (or view) of what is being measured (we'll assume for simplicity that both items have equal so called "difficulty level"). The fact that T is capital letter serves to convey to us that within the respondent level it is a fixed quantity, not a random value which might vary. e stands for "measurement error". It could be conceptualized as momentary fault occuring by chance while the respondent is making an answer. Items do differ by wording, however that respondent's reaction to an item peculiarity is considered by the model exactly like his unexpected sneeze to put out the pen one point away. It is single random variable within the respondent (the letter is lowercase) with two happened realizations, values e' and e''. Like most noise, they are assumed to come from normal distribution with zero mean and some variance. That variance is the measure of an individual item's unreliability. We'll assume for simplicity that variances are equal for both items, though they could differ. Now to the essence of the question - why reliability (in the form of Cronbach's at least) may grow just simply as we add more items (as was shown in the answer by @T.E.G.). Because T (on respondent level) is constant and items are repeated measurement attempts of the same thing, varying only by the unbiased (symmetric) noise e, the more attempts (items) 1,2,3,... we use the closer the sum e'+e''+e'''+... is to zero, their expectation, and so the closer the mean of items to T. Cancelling out of noise effect on the mean as tries accumulate. If there were no error terms (no "sneezing" effects, so to speak) then all correlations would be complete (r=1) and alpha'd be 1. It is just due to the error assumed independent from item to item that mean r come below 1 - since the simplest reliability model declares no other source of variation besides true score T and "sneezing" error e. With only 2 items, the sneeze shifts won't probably cancel each other but with many items they will. Thus, alpha grows as errors are smaller (hence correlations are bigger) and/or correlating items are more plenty. Classic Factor analysis model is a bit more complex than the classic scale reliability model. Let us have just one-factor model: Item1 = F + S1 + e' and Item2 = F + S2 + e'' F is the latent common factor which our scale (consisting of items) aims to measure. S1 and S2 are the specific factors belonging to item1 and item2, respectively. e is the random error term like the one described earlier. Specific factors are not known or measured but they are real, because it is realistic to suppose that each item contains something common with other items (and what makes them to correlate) and something individual (what hinders them to correlate completely). That individual parts S1 and S2 are systematic (i.e. fixed on a given respondent level), like factor F is, and they are two different values. Thus the "true score" of the scale T1=F+S1 and T2=F+S2 is not same magnitude in different items. Even though as you add more and more items (with individual S's) error term sum e'+e''+e'''+... will converge towards zero, it won't help stabilize on the unbiased F (our aim) as something what the scale (sum or mean of items) reflects, because we don't know S1+S2+S3... sum of values within a respondent. Adding items to a scale (construct) does not necessarily make the scale more valid as a measure of the latent factor it was intended to measure, in spite that the scale tends to grow in reliability to measure "whatever it measures", something one. Reliability testing, to repeat, assumes that items are equivalent and their scores are just randompy noised, so adding the sufficient number of items (few, if possible, they are to correlate better, then) recovers true, unbiased score of the scale for every respondent. Factor analysis do not pose that items are equivalent, they contain true factor inside plus item-specific biases away from it, along with random noise; so summing up items (even quite well correlated due to the same factor) does not guarantee the unbiased estimate of the factor value for every respondent. Moreover, in factor analysis as it is computationally we actually do not consider measurement errors e separately at all. That term is seen immersed into the term called "unique factor" U: U1=S1+e' and U2=S2+e'', which complements the common F in the model. Factor extraction usually will aim to maximize F variance, thus minimize on the overall Us' variances. That implies that error es' variances are also constrained, "preselected". That makes Factor analysis barely comparable with Reliability analysis. There, however, exist Alpha factor analysis which is more kindred to Reliability analysis with its Cronbach.
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis
You should not consider Cronbach's alpha along with exploratory Factor analysis. Alpha is from the domain of reliability, specifically, one of measures of item-item homogeneity (interchangeability) wi
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis You should not consider Cronbach's alpha along with exploratory Factor analysis. Alpha is from the domain of reliability, specifically, one of measures of item-item homogeneity (interchangeability) within a scale; or more specifically about alpha - how much sufficient a scale is supplied with items. Factor analysis is done to uncover latent traits and to validate a scale which pretend to be based on one factor. See reliability vs validity views. According to classic reliability viewpoint, questionnaire items (which scores are summed or averaged to give the overall scale score) are seen as the repeated measurements of something one and same. Consider just one respondent and a scale comprised of two items. His responses are modelled as: Item1 = T + e' and Item2 = T + e'' T stands for the "true score" of the scale. We do not claim that the true score is the value of some latent trait of factor, though we might. There could be a mixture of factors actually behind the true score; the question what is behind it is beyond the scope of reliability. Suffice to think there is something "true" that the questionnaire measures. The fact that T is the same symbol in both equations says that it is the same value in both, characterizing our concrete respondent's posession (or view) of what is being measured (we'll assume for simplicity that both items have equal so called "difficulty level"). The fact that T is capital letter serves to convey to us that within the respondent level it is a fixed quantity, not a random value which might vary. e stands for "measurement error". It could be conceptualized as momentary fault occuring by chance while the respondent is making an answer. Items do differ by wording, however that respondent's reaction to an item peculiarity is considered by the model exactly like his unexpected sneeze to put out the pen one point away. It is single random variable within the respondent (the letter is lowercase) with two happened realizations, values e' and e''. Like most noise, they are assumed to come from normal distribution with zero mean and some variance. That variance is the measure of an individual item's unreliability. We'll assume for simplicity that variances are equal for both items, though they could differ. Now to the essence of the question - why reliability (in the form of Cronbach's at least) may grow just simply as we add more items (as was shown in the answer by @T.E.G.). Because T (on respondent level) is constant and items are repeated measurement attempts of the same thing, varying only by the unbiased (symmetric) noise e, the more attempts (items) 1,2,3,... we use the closer the sum e'+e''+e'''+... is to zero, their expectation, and so the closer the mean of items to T. Cancelling out of noise effect on the mean as tries accumulate. If there were no error terms (no "sneezing" effects, so to speak) then all correlations would be complete (r=1) and alpha'd be 1. It is just due to the error assumed independent from item to item that mean r come below 1 - since the simplest reliability model declares no other source of variation besides true score T and "sneezing" error e. With only 2 items, the sneeze shifts won't probably cancel each other but with many items they will. Thus, alpha grows as errors are smaller (hence correlations are bigger) and/or correlating items are more plenty. Classic Factor analysis model is a bit more complex than the classic scale reliability model. Let us have just one-factor model: Item1 = F + S1 + e' and Item2 = F + S2 + e'' F is the latent common factor which our scale (consisting of items) aims to measure. S1 and S2 are the specific factors belonging to item1 and item2, respectively. e is the random error term like the one described earlier. Specific factors are not known or measured but they are real, because it is realistic to suppose that each item contains something common with other items (and what makes them to correlate) and something individual (what hinders them to correlate completely). That individual parts S1 and S2 are systematic (i.e. fixed on a given respondent level), like factor F is, and they are two different values. Thus the "true score" of the scale T1=F+S1 and T2=F+S2 is not same magnitude in different items. Even though as you add more and more items (with individual S's) error term sum e'+e''+e'''+... will converge towards zero, it won't help stabilize on the unbiased F (our aim) as something what the scale (sum or mean of items) reflects, because we don't know S1+S2+S3... sum of values within a respondent. Adding items to a scale (construct) does not necessarily make the scale more valid as a measure of the latent factor it was intended to measure, in spite that the scale tends to grow in reliability to measure "whatever it measures", something one. Reliability testing, to repeat, assumes that items are equivalent and their scores are just randompy noised, so adding the sufficient number of items (few, if possible, they are to correlate better, then) recovers true, unbiased score of the scale for every respondent. Factor analysis do not pose that items are equivalent, they contain true factor inside plus item-specific biases away from it, along with random noise; so summing up items (even quite well correlated due to the same factor) does not guarantee the unbiased estimate of the factor value for every respondent. Moreover, in factor analysis as it is computationally we actually do not consider measurement errors e separately at all. That term is seen immersed into the term called "unique factor" U: U1=S1+e' and U2=S2+e'', which complements the common F in the model. Factor extraction usually will aim to maximize F variance, thus minimize on the overall Us' variances. That implies that error es' variances are also constrained, "preselected". That makes Factor analysis barely comparable with Reliability analysis. There, however, exist Alpha factor analysis which is more kindred to Reliability analysis with its Cronbach.
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis You should not consider Cronbach's alpha along with exploratory Factor analysis. Alpha is from the domain of reliability, specifically, one of measures of item-item homogeneity (interchangeability) wi
44,278
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis
So for example, let’s say I do a survey on healthy eating. My questions are: 1) Do you like cherry tomatoes? 2) Do you like yellow tomatoes? Whenever the respondent answers these questions, he sneezes and slightly shifts his pen on the paper. If I add the answers to the 2 questions, I average out this error. As I add more questions, I get more covariance terms in the denominator for the formula for Chronbach alpha, and –provided the covariances are positive- alpha gets bigger as I add questions. This is counteracted slightly by the K/(K-1) factor in the formula for alpha, which gets smaller as K increases. (K being the number of questions). That would also be the case even if there were no error terms (no sneezing) Now for factor analysis: I am looking for a hidden factor (‘healthy eating’), and now we see the answer to question 1 as made up of 3 things: healthy eating, his liking for cherry tomatoes, and the sneeze. Adding more questions will average out the sneeze as before, but gets me no closer to my hidden factor, because I keep adding variables, such as his liking for yellow things, etc. Is it necessarily a bad thing if I cannot find a small number of latent factors in a survey?
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis
So for example, let’s say I do a survey on healthy eating. My questions are: 1) Do you like cherry tomatoes? 2) Do you like yellow tomatoes? Whenever the respondent answers these questions, he sneez
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis So for example, let’s say I do a survey on healthy eating. My questions are: 1) Do you like cherry tomatoes? 2) Do you like yellow tomatoes? Whenever the respondent answers these questions, he sneezes and slightly shifts his pen on the paper. If I add the answers to the 2 questions, I average out this error. As I add more questions, I get more covariance terms in the denominator for the formula for Chronbach alpha, and –provided the covariances are positive- alpha gets bigger as I add questions. This is counteracted slightly by the K/(K-1) factor in the formula for alpha, which gets smaller as K increases. (K being the number of questions). That would also be the case even if there were no error terms (no sneezing) Now for factor analysis: I am looking for a hidden factor (‘healthy eating’), and now we see the answer to question 1 as made up of 3 things: healthy eating, his liking for cherry tomatoes, and the sneeze. Adding more questions will average out the sneeze as before, but gets me no closer to my hidden factor, because I keep adding variables, such as his liking for yellow things, etc. Is it necessarily a bad thing if I cannot find a small number of latent factors in a survey?
What does it mean if I have high Cronbach alpha, but poor results in Exploratory Factor Analysis So for example, let’s say I do a survey on healthy eating. My questions are: 1) Do you like cherry tomatoes? 2) Do you like yellow tomatoes? Whenever the respondent answers these questions, he sneez
44,279
How can I apply Akaike Information Criterion and calculate it for Linear Regression?
A simple formula for the calculation of the AIC in the OLS framework (since you say linear regression) can be found in Gordon (2015, p. 201): $$\text{AIC} = n *\ln\Big(\frac{SSE}{n}\Big)+2k $$ Where SSE means Sum of Squared Errors ($\sum(Y_i-\hat Y_i)^2$), $n$ is the sample size, and $k$ is the number of predictors in the model plus one for the intercept. Although AIC values are not generally interpretable, differences between values for different models can be interpreted (A number of questions on CV covers this issue, for example in here). So, the model with the smallest AIC is usually selected. It is easy to see why this is the case in the above formula: All else being equal, as the SSE decreases, AIC also decreases. In other sources, you may find a more general, maximum-likelihood formula. For example, in Applied Regression Analysis and Generalized Linear Models, Fox provides: $$\text{AIC}_j \equiv - \text{log}_eL(\hat \theta_j)+2s_j$$ where $L(\hat \theta_j)$ is the maximized likelihood under model $M_j$ ($\theta_j$ is the vector of parameters of the model, $\hat \theta_j$ is the vector of maximum-likelihood estimates of the parameters) and $s_j$ is the number of parameters (Fox 2016, p. 673-674). In OLS framework, this second formula simplifies to the first one. Using this first formula, I think it is not difficult to calculate and use AIC for the comparison of linear regression models. Fox, J. (2016). Applied Regression Analysis and Generalized Linear Models (3rd ed.). Los Angeles: Sage Publications. Gordon, R. A. (2015). Regression Analysis for the Social Sciences. New York and London: Routledge. And the original article: Akaike, H. (1998). Information Theory and an Extension of the Maximum Likelihood Principle. In E. Parzen, K. Tanabe, & G. Kitagawa (Eds.), Selected Papers of Hirotogu Akaike (pp. 199–215). New York: Springer.
How can I apply Akaike Information Criterion and calculate it for Linear Regression?
A simple formula for the calculation of the AIC in the OLS framework (since you say linear regression) can be found in Gordon (2015, p. 201): $$\text{AIC} = n *\ln\Big(\frac{SSE}{n}\Big)+2k $$ Where S
How can I apply Akaike Information Criterion and calculate it for Linear Regression? A simple formula for the calculation of the AIC in the OLS framework (since you say linear regression) can be found in Gordon (2015, p. 201): $$\text{AIC} = n *\ln\Big(\frac{SSE}{n}\Big)+2k $$ Where SSE means Sum of Squared Errors ($\sum(Y_i-\hat Y_i)^2$), $n$ is the sample size, and $k$ is the number of predictors in the model plus one for the intercept. Although AIC values are not generally interpretable, differences between values for different models can be interpreted (A number of questions on CV covers this issue, for example in here). So, the model with the smallest AIC is usually selected. It is easy to see why this is the case in the above formula: All else being equal, as the SSE decreases, AIC also decreases. In other sources, you may find a more general, maximum-likelihood formula. For example, in Applied Regression Analysis and Generalized Linear Models, Fox provides: $$\text{AIC}_j \equiv - \text{log}_eL(\hat \theta_j)+2s_j$$ where $L(\hat \theta_j)$ is the maximized likelihood under model $M_j$ ($\theta_j$ is the vector of parameters of the model, $\hat \theta_j$ is the vector of maximum-likelihood estimates of the parameters) and $s_j$ is the number of parameters (Fox 2016, p. 673-674). In OLS framework, this second formula simplifies to the first one. Using this first formula, I think it is not difficult to calculate and use AIC for the comparison of linear regression models. Fox, J. (2016). Applied Regression Analysis and Generalized Linear Models (3rd ed.). Los Angeles: Sage Publications. Gordon, R. A. (2015). Regression Analysis for the Social Sciences. New York and London: Routledge. And the original article: Akaike, H. (1998). Information Theory and an Extension of the Maximum Likelihood Principle. In E. Parzen, K. Tanabe, & G. Kitagawa (Eds.), Selected Papers of Hirotogu Akaike (pp. 199–215). New York: Springer.
How can I apply Akaike Information Criterion and calculate it for Linear Regression? A simple formula for the calculation of the AIC in the OLS framework (since you say linear regression) can be found in Gordon (2015, p. 201): $$\text{AIC} = n *\ln\Big(\frac{SSE}{n}\Big)+2k $$ Where S
44,280
Distribution of 2X - Y when X and Y are known
For two variables $X$ and $Y$, the variance of $aX-bY$ is: $$Var(aX-bY)=a^2Var(X)+b^2Var(Y)-2ab·Cov(X,Y)$$ Where $Cov(X,Y)$ is the covariance between $X$ and $Y$. (source) Usually the problem statement should say whether the variables $X$ and $Y$ are dependent or independent. Since this one apparently doesn't, I'm taking a guess and claiming independence—only because that matches the expected problem answer: first, the linear combination of two independent Normal random variables is a Normal random variable; Second, the covariance between two independent variables is zero. So: $$\begin{align}Var(2X-Y)&=2^2Var(X)+1^2Var(Y)-2ab·Cov(X,Y)\\ &=4 · Var(X)+Var(Y)-0\\ &=4·4+4\\ &=20\end{align}$$
Distribution of 2X - Y when X and Y are known
For two variables $X$ and $Y$, the variance of $aX-bY$ is: $$Var(aX-bY)=a^2Var(X)+b^2Var(Y)-2ab·Cov(X,Y)$$ Where $Cov(X,Y)$ is the covariance between $X$ and $Y$. (source) Usually the problem statemen
Distribution of 2X - Y when X and Y are known For two variables $X$ and $Y$, the variance of $aX-bY$ is: $$Var(aX-bY)=a^2Var(X)+b^2Var(Y)-2ab·Cov(X,Y)$$ Where $Cov(X,Y)$ is the covariance between $X$ and $Y$. (source) Usually the problem statement should say whether the variables $X$ and $Y$ are dependent or independent. Since this one apparently doesn't, I'm taking a guess and claiming independence—only because that matches the expected problem answer: first, the linear combination of two independent Normal random variables is a Normal random variable; Second, the covariance between two independent variables is zero. So: $$\begin{align}Var(2X-Y)&=2^2Var(X)+1^2Var(Y)-2ab·Cov(X,Y)\\ &=4 · Var(X)+Var(Y)-0\\ &=4·4+4\\ &=20\end{align}$$
Distribution of 2X - Y when X and Y are known For two variables $X$ and $Y$, the variance of $aX-bY$ is: $$Var(aX-bY)=a^2Var(X)+b^2Var(Y)-2ab·Cov(X,Y)$$ Where $Cov(X,Y)$ is the covariance between $X$ and $Y$. (source) Usually the problem statemen
44,281
Distribution of 2X - Y when X and Y are known
There are a few important results that are required here. Based on the provided answer, I think an assumption of the question was that $X$ and $Y$ are independent random variables. Let's try and start by proving an important result $$X\sim N(\mu,\sigma^{2})\Leftrightarrow aX\sim N(a\mu,a^{2}\sigma^{2})$$ We can do this many ways, but let's use the moment generating function of the normal distribution. Let $$M_{X}(t)=\mathbb{E}[e^{tX}]=e^{\mu t+\tfrac{1}{2}\sigma^{2}t^{2}}$$ and $$X\sim N(\mu,\sigma^{2})$$ So, $$M_{aX}(t)=\mathbb{E}[e^{atX}]=e^{a\mu t+\tfrac{1}{2}a^{2}\sigma^{2}t^{2}}$$ and $$aX\sim N(a\mu,a^{2}\sigma^{2})$$ Another important result is the sum of two independent normal random variables. If $$X\sim N(\mu_{x},\sigma^{2}_{x})$$ and $$Y\sim N(\mu_{y},\sigma^{2}_{y})$$ then $$X+Y\sim N(\mu_{x}+\mu_{y},\sigma_{x}^{2}+\sigma_{y}^{2})$$ Once again we can prove this using the moment generating function: $$\begin{align} M_{X+Y}(t)&=\mathbb{E}[e^{X+Y}]\\ &\overset{*}{=}\mathbb{E}[e^{X}]\mathbb{E}[e^{Y}]\\ &=e^{\mu_{x} t+\tfrac{1}{2}\sigma_{x}^{2}t^{2}}e^{\mu_{y} t+\tfrac{1}{2}\sigma_{y}^{2}t^{2}}\\ &=e^{(\mu_{x}+\mu_{y})t+\tfrac{1}{2}(\sigma_{x}^{2}+\sigma_{y}^{2})t^{2}} \end{align}$$ So $$X+Y\sim N(\mu_{x}+\mu_{y},\sigma_{x}^{2}+\sigma_{y}^{2})$$ $^{*}$Due to independence between $X$ and $Y$.
Distribution of 2X - Y when X and Y are known
There are a few important results that are required here. Based on the provided answer, I think an assumption of the question was that $X$ and $Y$ are independent random variables. Let's try and start
Distribution of 2X - Y when X and Y are known There are a few important results that are required here. Based on the provided answer, I think an assumption of the question was that $X$ and $Y$ are independent random variables. Let's try and start by proving an important result $$X\sim N(\mu,\sigma^{2})\Leftrightarrow aX\sim N(a\mu,a^{2}\sigma^{2})$$ We can do this many ways, but let's use the moment generating function of the normal distribution. Let $$M_{X}(t)=\mathbb{E}[e^{tX}]=e^{\mu t+\tfrac{1}{2}\sigma^{2}t^{2}}$$ and $$X\sim N(\mu,\sigma^{2})$$ So, $$M_{aX}(t)=\mathbb{E}[e^{atX}]=e^{a\mu t+\tfrac{1}{2}a^{2}\sigma^{2}t^{2}}$$ and $$aX\sim N(a\mu,a^{2}\sigma^{2})$$ Another important result is the sum of two independent normal random variables. If $$X\sim N(\mu_{x},\sigma^{2}_{x})$$ and $$Y\sim N(\mu_{y},\sigma^{2}_{y})$$ then $$X+Y\sim N(\mu_{x}+\mu_{y},\sigma_{x}^{2}+\sigma_{y}^{2})$$ Once again we can prove this using the moment generating function: $$\begin{align} M_{X+Y}(t)&=\mathbb{E}[e^{X+Y}]\\ &\overset{*}{=}\mathbb{E}[e^{X}]\mathbb{E}[e^{Y}]\\ &=e^{\mu_{x} t+\tfrac{1}{2}\sigma_{x}^{2}t^{2}}e^{\mu_{y} t+\tfrac{1}{2}\sigma_{y}^{2}t^{2}}\\ &=e^{(\mu_{x}+\mu_{y})t+\tfrac{1}{2}(\sigma_{x}^{2}+\sigma_{y}^{2})t^{2}} \end{align}$$ So $$X+Y\sim N(\mu_{x}+\mu_{y},\sigma_{x}^{2}+\sigma_{y}^{2})$$ $^{*}$Due to independence between $X$ and $Y$.
Distribution of 2X - Y when X and Y are known There are a few important results that are required here. Based on the provided answer, I think an assumption of the question was that $X$ and $Y$ are independent random variables. Let's try and start
44,282
stratification in cox model
In a Cox model, stratification allows for as many different hazard functions as there are strata. Beta coefficients (hazard ratios) optimized for all strata are then fitted. In your example, the model coxph(Surv(futime, fustat) ~ age + strata(rx) will output a hazard ratio for age in the presence of two (or more) hazards intrinsic to the levels of rx. If rx violated the proportional hazards assumption, for example, stratifying may help meet the PH assumption and provide more valid estimates for age. The effect of rx is not explicitly provided as a hazard ratio. Likelihood estimates for the model can be used to assess whether stratification by rx improved the model fit. coxph(Surv(futime, fustat) ~ age will output a hazard ratio for age only, assuming that the hazard for different levels of rx are the same. In this model, the effect of rx is not explicitly modeled. The model coxph(Surv(futime, fustat) ~ age + rx may be useful to consider. This model would provide estimates of the HR for age and rx with both present in the model ("adjusted for one another"). This would be different from coxph(Surv(futime, fustat) ~ age + str(rx) in that the unstratified model provides estimation of effect for both age and rx using a single underlying hazard.
stratification in cox model
In a Cox model, stratification allows for as many different hazard functions as there are strata. Beta coefficients (hazard ratios) optimized for all strata are then fitted. In your example, the model
stratification in cox model In a Cox model, stratification allows for as many different hazard functions as there are strata. Beta coefficients (hazard ratios) optimized for all strata are then fitted. In your example, the model coxph(Surv(futime, fustat) ~ age + strata(rx) will output a hazard ratio for age in the presence of two (or more) hazards intrinsic to the levels of rx. If rx violated the proportional hazards assumption, for example, stratifying may help meet the PH assumption and provide more valid estimates for age. The effect of rx is not explicitly provided as a hazard ratio. Likelihood estimates for the model can be used to assess whether stratification by rx improved the model fit. coxph(Surv(futime, fustat) ~ age will output a hazard ratio for age only, assuming that the hazard for different levels of rx are the same. In this model, the effect of rx is not explicitly modeled. The model coxph(Surv(futime, fustat) ~ age + rx may be useful to consider. This model would provide estimates of the HR for age and rx with both present in the model ("adjusted for one another"). This would be different from coxph(Surv(futime, fustat) ~ age + str(rx) in that the unstratified model provides estimation of effect for both age and rx using a single underlying hazard.
stratification in cox model In a Cox model, stratification allows for as many different hazard functions as there are strata. Beta coefficients (hazard ratios) optimized for all strata are then fitted. In your example, the model
44,283
stratification in cox model
In addition to the good answer from Todd B, here's a process you can follow, and some more of the background math. A reasonable process to follow Fit a Cox model (fit.unstrat) with all of the covariates and no stratifying variables. Use cox.zph(fit.unstrat) to check for violations of the proportional hazards assumption. If you see e.g. rx has p<0.05, then rx violates the proportional hazards assumption and should not be included as a covariate in the Cox model. A reasonable follow-up is to try changing it to a stratifying variable, e.g., fit.strat <- update(fit.unstrat, . ~ . - rx + strata(rx)). Next, it's appropriate to evaluate whether multiple models improve over the stratified model. The stratified Cox model allows the two rx groups to have different baseline hazards / baseline survivals, but it still only calculates a single effect $\beta_\text{age}$ of age on survival time. You can think of this as being the mean effect of age averaged across both rx groups. This raises a question: do you get a statistically significantly better fit when you allow the two rx groups to have different covariate effects ($\beta_\text{age, rx=2}$ and $\beta_\text{age, rx=1}$)? To answer this question, you: fit the stratified model, fit two separate Cox models for datasets subsetted by rx, and compare them in a likelihood ratio test, where the p-value is $P\left(\chi^2_{(k-1)(q)}\right)>\ell_\text{stratified model} - \sum \ell_\text{unstratified models}$, with $k$ being the number of stratifying groups (just two here--rx=1 and rx=2), $q$ being the number of covariates (just 1 here--$z_\text{age}$), and $\ell$ is a model's log-likelihood. Here's some sample code for the likelihood ratio tests. In this example (pretending rx violates the proportional hazards assumption), we wouldn't choose the multiple models, because while they improve the log likelihood, it's not a statistically significant improvement in the fit (p=0.1575): library(survival) fit.strat <- coxph(Surv(futime, fustat) ~ age + strata(rx), data=ovarian) fit.grp1 <- coxph(Surv(futime, fustat) ~ age, subset=(rx==1), data=ovarian) fit.grp2 <- coxph(Surv(futime, fustat) ~ age, subset=(rx==2), data=ovarian) LL.strat <- fit.strat$loglik[2] LL.unstrat <- fit.grp1$loglik[2] + fit.grp2$loglik[2] X2 <- -2*(LL.strat - LL.unstrat) n_groups <- length( unique(ovarian$rx) ) n_params <- length( fit.strat$coef ) p_val <- 1 - pchisq(X2, df=(n_groups-1)*n_params) Background math Standard Cox proportional hazards model: $$h(t|Z) = h_0 \exp(\beta_\text{age}Z_\text{age} + \beta_\text{rx}Z_\text{rx})$$ fit.unstrat <- coxph(Surv(futime, fustat) ~ age + rx, data=ovarian) The quantity $h_0$ is called the baseline hazard. It corresponds with the baseline survival, which is the survival of the reference group whose covariates are all equal to 0. For a Cox model, the baseline hazard is estimated from the data non-parametrically (without assuming any distribution). The equation above implies: (hazard for rx==2 group)/(hazard for rx==1 group) is a constant. In other words, group 2's hazard is always higher/lower than group 1's hazard by a constant factor. The two rx groups have the same baseline hazard and baseline survival. Stratified Cox proportional hazards model (you're actually fitting two equations that share a single $\beta_\text{age}$): $$h_\text{rx=2}(t|Z) = h_{0,\text{rx=2}} \exp(\beta_\text{age}Z_\text{age}) \\ h_\text{rx=1}(t|Z) = h_{0,\text{rx=1}} \exp(\beta_\text{age}Z_\text{age})$$ fit.strat <- coxph(Surv(futime, fustat) ~ age + strata(rx), data=ovarian) These equations imply: The two rx groups have different baseline hazards / baseline survivals. The two rx groups share a single factor, $\exp(\beta_\text{age})$, by which the hazard is always higher/lower for a 1-unit increase in age. In other words, we're specifying that both rx groups have the same $\beta_\text{age}$. Multiple models (this is just a term I'm making up): $$h_\text{rx=2}(t|Z) = h_{0,\text{rx=2}} \exp(\beta_\text{age, rx=2}Z_\text{age}) \\ h_\text{rx=1}(t|Z) = h_{0,\text{rx=1}} \exp(\beta_\text{age, rx=1}Z_\text{age})$$ fit.grp1 <- coxph(Surv(futime, fustat) ~ age, subset=(rx==1), data=ovarian) fit.grp2 <- coxph(Surv(futime, fustat) ~ age, subset=(rx==2), data=ovarian) Short note about time-dependent covariates In addition to fitting a stratified model, another typical way to remediate a violation of the proportional hazards assumption is to (1) convert the violating variable into a time-dependent variable, and then (2) fit a new Cox PH model and check if the time-dependent covariate satisfies the PH assumption. Time-dependent covariates are an entirely different topic, but they can get invoked for the same reason as a stratified Cox model. Picking between these two often depends on context. If you think the two rx groups truly have different baseline survivals, then a stratified model makes sense. If there's a time component to rx (e.g., the data also contain a variable indicating how much time passed before they started treatment, or we think rx might have a cumulative effect such that the treatment only provides a benefit after some amount of time has passed), then a time-dependent variable might make more sense.
stratification in cox model
In addition to the good answer from Todd B, here's a process you can follow, and some more of the background math. A reasonable process to follow Fit a Cox model (fit.unstrat) with all of the covaria
stratification in cox model In addition to the good answer from Todd B, here's a process you can follow, and some more of the background math. A reasonable process to follow Fit a Cox model (fit.unstrat) with all of the covariates and no stratifying variables. Use cox.zph(fit.unstrat) to check for violations of the proportional hazards assumption. If you see e.g. rx has p<0.05, then rx violates the proportional hazards assumption and should not be included as a covariate in the Cox model. A reasonable follow-up is to try changing it to a stratifying variable, e.g., fit.strat <- update(fit.unstrat, . ~ . - rx + strata(rx)). Next, it's appropriate to evaluate whether multiple models improve over the stratified model. The stratified Cox model allows the two rx groups to have different baseline hazards / baseline survivals, but it still only calculates a single effect $\beta_\text{age}$ of age on survival time. You can think of this as being the mean effect of age averaged across both rx groups. This raises a question: do you get a statistically significantly better fit when you allow the two rx groups to have different covariate effects ($\beta_\text{age, rx=2}$ and $\beta_\text{age, rx=1}$)? To answer this question, you: fit the stratified model, fit two separate Cox models for datasets subsetted by rx, and compare them in a likelihood ratio test, where the p-value is $P\left(\chi^2_{(k-1)(q)}\right)>\ell_\text{stratified model} - \sum \ell_\text{unstratified models}$, with $k$ being the number of stratifying groups (just two here--rx=1 and rx=2), $q$ being the number of covariates (just 1 here--$z_\text{age}$), and $\ell$ is a model's log-likelihood. Here's some sample code for the likelihood ratio tests. In this example (pretending rx violates the proportional hazards assumption), we wouldn't choose the multiple models, because while they improve the log likelihood, it's not a statistically significant improvement in the fit (p=0.1575): library(survival) fit.strat <- coxph(Surv(futime, fustat) ~ age + strata(rx), data=ovarian) fit.grp1 <- coxph(Surv(futime, fustat) ~ age, subset=(rx==1), data=ovarian) fit.grp2 <- coxph(Surv(futime, fustat) ~ age, subset=(rx==2), data=ovarian) LL.strat <- fit.strat$loglik[2] LL.unstrat <- fit.grp1$loglik[2] + fit.grp2$loglik[2] X2 <- -2*(LL.strat - LL.unstrat) n_groups <- length( unique(ovarian$rx) ) n_params <- length( fit.strat$coef ) p_val <- 1 - pchisq(X2, df=(n_groups-1)*n_params) Background math Standard Cox proportional hazards model: $$h(t|Z) = h_0 \exp(\beta_\text{age}Z_\text{age} + \beta_\text{rx}Z_\text{rx})$$ fit.unstrat <- coxph(Surv(futime, fustat) ~ age + rx, data=ovarian) The quantity $h_0$ is called the baseline hazard. It corresponds with the baseline survival, which is the survival of the reference group whose covariates are all equal to 0. For a Cox model, the baseline hazard is estimated from the data non-parametrically (without assuming any distribution). The equation above implies: (hazard for rx==2 group)/(hazard for rx==1 group) is a constant. In other words, group 2's hazard is always higher/lower than group 1's hazard by a constant factor. The two rx groups have the same baseline hazard and baseline survival. Stratified Cox proportional hazards model (you're actually fitting two equations that share a single $\beta_\text{age}$): $$h_\text{rx=2}(t|Z) = h_{0,\text{rx=2}} \exp(\beta_\text{age}Z_\text{age}) \\ h_\text{rx=1}(t|Z) = h_{0,\text{rx=1}} \exp(\beta_\text{age}Z_\text{age})$$ fit.strat <- coxph(Surv(futime, fustat) ~ age + strata(rx), data=ovarian) These equations imply: The two rx groups have different baseline hazards / baseline survivals. The two rx groups share a single factor, $\exp(\beta_\text{age})$, by which the hazard is always higher/lower for a 1-unit increase in age. In other words, we're specifying that both rx groups have the same $\beta_\text{age}$. Multiple models (this is just a term I'm making up): $$h_\text{rx=2}(t|Z) = h_{0,\text{rx=2}} \exp(\beta_\text{age, rx=2}Z_\text{age}) \\ h_\text{rx=1}(t|Z) = h_{0,\text{rx=1}} \exp(\beta_\text{age, rx=1}Z_\text{age})$$ fit.grp1 <- coxph(Surv(futime, fustat) ~ age, subset=(rx==1), data=ovarian) fit.grp2 <- coxph(Surv(futime, fustat) ~ age, subset=(rx==2), data=ovarian) Short note about time-dependent covariates In addition to fitting a stratified model, another typical way to remediate a violation of the proportional hazards assumption is to (1) convert the violating variable into a time-dependent variable, and then (2) fit a new Cox PH model and check if the time-dependent covariate satisfies the PH assumption. Time-dependent covariates are an entirely different topic, but they can get invoked for the same reason as a stratified Cox model. Picking between these two often depends on context. If you think the two rx groups truly have different baseline survivals, then a stratified model makes sense. If there's a time component to rx (e.g., the data also contain a variable indicating how much time passed before they started treatment, or we think rx might have a cumulative effect such that the treatment only provides a benefit after some amount of time has passed), then a time-dependent variable might make more sense.
stratification in cox model In addition to the good answer from Todd B, here's a process you can follow, and some more of the background math. A reasonable process to follow Fit a Cox model (fit.unstrat) with all of the covaria
44,284
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$
No. First, probability is bounded in $[0, 1]$, so it cannot be infinite. Notice that there are two cases where probability can be equal to zero: When you are dealing with empty set $\Pr(\varnothing)=0$. So for example, if you ask "what is the probability that person being -31 years old dies in a car crash?", then it is impossible to answer such question since negative age is impossibility, so the answer for that question is undefined, and basically the question does not make sense. This was noted by  Kolmogorov the concept of a conditional probability with regard to an isolated hypothesis whose probability equals 0 is inadmissible On another hand, as noted by Dilip Sarwate in the comment to this thread and in the following answer by 40 votes, we often want to condition on zero-probability events in case of continuous random variables (where $\Pr(X=x)=0$ for all $x$'s) by approximating it using limits, i.e. by conditioning on probability densities. Check the referred Probability, conditional on a zero probability event thread on math.stackexchange.com that describes it in greater detail.
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$
No. First, probability is bounded in $[0, 1]$, so it cannot be infinite. Notice that there are two cases where probability can be equal to zero: When you are dealing with empty set $\Pr(\varnothing)=
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$ No. First, probability is bounded in $[0, 1]$, so it cannot be infinite. Notice that there are two cases where probability can be equal to zero: When you are dealing with empty set $\Pr(\varnothing)=0$. So for example, if you ask "what is the probability that person being -31 years old dies in a car crash?", then it is impossible to answer such question since negative age is impossibility, so the answer for that question is undefined, and basically the question does not make sense. This was noted by  Kolmogorov the concept of a conditional probability with regard to an isolated hypothesis whose probability equals 0 is inadmissible On another hand, as noted by Dilip Sarwate in the comment to this thread and in the following answer by 40 votes, we often want to condition on zero-probability events in case of continuous random variables (where $\Pr(X=x)=0$ for all $x$'s) by approximating it using limits, i.e. by conditioning on probability densities. Check the referred Probability, conditional on a zero probability event thread on math.stackexchange.com that describes it in greater detail.
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$ No. First, probability is bounded in $[0, 1]$, so it cannot be infinite. Notice that there are two cases where probability can be equal to zero: When you are dealing with empty set $\Pr(\varnothing)=
44,285
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$
No (no such thing as infinite probability: a certain event has probability 1). In fact if it is a probability of an event (and not of a continuous random variable) then it is an ill-posed problem: if $P(A)=0$, what is the probability of $B$ given that $A$ happened? $P(B|A)=\frac{P(B\cap A)}{P(A)}=\frac{0}{0}$ So I think it should just be considered undetermined. (Note that the definition of conditional probability applies only only when the probability of the conditioning event is non-zero, $P(A)\ne0$.) It is different if you are dealing with the probability of a continuous random variable assuming a particular value. See the comments to this question (which has already been referred to by the other answers).
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$
No (no such thing as infinite probability: a certain event has probability 1). In fact if it is a probability of an event (and not of a continuous random variable) then it is an ill-posed problem: if
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$ No (no such thing as infinite probability: a certain event has probability 1). In fact if it is a probability of an event (and not of a continuous random variable) then it is an ill-posed problem: if $P(A)=0$, what is the probability of $B$ given that $A$ happened? $P(B|A)=\frac{P(B\cap A)}{P(A)}=\frac{0}{0}$ So I think it should just be considered undetermined. (Note that the definition of conditional probability applies only only when the probability of the conditioning event is non-zero, $P(A)\ne0$.) It is different if you are dealing with the probability of a continuous random variable assuming a particular value. See the comments to this question (which has already been referred to by the other answers).
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$ No (no such thing as infinite probability: a certain event has probability 1). In fact if it is a probability of an event (and not of a continuous random variable) then it is an ill-posed problem: if
44,286
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$
As far as I know (Stochastic lecture and quick wikipedia lookup), the conditional probability P(B|A) is not defined for P(A)=0. (rule of Bayes) where A and B are events and P(B) ≠ 0. So I would say no, not valid. But if P(A) = 0 then the variables are independent anyways..
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$
As far as I know (Stochastic lecture and quick wikipedia lookup), the conditional probability P(B|A) is not defined for P(A)=0. (rule of Bayes) where A and B are events and P(B) ≠ 0. So I would say
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$ As far as I know (Stochastic lecture and quick wikipedia lookup), the conditional probability P(B|A) is not defined for P(A)=0. (rule of Bayes) where A and B are events and P(B) ≠ 0. So I would say no, not valid. But if P(A) = 0 then the variables are independent anyways..
How to interpret $\mathbb{P}(B|A)$ when $\mathbb{P}(A) = 0$ As far as I know (Stochastic lecture and quick wikipedia lookup), the conditional probability P(B|A) is not defined for P(A)=0. (rule of Bayes) where A and B are events and P(B) ≠ 0. So I would say
44,287
general solution sum of two uniform random variables aY+bX=Z?
If we have a variable $X\sim U(0,1)$ and multiply it by $a$, then $aX\sim U(0,a)$. Assume that we're dealing with independent continuous uniform on $(0,a)$ and $(0,b)$ respectively (with $a<b$) (This assumption is not restrictive since we can obtain the general case from this easily.) Then the joint density is $\frac{1}{ab} I_{(0,a)}\times I_{(0,b)}$. Since the bivariate density is constant where it's non-zero, we can just draw it "looking from above" by marking the boundary of that non-zero region. ... and so by elementary geometric argument (along the lines of (i) recognize that density increases linearly as the sum, $z$ goes from $0$ to $a$, stays constant until $b$ and then decreases linearly to $a+b$, and (ii) that the height in the middle section must be $1/b$ to get unit area, then (iii) the equations of the three non-zero sections follow immediately by inspection), the density of the convolution is $f(z) = \begin{cases} 0 & z\leq 0\\ z/ab & 0<z<a \\ 1/b & a\leq z<b \\ (a+b-z)/ab & b\leq z<a+b \\ 0 & z\geq a+b \end{cases}$ [While formal integration will obviously work, it's somewhat quicker - for me at least - to proceed by something like the above reasoning, where one simply draws the density and then writes the result down immediately.] The general case: Imagine instead we had independent $U(c,a+c)$ and $U(d,d+b)$. Then the above density would simply be shifted right by $c+d$.
general solution sum of two uniform random variables aY+bX=Z?
If we have a variable $X\sim U(0,1)$ and multiply it by $a$, then $aX\sim U(0,a)$. Assume that we're dealing with independent continuous uniform on $(0,a)$ and $(0,b)$ respectively (with $a<b$) (This
general solution sum of two uniform random variables aY+bX=Z? If we have a variable $X\sim U(0,1)$ and multiply it by $a$, then $aX\sim U(0,a)$. Assume that we're dealing with independent continuous uniform on $(0,a)$ and $(0,b)$ respectively (with $a<b$) (This assumption is not restrictive since we can obtain the general case from this easily.) Then the joint density is $\frac{1}{ab} I_{(0,a)}\times I_{(0,b)}$. Since the bivariate density is constant where it's non-zero, we can just draw it "looking from above" by marking the boundary of that non-zero region. ... and so by elementary geometric argument (along the lines of (i) recognize that density increases linearly as the sum, $z$ goes from $0$ to $a$, stays constant until $b$ and then decreases linearly to $a+b$, and (ii) that the height in the middle section must be $1/b$ to get unit area, then (iii) the equations of the three non-zero sections follow immediately by inspection), the density of the convolution is $f(z) = \begin{cases} 0 & z\leq 0\\ z/ab & 0<z<a \\ 1/b & a\leq z<b \\ (a+b-z)/ab & b\leq z<a+b \\ 0 & z\geq a+b \end{cases}$ [While formal integration will obviously work, it's somewhat quicker - for me at least - to proceed by something like the above reasoning, where one simply draws the density and then writes the result down immediately.] The general case: Imagine instead we had independent $U(c,a+c)$ and $U(d,d+b)$. Then the above density would simply be shifted right by $c+d$.
general solution sum of two uniform random variables aY+bX=Z? If we have a variable $X\sim U(0,1)$ and multiply it by $a$, then $aX\sim U(0,a)$. Assume that we're dealing with independent continuous uniform on $(0,a)$ and $(0,b)$ respectively (with $a<b$) (This
44,288
general solution sum of two uniform random variables aY+bX=Z?
Define $Y'=aY$ and $X'=bX$, find their distribution, and you are back to the problem you know how to solve: $Y'+X'=Z$ (convolution).
general solution sum of two uniform random variables aY+bX=Z?
Define $Y'=aY$ and $X'=bX$, find their distribution, and you are back to the problem you know how to solve: $Y'+X'=Z$ (convolution).
general solution sum of two uniform random variables aY+bX=Z? Define $Y'=aY$ and $X'=bX$, find their distribution, and you are back to the problem you know how to solve: $Y'+X'=Z$ (convolution).
general solution sum of two uniform random variables aY+bX=Z? Define $Y'=aY$ and $X'=bX$, find their distribution, and you are back to the problem you know how to solve: $Y'+X'=Z$ (convolution).
44,289
Linear Transformation of Gaussian Random Variable
I deprecate your dreadful notation, it will not help you achieve any kind of rigor at all. If $\mathbf X$ is a (jointly continuous) vector random variable with density function $f_{\mathbf X}({\mathbf x})$, then with $\mathbf G$ being an invertible matrix, the density function of $\mathbf{Y} =\mathbf{XG}$ is $$f_{\mathbf Y}({\mathbf y}) = \frac{f_{\mathbf X}\left({\mathbf y\mathbf G^{-1}}\right)}{\vert\det{\mathbf G}\vert}.\tag{1}$$ (Note that I am using row vectors instead of the column vectors that have been claimed to be more common usage in statistical circles). This is a general result that holds regardless of whether multivariate normality is assumed or not. Also, the mean vector $E[\mathbf Y]$ of $\mathbf Y$ is related to the mean vector $E[\mathbf X]$ as $$E[\mathbf Y] = E[\mathbf{XG}] = E[\mathbf{X}]\mathbf{G}\tag{2}$$ while the covariance matrix is \begin{align}\Sigma_{\mathbf Y} &= E\left[\left(\mathbf Y - E[\mathbf Y]\right)^T\left(\mathbf Y - E[\mathbf Y]\right)\right]\\ &= E\left[\left(\mathbf {XG} - E[\mathbf X]\mathbf G\right)^T\left(\mathbf {XG} - E[\mathbf X]\mathbf G\right)\right]\\ &= \mathbf G^T E\left[\left(\mathbf {X} - E[\mathbf X]\right)^T \left(\mathbf {X} - E[\mathbf X]\right)\right]\mathbf G\\ &= \mathbf G^T\Sigma_{\mathbf X}\mathbf G. \tag{3} \end{align} For the special case of $\mathbf X$ having a $n$-variate normal distribution and the covariance matrix $\Sigma_{\mathbf X}$ being a strictly positive invertible $n\times n$ matrix, the density function $f_{\mathbf X}({\mathbf x})$ is of the form $$f_{\mathbf X}({\mathbf x}) = \frac{1}{(2\pi)^{n/2}\sqrt{\det\left(\Sigma_{\mathbf X}\right)}} \exp\left[-\frac 12 \left(\mathbf {x} - E[\mathbf X]\right) \Sigma_{\mathbf X}^{-1}\left(\mathbf {x} - E[\mathbf X]\right)^T\right] \tag{4}$$ and so from $(1)$ we get \begin{align} f_{\mathbf Y}({\mathbf y}) &= \frac{f_{\mathbf X}\left({\mathbf y\mathbf G^{-1}}\right)}{\vert\det{\mathbf G}\vert}\\ &= \frac{1}{(2\pi)^{n/2}\sqrt{\det\left(\Sigma_{\mathbf X}\right)} \vert\det{\mathbf G}\vert} \exp\left[-\frac 12 \left(\mathbf{yG}^{-1} - E[\mathbf X]\right) \Sigma_{\mathbf X}^{-1}\left(\mathbf{yG}^{-1} - E[\mathbf X]\right)^T\right]\\ &= \frac{1}{(2\pi)^{n/2}\sqrt{\det\left(\Sigma_{\mathbf X}\right)} \vert\det{\mathbf G}\vert^{1/2}\vert\det{\mathbf G}^T\vert^{1/2}} \exp\left[-\frac 12 \left(\mathbf{yG}^{-1} - E[\mathbf X]\right) \Sigma_{\mathbf X}^{-1}\left(\mathbf{yG}^{-1} - E[\mathbf X]\right)^T\right]\\ &= \frac{1}{(2\pi)^{n/2}\sqrt{\left|\det\left(\mathbf G^T\Sigma_{\mathbf X}\mathbf G\right)\right|}} \exp\left[-\frac 12 \left(\mathbf{y} - E[\mathbf X]\mathbf G\right) \mathbf G^{-1} \Sigma_{\mathbf X}^{-1}\left(\left(\mathbf{y} - E[\mathbf X]\mathbf G\right)\mathbf G^{-1}\right)^T\right]\\ &= \frac{1}{(2\pi)^{n/2}\sqrt{\left|\det\left(\mathbf G^T\Sigma_{\mathbf X}\mathbf G\right)\right|}} \exp\left[-\frac 12 \left(\mathbf{y} - E[\mathbf Y]\right) \mathbf G^{-1} \Sigma_{\mathbf X}^{-1}\left(\mathbf G^{-1}\right)^T\left(\mathbf{y} - E[\mathbf Y]\right)^T\right]\\ &= \frac{1}{(2\pi)^{n/2}\sqrt{\left|\det\Sigma_{\mathbf Y}\right|}} \exp\left[-\frac 12 \left(\mathbf{y} - E[\mathbf Y]\right) \Sigma_{\mathbf Y}^{-1}\left(\mathbf{y} - E[\mathbf Y]\right)^T\right] \end{align} which shows that $\mathbf Y = \mathbf{XG}$ also has a $n$-variate normal density with mean vector and covariance matrix as given in (2) and (3).
Linear Transformation of Gaussian Random Variable
I deprecate your dreadful notation, it will not help you achieve any kind of rigor at all. If $\mathbf X$ is a (jointly continuous) vector random variable with density function $f_{\mathbf X}({\mathbf
Linear Transformation of Gaussian Random Variable I deprecate your dreadful notation, it will not help you achieve any kind of rigor at all. If $\mathbf X$ is a (jointly continuous) vector random variable with density function $f_{\mathbf X}({\mathbf x})$, then with $\mathbf G$ being an invertible matrix, the density function of $\mathbf{Y} =\mathbf{XG}$ is $$f_{\mathbf Y}({\mathbf y}) = \frac{f_{\mathbf X}\left({\mathbf y\mathbf G^{-1}}\right)}{\vert\det{\mathbf G}\vert}.\tag{1}$$ (Note that I am using row vectors instead of the column vectors that have been claimed to be more common usage in statistical circles). This is a general result that holds regardless of whether multivariate normality is assumed or not. Also, the mean vector $E[\mathbf Y]$ of $\mathbf Y$ is related to the mean vector $E[\mathbf X]$ as $$E[\mathbf Y] = E[\mathbf{XG}] = E[\mathbf{X}]\mathbf{G}\tag{2}$$ while the covariance matrix is \begin{align}\Sigma_{\mathbf Y} &= E\left[\left(\mathbf Y - E[\mathbf Y]\right)^T\left(\mathbf Y - E[\mathbf Y]\right)\right]\\ &= E\left[\left(\mathbf {XG} - E[\mathbf X]\mathbf G\right)^T\left(\mathbf {XG} - E[\mathbf X]\mathbf G\right)\right]\\ &= \mathbf G^T E\left[\left(\mathbf {X} - E[\mathbf X]\right)^T \left(\mathbf {X} - E[\mathbf X]\right)\right]\mathbf G\\ &= \mathbf G^T\Sigma_{\mathbf X}\mathbf G. \tag{3} \end{align} For the special case of $\mathbf X$ having a $n$-variate normal distribution and the covariance matrix $\Sigma_{\mathbf X}$ being a strictly positive invertible $n\times n$ matrix, the density function $f_{\mathbf X}({\mathbf x})$ is of the form $$f_{\mathbf X}({\mathbf x}) = \frac{1}{(2\pi)^{n/2}\sqrt{\det\left(\Sigma_{\mathbf X}\right)}} \exp\left[-\frac 12 \left(\mathbf {x} - E[\mathbf X]\right) \Sigma_{\mathbf X}^{-1}\left(\mathbf {x} - E[\mathbf X]\right)^T\right] \tag{4}$$ and so from $(1)$ we get \begin{align} f_{\mathbf Y}({\mathbf y}) &= \frac{f_{\mathbf X}\left({\mathbf y\mathbf G^{-1}}\right)}{\vert\det{\mathbf G}\vert}\\ &= \frac{1}{(2\pi)^{n/2}\sqrt{\det\left(\Sigma_{\mathbf X}\right)} \vert\det{\mathbf G}\vert} \exp\left[-\frac 12 \left(\mathbf{yG}^{-1} - E[\mathbf X]\right) \Sigma_{\mathbf X}^{-1}\left(\mathbf{yG}^{-1} - E[\mathbf X]\right)^T\right]\\ &= \frac{1}{(2\pi)^{n/2}\sqrt{\det\left(\Sigma_{\mathbf X}\right)} \vert\det{\mathbf G}\vert^{1/2}\vert\det{\mathbf G}^T\vert^{1/2}} \exp\left[-\frac 12 \left(\mathbf{yG}^{-1} - E[\mathbf X]\right) \Sigma_{\mathbf X}^{-1}\left(\mathbf{yG}^{-1} - E[\mathbf X]\right)^T\right]\\ &= \frac{1}{(2\pi)^{n/2}\sqrt{\left|\det\left(\mathbf G^T\Sigma_{\mathbf X}\mathbf G\right)\right|}} \exp\left[-\frac 12 \left(\mathbf{y} - E[\mathbf X]\mathbf G\right) \mathbf G^{-1} \Sigma_{\mathbf X}^{-1}\left(\left(\mathbf{y} - E[\mathbf X]\mathbf G\right)\mathbf G^{-1}\right)^T\right]\\ &= \frac{1}{(2\pi)^{n/2}\sqrt{\left|\det\left(\mathbf G^T\Sigma_{\mathbf X}\mathbf G\right)\right|}} \exp\left[-\frac 12 \left(\mathbf{y} - E[\mathbf Y]\right) \mathbf G^{-1} \Sigma_{\mathbf X}^{-1}\left(\mathbf G^{-1}\right)^T\left(\mathbf{y} - E[\mathbf Y]\right)^T\right]\\ &= \frac{1}{(2\pi)^{n/2}\sqrt{\left|\det\Sigma_{\mathbf Y}\right|}} \exp\left[-\frac 12 \left(\mathbf{y} - E[\mathbf Y]\right) \Sigma_{\mathbf Y}^{-1}\left(\mathbf{y} - E[\mathbf Y]\right)^T\right] \end{align} which shows that $\mathbf Y = \mathbf{XG}$ also has a $n$-variate normal density with mean vector and covariance matrix as given in (2) and (3).
Linear Transformation of Gaussian Random Variable I deprecate your dreadful notation, it will not help you achieve any kind of rigor at all. If $\mathbf X$ is a (jointly continuous) vector random variable with density function $f_{\mathbf X}({\mathbf
44,290
Linear Transformation of Gaussian Random Variable
This can be shown very succinctly by using the characteristic function of distributions. Let $\phi_X(t) = E[ \exp(i t ^ \mathsf T X) ]$ be the characteristic function of a random variable $X \in \mathbb R^n$. If $x$ is normally distributed $x \sim \mathcal N(\mu, \Sigma)$, then we have $\phi_x(t) = \exp \Big (i t ^ \mathsf T \mu - \tfrac {1}{2} t ^ \mathsf T \Sigma t \Big )$. If $y = A x + b$, then \begin{align} \phi_y(t) &= E[ \exp \Big(i t ^ \mathsf T (A x + b) \Big) ] \\ &= E[ \exp \Big(i t ^ \mathsf T b \Big) \exp \Big(i t ^ \mathsf T A x \Big) ] \\ &= \exp \Big(i t ^ \mathsf T b \Big) E[ \exp \Big(i (A ^ \mathsf T t) ^ \mathsf T x \Big) ] \\ &= \exp \Big(i t ^ \mathsf T b \Big) \phi_x (A ^ \mathsf T t) \\ &= \exp \Big(i t ^ \mathsf T b \Big) \exp \Big (i (A ^ \mathsf T t) ^ \mathsf T \mu - \tfrac {1}{2} (A ^ \mathsf T t) ^ \mathsf T \Sigma (A ^ \mathsf T t) \Big ) \\ &= \exp \Big (i t ^ \mathsf T (A \mu + b) - \tfrac {1}{2} t ^ \mathsf T A \Sigma A ^ \mathsf T t \Big ) \\ \end{align} Since the characteristic function uniquely defines the distribution, we have $y \sim \mathcal N(A \mu + b, A \Sigma A ^ \mathsf T)$ as wanted.
Linear Transformation of Gaussian Random Variable
This can be shown very succinctly by using the characteristic function of distributions. Let $\phi_X(t) = E[ \exp(i t ^ \mathsf T X) ]$ be the characteristic function of a random variable $X \in \math
Linear Transformation of Gaussian Random Variable This can be shown very succinctly by using the characteristic function of distributions. Let $\phi_X(t) = E[ \exp(i t ^ \mathsf T X) ]$ be the characteristic function of a random variable $X \in \mathbb R^n$. If $x$ is normally distributed $x \sim \mathcal N(\mu, \Sigma)$, then we have $\phi_x(t) = \exp \Big (i t ^ \mathsf T \mu - \tfrac {1}{2} t ^ \mathsf T \Sigma t \Big )$. If $y = A x + b$, then \begin{align} \phi_y(t) &= E[ \exp \Big(i t ^ \mathsf T (A x + b) \Big) ] \\ &= E[ \exp \Big(i t ^ \mathsf T b \Big) \exp \Big(i t ^ \mathsf T A x \Big) ] \\ &= \exp \Big(i t ^ \mathsf T b \Big) E[ \exp \Big(i (A ^ \mathsf T t) ^ \mathsf T x \Big) ] \\ &= \exp \Big(i t ^ \mathsf T b \Big) \phi_x (A ^ \mathsf T t) \\ &= \exp \Big(i t ^ \mathsf T b \Big) \exp \Big (i (A ^ \mathsf T t) ^ \mathsf T \mu - \tfrac {1}{2} (A ^ \mathsf T t) ^ \mathsf T \Sigma (A ^ \mathsf T t) \Big ) \\ &= \exp \Big (i t ^ \mathsf T (A \mu + b) - \tfrac {1}{2} t ^ \mathsf T A \Sigma A ^ \mathsf T t \Big ) \\ \end{align} Since the characteristic function uniquely defines the distribution, we have $y \sim \mathcal N(A \mu + b, A \Sigma A ^ \mathsf T)$ as wanted.
Linear Transformation of Gaussian Random Variable This can be shown very succinctly by using the characteristic function of distributions. Let $\phi_X(t) = E[ \exp(i t ^ \mathsf T X) ]$ be the characteristic function of a random variable $X \in \math
44,291
Intuition for this observation//how restrictive is this assumption?
The OP really seeks the distributions with log-concave density functions -the quotient he differentiates is the reciprocal of the one we examine in order to determine the log-concavity or log-convexity of a function. Specifically: For $f$ to be log-concave, it means that $\ln f$ is concave, for which we require that $$\frac {d^2}{dx^2} \ln f \leq 0 \implies \frac {d}{dx}\left (\frac {f'}{f}\right) \leq 0 \implies f''\cdot f-(f')^2 \leq 0$$ From his part, the OP wants $$\frac {d}{dx} \left (\frac {F'}{F''}\right) \geq 0 \implies \frac {d}{dx} \left (\frac {f}{f'}\right) \geq 0 \implies (f')^2 - f\cdot f'' \geq 0 $$ and upon re-arranging, the OP wants $$ f\cdot f'' - (f')^2 \leq 0$$ which is the condition for log-concavity, not log-convexity. It is the expression of the condition through the use of the reciprocal quotient that may cause some confusion. A good free resource on some of the "named" distributions that have log-concave densities is Mark Bagnoli and Ted Bergstrom. "Log-concave Probability and its Applications" 2004 It focuses on log-concavity but it also contains results on log-convexity. We see that the OP's assertion that "Weibull, normal, log-normal, exponential, gamma" have log-concave densities is not fully correct: for example, the normal and the exponential distribution do have log-concave densities, while Weibull and gamma have also log-concave densities for some of their incarnations, while for others they have log-convex densities. The log-normal has a density that is neither log-concave, nor log-convex. Another resource that examines log-concavity and log-convexity more abstractly and rigorously is An, M. Y. (1998). Logconcavity versus logconvexity: a complete characterization. Journal of Economic theory, 80(2), 350-369.
Intuition for this observation//how restrictive is this assumption?
The OP really seeks the distributions with log-concave density functions -the quotient he differentiates is the reciprocal of the one we examine in order to determine the log-concavity or log-convexit
Intuition for this observation//how restrictive is this assumption? The OP really seeks the distributions with log-concave density functions -the quotient he differentiates is the reciprocal of the one we examine in order to determine the log-concavity or log-convexity of a function. Specifically: For $f$ to be log-concave, it means that $\ln f$ is concave, for which we require that $$\frac {d^2}{dx^2} \ln f \leq 0 \implies \frac {d}{dx}\left (\frac {f'}{f}\right) \leq 0 \implies f''\cdot f-(f')^2 \leq 0$$ From his part, the OP wants $$\frac {d}{dx} \left (\frac {F'}{F''}\right) \geq 0 \implies \frac {d}{dx} \left (\frac {f}{f'}\right) \geq 0 \implies (f')^2 - f\cdot f'' \geq 0 $$ and upon re-arranging, the OP wants $$ f\cdot f'' - (f')^2 \leq 0$$ which is the condition for log-concavity, not log-convexity. It is the expression of the condition through the use of the reciprocal quotient that may cause some confusion. A good free resource on some of the "named" distributions that have log-concave densities is Mark Bagnoli and Ted Bergstrom. "Log-concave Probability and its Applications" 2004 It focuses on log-concavity but it also contains results on log-convexity. We see that the OP's assertion that "Weibull, normal, log-normal, exponential, gamma" have log-concave densities is not fully correct: for example, the normal and the exponential distribution do have log-concave densities, while Weibull and gamma have also log-concave densities for some of their incarnations, while for others they have log-convex densities. The log-normal has a density that is neither log-concave, nor log-convex. Another resource that examines log-concavity and log-convexity more abstractly and rigorously is An, M. Y. (1998). Logconcavity versus logconvexity: a complete characterization. Journal of Economic theory, 80(2), 350-369.
Intuition for this observation//how restrictive is this assumption? The OP really seeks the distributions with log-concave density functions -the quotient he differentiates is the reciprocal of the one we examine in order to determine the log-concavity or log-convexit
44,292
Intuition for this observation//how restrictive is this assumption?
Let $f(x)=F^\prime(x)$. Since $$\frac{d}{dx} \frac{F^\prime(x)}{F^{\prime\prime}(x)} = \frac{d}{dx}\left(1/\frac{f^\prime(x)}{f(x)}\right)= \frac{d}{dx}\left(1/\frac{d}{dx}\log(f(x))\right)=-\frac{\frac{d^2}{dx^2}\log(x)}{{(\cdots)}^2},$$ the positivity of the left hand side assures the negativity of the second derivative of $\log(f)$. A standard Calculus theorem asserts $\log(f)$ is concave (on an open set) provided its second derivative is everywhere negative. That's what "log-concave" means. An important technical condition is that the domain of the function be convex. Convex sets of real numbers are intervals, potentially infinite ones. The "support" of a continuous density function $f$ is the closure of the set of numbers where it is nonzero. By extension, we may also call that set the support of the distribution function $F$. Your functions therefore are all the distribution functions of interval support whose density functions are second-differentiable and log-concave. Why the technicalities about the support? To rule out situations where this local characterization is not a global one. For instance, let $X$ be a random variable with density function equal to $2x$ on the interval $(0,1)$ and zero elsewhere. Consider the distribution function $F$ of an equal mixture of $X$ and $X+2$. Its density is defined, nonzero, and continuously differentiable in $(0,1)\cup(2,3)$ where its log is either $\log(x)$ or $\log(x-2)$. Both are concave functions--but $F$ should not qualify as a log-concave distribution because $f$ itself is obviously not concave and log-concavity is intended to be even stronger than concaveity. Couldn't we not bother with this and just require $F$ to be supported on the entire real line? Sure--but that would rule out interesting and important examples like Gamma distributions.
Intuition for this observation//how restrictive is this assumption?
Let $f(x)=F^\prime(x)$. Since $$\frac{d}{dx} \frac{F^\prime(x)}{F^{\prime\prime}(x)} = \frac{d}{dx}\left(1/\frac{f^\prime(x)}{f(x)}\right)= \frac{d}{dx}\left(1/\frac{d}{dx}\log(f(x))\right)=-\frac{\f
Intuition for this observation//how restrictive is this assumption? Let $f(x)=F^\prime(x)$. Since $$\frac{d}{dx} \frac{F^\prime(x)}{F^{\prime\prime}(x)} = \frac{d}{dx}\left(1/\frac{f^\prime(x)}{f(x)}\right)= \frac{d}{dx}\left(1/\frac{d}{dx}\log(f(x))\right)=-\frac{\frac{d^2}{dx^2}\log(x)}{{(\cdots)}^2},$$ the positivity of the left hand side assures the negativity of the second derivative of $\log(f)$. A standard Calculus theorem asserts $\log(f)$ is concave (on an open set) provided its second derivative is everywhere negative. That's what "log-concave" means. An important technical condition is that the domain of the function be convex. Convex sets of real numbers are intervals, potentially infinite ones. The "support" of a continuous density function $f$ is the closure of the set of numbers where it is nonzero. By extension, we may also call that set the support of the distribution function $F$. Your functions therefore are all the distribution functions of interval support whose density functions are second-differentiable and log-concave. Why the technicalities about the support? To rule out situations where this local characterization is not a global one. For instance, let $X$ be a random variable with density function equal to $2x$ on the interval $(0,1)$ and zero elsewhere. Consider the distribution function $F$ of an equal mixture of $X$ and $X+2$. Its density is defined, nonzero, and continuously differentiable in $(0,1)\cup(2,3)$ where its log is either $\log(x)$ or $\log(x-2)$. Both are concave functions--but $F$ should not qualify as a log-concave distribution because $f$ itself is obviously not concave and log-concavity is intended to be even stronger than concaveity. Couldn't we not bother with this and just require $F$ to be supported on the entire real line? Sure--but that would rule out interesting and important examples like Gamma distributions.
Intuition for this observation//how restrictive is this assumption? Let $f(x)=F^\prime(x)$. Since $$\frac{d}{dx} \frac{F^\prime(x)}{F^{\prime\prime}(x)} = \frac{d}{dx}\left(1/\frac{f^\prime(x)}{f(x)}\right)= \frac{d}{dx}\left(1/\frac{d}{dx}\log(f(x))\right)=-\frac{\f
44,293
Fitted Confidence Intervals Forecast Function R
Presumably you mean prediction intervals rather than confidence intervals. The fitted values are in-sample one-step forecasts. Assuming normally distributed errors, 95% prediction intervals are given by $$\hat{y}_t \pm 1.96 \hat{\sigma}$$ where $\hat\sigma^2$ is the estimated variance of the residuals. Here is an example using R: library(forecast) fit <- auto.arima(Nile) upper <- fitted(fit) + 1.96*sqrt(fit$sigma2) lower <- fitted(fit) - 1.96*sqrt(fit$sigma2) plot(Nile, type="n", ylim=range(lower,upper)) polygon(c(time(Nile),rev(time(Nile))), c(upper,rev(lower)), col=rgb(0,0,0.6,0.2), border=FALSE) lines(Nile) lines(fitted(fit),col='red') out <- (Nile < lower | Nile > upper) points(time(Nile)[out], Nile[out], pch=19)
Fitted Confidence Intervals Forecast Function R
Presumably you mean prediction intervals rather than confidence intervals. The fitted values are in-sample one-step forecasts. Assuming normally distributed errors, 95% prediction intervals are given
Fitted Confidence Intervals Forecast Function R Presumably you mean prediction intervals rather than confidence intervals. The fitted values are in-sample one-step forecasts. Assuming normally distributed errors, 95% prediction intervals are given by $$\hat{y}_t \pm 1.96 \hat{\sigma}$$ where $\hat\sigma^2$ is the estimated variance of the residuals. Here is an example using R: library(forecast) fit <- auto.arima(Nile) upper <- fitted(fit) + 1.96*sqrt(fit$sigma2) lower <- fitted(fit) - 1.96*sqrt(fit$sigma2) plot(Nile, type="n", ylim=range(lower,upper)) polygon(c(time(Nile),rev(time(Nile))), c(upper,rev(lower)), col=rgb(0,0,0.6,0.2), border=FALSE) lines(Nile) lines(fitted(fit),col='red') out <- (Nile < lower | Nile > upper) points(time(Nile)[out], Nile[out], pch=19)
Fitted Confidence Intervals Forecast Function R Presumably you mean prediction intervals rather than confidence intervals. The fitted values are in-sample one-step forecasts. Assuming normally distributed errors, 95% prediction intervals are given
44,294
How to explain degrees of freedom term to a layman? [duplicate]
You get the next 7 days off work, but you use the first day planning the rest of the days, so you have 6 days free. "the number of observations minus the number of necessary relations among these observations." -Walker Degrees of freedom can be very complex though and contrary to popular belief, see this answer for more.
How to explain degrees of freedom term to a layman? [duplicate]
You get the next 7 days off work, but you use the first day planning the rest of the days, so you have 6 days free. "the number of observations minus the number of necessary relations among these obse
How to explain degrees of freedom term to a layman? [duplicate] You get the next 7 days off work, but you use the first day planning the rest of the days, so you have 6 days free. "the number of observations minus the number of necessary relations among these observations." -Walker Degrees of freedom can be very complex though and contrary to popular belief, see this answer for more.
How to explain degrees of freedom term to a layman? [duplicate] You get the next 7 days off work, but you use the first day planning the rest of the days, so you have 6 days free. "the number of observations minus the number of necessary relations among these obse
44,295
How to explain degrees of freedom term to a layman? [duplicate]
Definition for Layman Degrees of freedom is the number of values that are free to vary when the  value of some statistic, like $\bar{X}$ or $\hat{\sigma}^2$, is known. In other words, it is the number of values that need to be known in order to know all of the values. I will provide two examples. The first example is appropriate for a layman with a mathematical mind and the second example is probably not good for a layman but I give it anyway. Example with $\bar{X}$ As a very simple example, consider $\bar{X}$ with a sample size of $n$. If you know the values $X_1, X_2,..., X_{n-1}$ then you also know the value of $X_n$. So, we say that $\bar{X}$ has $n-1$ degrees of freedom. $$X_n = n(\bar{X}) - \sum\limits_{i=1}^{n-1} X_i$$ Example with Simple Linear Regression As a slightly more difficult example, consider the simple linear model $Y_i =\alpha+ \beta x_i + \epsilon_i$ for $i=1,...,n$. Recall the following two identities in linear regression $$e_1 + e_2 + ... + e_n = 0$$ $$x_1e_1 + x_2e_2 + ... + x_ne_n = 0$$ where the residuals $e_i = \hat{Y}_i - Y_i$. Notice, if we know $e_1,..., e_{n-2}$ but $e_{n-1}$ and $e_n$ are unknown then the above identities give us two equations with two unknowns. Since the number of equations and the number of unknowns is the same, we can solve for $e_{n-1}$ and $e_n$. So, knowing the $n-2$ values  $e_1,..., e_{n-2}$ allows us to know all of the values $e_1,...,e_n$ and so the residuals have $n-2$ degrees of freedom. This can be easily generalized to a multiple linear regression situation with $p$ variables if one recalls that $X^Te = 0$.
How to explain degrees of freedom term to a layman? [duplicate]
Definition for Layman Degrees of freedom is the number of values that are free to vary when the  value of some statistic, like $\bar{X}$ or $\hat{\sigma}^2$, is known. In other words, it is the number
How to explain degrees of freedom term to a layman? [duplicate] Definition for Layman Degrees of freedom is the number of values that are free to vary when the  value of some statistic, like $\bar{X}$ or $\hat{\sigma}^2$, is known. In other words, it is the number of values that need to be known in order to know all of the values. I will provide two examples. The first example is appropriate for a layman with a mathematical mind and the second example is probably not good for a layman but I give it anyway. Example with $\bar{X}$ As a very simple example, consider $\bar{X}$ with a sample size of $n$. If you know the values $X_1, X_2,..., X_{n-1}$ then you also know the value of $X_n$. So, we say that $\bar{X}$ has $n-1$ degrees of freedom. $$X_n = n(\bar{X}) - \sum\limits_{i=1}^{n-1} X_i$$ Example with Simple Linear Regression As a slightly more difficult example, consider the simple linear model $Y_i =\alpha+ \beta x_i + \epsilon_i$ for $i=1,...,n$. Recall the following two identities in linear regression $$e_1 + e_2 + ... + e_n = 0$$ $$x_1e_1 + x_2e_2 + ... + x_ne_n = 0$$ where the residuals $e_i = \hat{Y}_i - Y_i$. Notice, if we know $e_1,..., e_{n-2}$ but $e_{n-1}$ and $e_n$ are unknown then the above identities give us two equations with two unknowns. Since the number of equations and the number of unknowns is the same, we can solve for $e_{n-1}$ and $e_n$. So, knowing the $n-2$ values  $e_1,..., e_{n-2}$ allows us to know all of the values $e_1,...,e_n$ and so the residuals have $n-2$ degrees of freedom. This can be easily generalized to a multiple linear regression situation with $p$ variables if one recalls that $X^Te = 0$.
How to explain degrees of freedom term to a layman? [duplicate] Definition for Layman Degrees of freedom is the number of values that are free to vary when the  value of some statistic, like $\bar{X}$ or $\hat{\sigma}^2$, is known. In other words, it is the number
44,296
How to explain degrees of freedom term to a layman? [duplicate]
The Wikipedia article Degrees of freedom (statistics) is pretty good at explaining it (see the first few paragraphs). Imagine you have some system or a black box which behavior is defined by a number of values (or parameters). The concrete values of the parameters set one particular mode of operation. Another set of parameters will define another mode of operation. The catch here is that even for a simple system (say with one parameter only) you can "create" many versions of that parameter (e.g. multiple, added constant etc). Here the degrees of freedom is minimal number of parameters that are independent and are free to vary (under some constraints if any).
How to explain degrees of freedom term to a layman? [duplicate]
The Wikipedia article Degrees of freedom (statistics) is pretty good at explaining it (see the first few paragraphs). Imagine you have some system or a black box which behavior is defined by a number
How to explain degrees of freedom term to a layman? [duplicate] The Wikipedia article Degrees of freedom (statistics) is pretty good at explaining it (see the first few paragraphs). Imagine you have some system or a black box which behavior is defined by a number of values (or parameters). The concrete values of the parameters set one particular mode of operation. Another set of parameters will define another mode of operation. The catch here is that even for a simple system (say with one parameter only) you can "create" many versions of that parameter (e.g. multiple, added constant etc). Here the degrees of freedom is minimal number of parameters that are independent and are free to vary (under some constraints if any).
How to explain degrees of freedom term to a layman? [duplicate] The Wikipedia article Degrees of freedom (statistics) is pretty good at explaining it (see the first few paragraphs). Imagine you have some system or a black box which behavior is defined by a number
44,297
Using years when calculating linear regression?
In principle, it doesn't matter - only the intercept term will be affected. Say that you want to estimate the regression Y = a + bX + e. Remember that the slope coefficient can be calculated as b = Cov(Y, X) / Var(X), and a = Ym - bXm, where Ym and Xm are the sample means of the respective variables. Now, let's add a constant C to the X variable (corresponding to switching the year definition in your example): b = Cov(Y, X + C) / Var(X + C) = [Cov(Y, X) + Cov(Y, C)] / [Var(X) + Var(C)]. Furthermore, Cov(Y, C) = Var(C) = 0, because C is a constant. This gets us back to the same expression for b as before. For the intercept, we get a = Ym - b*(Xm + C). In practice, you can sometimes run into issues when using very large values for a variable. This is because you can run into the limits of your computers level of numerical precision, but in your case, I can't imagine that it would make any difference.
Using years when calculating linear regression?
In principle, it doesn't matter - only the intercept term will be affected. Say that you want to estimate the regression Y = a + bX + e. Remember that the slope coefficient can be calculated as b = Co
Using years when calculating linear regression? In principle, it doesn't matter - only the intercept term will be affected. Say that you want to estimate the regression Y = a + bX + e. Remember that the slope coefficient can be calculated as b = Cov(Y, X) / Var(X), and a = Ym - bXm, where Ym and Xm are the sample means of the respective variables. Now, let's add a constant C to the X variable (corresponding to switching the year definition in your example): b = Cov(Y, X + C) / Var(X + C) = [Cov(Y, X) + Cov(Y, C)] / [Var(X) + Var(C)]. Furthermore, Cov(Y, C) = Var(C) = 0, because C is a constant. This gets us back to the same expression for b as before. For the intercept, we get a = Ym - b*(Xm + C). In practice, you can sometimes run into issues when using very large values for a variable. This is because you can run into the limits of your computers level of numerical precision, but in your case, I can't imagine that it would make any difference.
Using years when calculating linear regression? In principle, it doesn't matter - only the intercept term will be affected. Say that you want to estimate the regression Y = a + bX + e. Remember that the slope coefficient can be calculated as b = Co
44,298
Using years when calculating linear regression?
The second series can be written as the first one minus 2008. Ought it to make a difference to how we think unemployment changes over time when we start counting years from—the birth of Christ or the start of the data series? Look at the least-squares equations & try to work out the effect of subtracting a constant from the predictor. Of the estimated coefficients & the predicted values what will change, & how? Check by performing the regression both ways.
Using years when calculating linear regression?
The second series can be written as the first one minus 2008. Ought it to make a difference to how we think unemployment changes over time when we start counting years from—the birth of Christ or the
Using years when calculating linear regression? The second series can be written as the first one minus 2008. Ought it to make a difference to how we think unemployment changes over time when we start counting years from—the birth of Christ or the start of the data series? Look at the least-squares equations & try to work out the effect of subtracting a constant from the predictor. Of the estimated coefficients & the predicted values what will change, & how? Check by performing the regression both ways.
Using years when calculating linear regression? The second series can be written as the first one minus 2008. Ought it to make a difference to how we think unemployment changes over time when we start counting years from—the birth of Christ or the
44,299
Using years when calculating linear regression?
a) If you're sure (or in this case specifically told) you only need to use year as linear variable (no interactions, no quadratic terms, no other terms), and you only have one timeseries, then in this case it doesn't make any difference (just results in a constant offset). So might as well use year as is. b) In general), if you're looking at an arbitrary unknown modeling problem, where you might well need quadratic, higher-order or nonlinear terms, then you should define a time-index: yearx = year - 2007. We usually define time-index to start at 1, not 0, since many useful functions object to 0, such as log, 1/x etc. (But this is more broad than your example.) c) There's another, more basic reason: if you have multiple timeseries, each with a different start-year (e.g. one series starts in 1996, another in 2008). Then if you want to focus on the relative time lag, and remove hard year numbers from the model coefficients, graphs etc., again compute yearx = year - start_year for each series.
Using years when calculating linear regression?
a) If you're sure (or in this case specifically told) you only need to use year as linear variable (no interactions, no quadratic terms, no other terms), and you only have one timeseries, then in this
Using years when calculating linear regression? a) If you're sure (or in this case specifically told) you only need to use year as linear variable (no interactions, no quadratic terms, no other terms), and you only have one timeseries, then in this case it doesn't make any difference (just results in a constant offset). So might as well use year as is. b) In general), if you're looking at an arbitrary unknown modeling problem, where you might well need quadratic, higher-order or nonlinear terms, then you should define a time-index: yearx = year - 2007. We usually define time-index to start at 1, not 0, since many useful functions object to 0, such as log, 1/x etc. (But this is more broad than your example.) c) There's another, more basic reason: if you have multiple timeseries, each with a different start-year (e.g. one series starts in 1996, another in 2008). Then if you want to focus on the relative time lag, and remove hard year numbers from the model coefficients, graphs etc., again compute yearx = year - start_year for each series.
Using years when calculating linear regression? a) If you're sure (or in this case specifically told) you only need to use year as linear variable (no interactions, no quadratic terms, no other terms), and you only have one timeseries, then in this
44,300
Using years when calculating linear regression?
Yes, you can use years as the predictor variable in linear regression. The basic code would be Outcome = Year. The beta coefficient from such a model would allow you to predict the outcome for an unobserved year. It is important to remember that the p-value for the beta coefficient is testing whether there is a linear relationship between Year and Outcome across all years. This is often untrue even if the first and last year are obviously different. If you are really interested in whether the first year is significantly different from the last, you should restrict your data to just those two years, in which case linear regression would not be an appropriate method.
Using years when calculating linear regression?
Yes, you can use years as the predictor variable in linear regression. The basic code would be Outcome = Year. The beta coefficient from such a model would allow you to predict the outcome for an unob
Using years when calculating linear regression? Yes, you can use years as the predictor variable in linear regression. The basic code would be Outcome = Year. The beta coefficient from such a model would allow you to predict the outcome for an unobserved year. It is important to remember that the p-value for the beta coefficient is testing whether there is a linear relationship between Year and Outcome across all years. This is often untrue even if the first and last year are obviously different. If you are really interested in whether the first year is significantly different from the last, you should restrict your data to just those two years, in which case linear regression would not be an appropriate method.
Using years when calculating linear regression? Yes, you can use years as the predictor variable in linear regression. The basic code would be Outcome = Year. The beta coefficient from such a model would allow you to predict the outcome for an unob