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
15,701
Why does the supremum of the Brownian bridge have the Kolmogorov–Smirnov distribution?
For Kolmogorov-Smirnov, consider the null hypothesis. It says that a sample is drawn from a particular distribution. So if you construct the empirical distribution function for $n$ samples $f(x) = \frac{1}{n} \sum_i \chi_{(-\infty, X_i]}(x)$, in the limit of infinite data, it will converge to the underlying distribution. For finite information, it will be off. If one of the measurements is $q$, then at $x=q$ the empirical distribution function takes a step up. We can look at it as a random walk which is constrained to begin and end on the true distribution function. Once you know that, you go ransack the literature for the huge amount of information known about random walks to find out what the largest expected deviation of such a walk is. You can do the same trick with any $p$-norm of the difference between the empirical and underlying distribution functions. For $p=2$, it's called the Cramer-von Mises test. I don't know the set of all such tests for arbitrary real, positive $p$ form a complete class of any kind, but it might be an interesting thing to look at.
Why does the supremum of the Brownian bridge have the Kolmogorov–Smirnov distribution?
For Kolmogorov-Smirnov, consider the null hypothesis. It says that a sample is drawn from a particular distribution. So if you construct the empirical distribution function for $n$ samples $f(x) = \
Why does the supremum of the Brownian bridge have the Kolmogorov–Smirnov distribution? For Kolmogorov-Smirnov, consider the null hypothesis. It says that a sample is drawn from a particular distribution. So if you construct the empirical distribution function for $n$ samples $f(x) = \frac{1}{n} \sum_i \chi_{(-\infty, X_i]}(x)$, in the limit of infinite data, it will converge to the underlying distribution. For finite information, it will be off. If one of the measurements is $q$, then at $x=q$ the empirical distribution function takes a step up. We can look at it as a random walk which is constrained to begin and end on the true distribution function. Once you know that, you go ransack the literature for the huge amount of information known about random walks to find out what the largest expected deviation of such a walk is. You can do the same trick with any $p$-norm of the difference between the empirical and underlying distribution functions. For $p=2$, it's called the Cramer-von Mises test. I don't know the set of all such tests for arbitrary real, positive $p$ form a complete class of any kind, but it might be an interesting thing to look at.
Why does the supremum of the Brownian bridge have the Kolmogorov–Smirnov distribution? For Kolmogorov-Smirnov, consider the null hypothesis. It says that a sample is drawn from a particular distribution. So if you construct the empirical distribution function for $n$ samples $f(x) = \
15,702
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy?
The answer is no. Your model gives a different result for each seed you use. This is a result of the non-deterministic nature of the model. By choosing a specific seed that maximizes the performance on the validation set means that you chose the "arrangement" that best fits this set. However, this does not guarantee that the model with this seed would perform better on a separate test set. This simply means that you have overfit the model on the validation set. This effect is the reason you see many people that rank high in competitions (e.g. kaggle) on the public test set, fall way off on the hidden test set. This approach is not considered by any means the correct approach. Edit (not directly correlated to the answer, but I found it interesting) You can find an interesting study showing the influence of random seeds in computer vision here. The authors first prove that you can achieve better results when using a better seed than the other and offer the critique that many of the supposed SOTA solutions could be merely better seed selection than the others. This is described in the same context as if it is cheating, which in all fairness it kind of is... Better seed selection does not make your model inherently better, it just makes it appear better on the specific test set.
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy?
The answer is no. Your model gives a different result for each seed you use. This is a result of the non-deterministic nature of the model. By choosing a specific seed that maximizes the performance o
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy? The answer is no. Your model gives a different result for each seed you use. This is a result of the non-deterministic nature of the model. By choosing a specific seed that maximizes the performance on the validation set means that you chose the "arrangement" that best fits this set. However, this does not guarantee that the model with this seed would perform better on a separate test set. This simply means that you have overfit the model on the validation set. This effect is the reason you see many people that rank high in competitions (e.g. kaggle) on the public test set, fall way off on the hidden test set. This approach is not considered by any means the correct approach. Edit (not directly correlated to the answer, but I found it interesting) You can find an interesting study showing the influence of random seeds in computer vision here. The authors first prove that you can achieve better results when using a better seed than the other and offer the critique that many of the supposed SOTA solutions could be merely better seed selection than the others. This is described in the same context as if it is cheating, which in all fairness it kind of is... Better seed selection does not make your model inherently better, it just makes it appear better on the specific test set.
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy? The answer is no. Your model gives a different result for each seed you use. This is a result of the non-deterministic nature of the model. By choosing a specific seed that maximizes the performance o
15,703
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy?
For some algorithms a bad initialization may matter and may be due to the particular random seed. In such cases, it may make sense to try to find a good initialitzation (=good random seed) that then leads to a good performance (or to find a way of modifying the training to reduce such effects). However, one should really be convinced that this is going on, because what we don't want to do - as others already pointed out - is to overfit our validation set by finding a seed that happens to produce a good result due to some ill-understood combination of the noisiness of the training process and the characteristics of the validation set (or sets in cross-validation). In the particular case of the random forest algorithm, I don't think we are in a case where we want to optimize the seed, at all. What we can do instead is to increase the number of trees until the results no longer depend on the seed in any meaningful way. More trees don't lead to overfitting for RF (unlike for, say, XGBoost, for which the corresponding remedy would be to fit the model multiple times and average the predictions), more trees just takes random noise out of the validaiton set performance (and up to an extent improve performance). For RF, I'd argue such randomness is just "bad" in the sense that it obscures the best hyperparameters with noise and might be due to some chance combination of factors between training process & validation set characteristics, but we have no reason to think these fluctuations would reliably turn up on new data (such as an unseen test set). So, it makes sense to eliminate it as much as possible (to the degree that that's possible in terms of our computational budget for training and inference).
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy?
For some algorithms a bad initialization may matter and may be due to the particular random seed. In such cases, it may make sense to try to find a good initialitzation (=good random seed) that then l
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy? For some algorithms a bad initialization may matter and may be due to the particular random seed. In such cases, it may make sense to try to find a good initialitzation (=good random seed) that then leads to a good performance (or to find a way of modifying the training to reduce such effects). However, one should really be convinced that this is going on, because what we don't want to do - as others already pointed out - is to overfit our validation set by finding a seed that happens to produce a good result due to some ill-understood combination of the noisiness of the training process and the characteristics of the validation set (or sets in cross-validation). In the particular case of the random forest algorithm, I don't think we are in a case where we want to optimize the seed, at all. What we can do instead is to increase the number of trees until the results no longer depend on the seed in any meaningful way. More trees don't lead to overfitting for RF (unlike for, say, XGBoost, for which the corresponding remedy would be to fit the model multiple times and average the predictions), more trees just takes random noise out of the validaiton set performance (and up to an extent improve performance). For RF, I'd argue such randomness is just "bad" in the sense that it obscures the best hyperparameters with noise and might be due to some chance combination of factors between training process & validation set characteristics, but we have no reason to think these fluctuations would reliably turn up on new data (such as an unseen test set). So, it makes sense to eliminate it as much as possible (to the degree that that's possible in terms of our computational budget for training and inference).
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy? For some algorithms a bad initialization may matter and may be due to the particular random seed. In such cases, it may make sense to try to find a good initialitzation (=good random seed) that then l
15,704
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy?
The short answer is YES, it is both fair and correct, contrary to what @Djib2011 wrote in a separate answer. If you follow the usual procedure in ML, then setting the seed in this context does NOT lead to overfitting, contrary to the other answer here is falsely suggesting. You can call it "seed optimization" or "seed hacking", but definitely not overfitting. Also, YES, using any type of Cross-Validation (including LOOCV) is acceptable, valid and correct. And you should use Model Validation actually (either a type of CV or something else). Essentially, it is totally correct to treat the seed as a hyperparameter in this specific context. It is actually accepted in both industry and academia (and competitions). There are published peer-reviewed papers describing this very procedure. Here are two good examples: https://arxiv.org/abs/1909.10447 https://arxiv.org/abs/1206.5533 Also, it is very common in Unsupervised Learning, e.g. using k-means++ algorithm to set the seed for k-means algorithm. So, I do not understand the confusion of @Djib2011 or other people. @jld in a separate answer goes in more depth to explain why this is not wrong and how to ensure you follow the correct procedure if you opt for performing CV as Model Validation. As it is explained, setting the set might or might not be useful, but this is an other story. Caution: There are at least six sources of randomness in ML (that can be set using a seed). You just described one of them. In some of those other contexts, it is wrong to set the seed. Again, this is an other story. Six of those sources are described below: https://medium.com/@ODSC/properly-setting-the-random-seed-in-ml-experiments-not-as-simple-as-you-might-imagine-219969c84752
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy?
The short answer is YES, it is both fair and correct, contrary to what @Djib2011 wrote in a separate answer. If you follow the usual procedure in ML, then setting the seed in this context does NOT lea
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy? The short answer is YES, it is both fair and correct, contrary to what @Djib2011 wrote in a separate answer. If you follow the usual procedure in ML, then setting the seed in this context does NOT lead to overfitting, contrary to the other answer here is falsely suggesting. You can call it "seed optimization" or "seed hacking", but definitely not overfitting. Also, YES, using any type of Cross-Validation (including LOOCV) is acceptable, valid and correct. And you should use Model Validation actually (either a type of CV or something else). Essentially, it is totally correct to treat the seed as a hyperparameter in this specific context. It is actually accepted in both industry and academia (and competitions). There are published peer-reviewed papers describing this very procedure. Here are two good examples: https://arxiv.org/abs/1909.10447 https://arxiv.org/abs/1206.5533 Also, it is very common in Unsupervised Learning, e.g. using k-means++ algorithm to set the seed for k-means algorithm. So, I do not understand the confusion of @Djib2011 or other people. @jld in a separate answer goes in more depth to explain why this is not wrong and how to ensure you follow the correct procedure if you opt for performing CV as Model Validation. As it is explained, setting the set might or might not be useful, but this is an other story. Caution: There are at least six sources of randomness in ML (that can be set using a seed). You just described one of them. In some of those other contexts, it is wrong to set the seed. Again, this is an other story. Six of those sources are described below: https://medium.com/@ODSC/properly-setting-the-random-seed-in-ml-experiments-not-as-simple-as-you-might-imagine-219969c84752
Is it 'fair' to set a seed in a random forest regression to yield the highest accuracy? The short answer is YES, it is both fair and correct, contrary to what @Djib2011 wrote in a separate answer. If you follow the usual procedure in ML, then setting the seed in this context does NOT lea
15,705
Feature scaling and mean normalization [closed]
$x^{(4)}_2 \to 4761$. Nomalized feature $\to \dfrac{x - u}{s}$ where $u$ is average of $X$ and $s = max - min = 8836 - 4761 = 4075$. Finally, $\dfrac{4761 - 6675.5}{4075} = -0.47$
Feature scaling and mean normalization [closed]
$x^{(4)}_2 \to 4761$. Nomalized feature $\to \dfrac{x - u}{s}$ where $u$ is average of $X$ and $s = max - min = 8836 - 4761 = 4075$. Finally, $\dfrac{4761 - 6675.5}{4075} = -0.47$
Feature scaling and mean normalization [closed] $x^{(4)}_2 \to 4761$. Nomalized feature $\to \dfrac{x - u}{s}$ where $u$ is average of $X$ and $s = max - min = 8836 - 4761 = 4075$. Finally, $\dfrac{4761 - 6675.5}{4075} = -0.47$
Feature scaling and mean normalization [closed] $x^{(4)}_2 \to 4761$. Nomalized feature $\to \dfrac{x - u}{s}$ where $u$ is average of $X$ and $s = max - min = 8836 - 4761 = 4075$. Finally, $\dfrac{4761 - 6675.5}{4075} = -0.47$
15,706
Feature scaling and mean normalization [closed]
My answer: Average = (7921 + 5184 + 8836 + 4761)/4 = 6675.5 Range = 8836 - 4761 = 4075 x2 = (5184 - 6675.5)/4075 = -0.366 = -0.37 (rounded to 2 decimal places) Edited: I got the error. I should have rounded to 2 decimal places.
Feature scaling and mean normalization [closed]
My answer: Average = (7921 + 5184 + 8836 + 4761)/4 = 6675.5 Range = 8836 - 4761 = 4075 x2 = (5184 - 6675.5)/4075 = -0.366 = -0.37 (rounded to 2 decimal places) Edited
Feature scaling and mean normalization [closed] My answer: Average = (7921 + 5184 + 8836 + 4761)/4 = 6675.5 Range = 8836 - 4761 = 4075 x2 = (5184 - 6675.5)/4075 = -0.366 = -0.37 (rounded to 2 decimal places) Edited: I got the error. I should have rounded to 2 decimal places.
Feature scaling and mean normalization [closed] My answer: Average = (7921 + 5184 + 8836 + 4761)/4 = 6675.5 Range = 8836 - 4761 = 4075 x2 = (5184 - 6675.5)/4075 = -0.366 = -0.37 (rounded to 2 decimal places) Edited
15,707
Feature scaling and mean normalization [closed]
Since , normalized $x = \frac{x - u}{s}$ where u = mean of the feature x, s = $range(max - min)$ or standard deviation Here, in this quiz s means the range actually so, normalized x = $\frac{4761 - 6675.5}{8836 - 4761}$ = -0.47
Feature scaling and mean normalization [closed]
Since , normalized $x = \frac{x - u}{s}$ where u = mean of the feature x, s = $range(max - min)$ or standard deviation Here, in this quiz s means the range actually so, normalized x = $\frac
Feature scaling and mean normalization [closed] Since , normalized $x = \frac{x - u}{s}$ where u = mean of the feature x, s = $range(max - min)$ or standard deviation Here, in this quiz s means the range actually so, normalized x = $\frac{4761 - 6675.5}{8836 - 4761}$ = -0.47
Feature scaling and mean normalization [closed] Since , normalized $x = \frac{x - u}{s}$ where u = mean of the feature x, s = $range(max - min)$ or standard deviation Here, in this quiz s means the range actually so, normalized x = $\frac
15,708
Feature scaling and mean normalization [closed]
Read the guide please : They said : Please round off your answer to two decimal places and enter in the text box below. The answer is -0.37 . I did it and success.
Feature scaling and mean normalization [closed]
Read the guide please : They said : Please round off your answer to two decimal places and enter in the text box below. The answer is -0.37 . I did it and success.
Feature scaling and mean normalization [closed] Read the guide please : They said : Please round off your answer to two decimal places and enter in the text box below. The answer is -0.37 . I did it and success.
Feature scaling and mean normalization [closed] Read the guide please : They said : Please round off your answer to two decimal places and enter in the text box below. The answer is -0.37 . I did it and success.
15,709
Feature scaling and mean normalization [closed]
x(4)2→4761. Nomalized feature →x−us where u is average of X and s=max−min=8836−4761=4075. Finally, 4761−6675.54075 = −0.47 So Answer is : −0.47
Feature scaling and mean normalization [closed]
x(4)2→4761. Nomalized feature →x−us where u is average of X and s=max−min=8836−4761=4075. Finally, 4761−6675.54075 = −0.47 So Answer is : −0.47
Feature scaling and mean normalization [closed] x(4)2→4761. Nomalized feature →x−us where u is average of X and s=max−min=8836−4761=4075. Finally, 4761−6675.54075 = −0.47 So Answer is : −0.47
Feature scaling and mean normalization [closed] x(4)2→4761. Nomalized feature →x−us where u is average of X and s=max−min=8836−4761=4075. Finally, 4761−6675.54075 = −0.47 So Answer is : −0.47
15,710
Confusion with Augmented Dickey Fuller test
Since you take the default value of k in adf.test, which in this case is 7, you're basically testing if the information set of the past 7 months helps explain $x_t - x_{t-1}$. Electricity usage has strong seasonality, as your plot shows, and is likely to be cyclical beyond a 7-month period. If you set k=12 and retest, the null of unit root cannot be rejected, > adf.test(electricity, k=12) Augmented Dickey-Fuller Test data: electricity Dickey-Fuller = -1.9414, Lag order = 12, p-value = 0.602 alternative hypothesis: stationary
Confusion with Augmented Dickey Fuller test
Since you take the default value of k in adf.test, which in this case is 7, you're basically testing if the information set of the past 7 months helps explain $x_t - x_{t-1}$. Electricity usage has st
Confusion with Augmented Dickey Fuller test Since you take the default value of k in adf.test, which in this case is 7, you're basically testing if the information set of the past 7 months helps explain $x_t - x_{t-1}$. Electricity usage has strong seasonality, as your plot shows, and is likely to be cyclical beyond a 7-month period. If you set k=12 and retest, the null of unit root cannot be rejected, > adf.test(electricity, k=12) Augmented Dickey-Fuller Test data: electricity Dickey-Fuller = -1.9414, Lag order = 12, p-value = 0.602 alternative hypothesis: stationary
Confusion with Augmented Dickey Fuller test Since you take the default value of k in adf.test, which in this case is 7, you're basically testing if the information set of the past 7 months helps explain $x_t - x_{t-1}$. Electricity usage has st
15,711
Confusion with Augmented Dickey Fuller test
Assuming that "adf.test" really comes from the "tseries" package (directly or indirectly), the reason would be that it automatically includes a linear time trend. From the tseries doc (version 0.10-35): "The general regression equation which incorporates a constant and a linear trend is used [...]" So the test result indeed indicates trend stationarity (which despite the name is not stationary). I also agree with Pantera that the seasonal effects could distort the result. The series could in reality be a time trend + deterministic seasonals + stochastic unit root process, but the ADF test might mis-interpret the seasonal fluctuations as stochastic reversions to the deterministic trend, which would imply roots smaller than unity. (On the other hand, given that you have included enough lags, this should rather show up as (spurious) unit roots at seasonal frequencies, not the zero/long-run frequency that the ADF test looks at. In any case, given the seasonal pattern it's better to include the seasonals.)
Confusion with Augmented Dickey Fuller test
Assuming that "adf.test" really comes from the "tseries" package (directly or indirectly), the reason would be that it automatically includes a linear time trend. From the tseries doc (version 0.10-35
Confusion with Augmented Dickey Fuller test Assuming that "adf.test" really comes from the "tseries" package (directly or indirectly), the reason would be that it automatically includes a linear time trend. From the tseries doc (version 0.10-35): "The general regression equation which incorporates a constant and a linear trend is used [...]" So the test result indeed indicates trend stationarity (which despite the name is not stationary). I also agree with Pantera that the seasonal effects could distort the result. The series could in reality be a time trend + deterministic seasonals + stochastic unit root process, but the ADF test might mis-interpret the seasonal fluctuations as stochastic reversions to the deterministic trend, which would imply roots smaller than unity. (On the other hand, given that you have included enough lags, this should rather show up as (spurious) unit roots at seasonal frequencies, not the zero/long-run frequency that the ADF test looks at. In any case, given the seasonal pattern it's better to include the seasonals.)
Confusion with Augmented Dickey Fuller test Assuming that "adf.test" really comes from the "tseries" package (directly or indirectly), the reason would be that it automatically includes a linear time trend. From the tseries doc (version 0.10-35
15,712
Can I use glm algorithms to do a multinomial logistic regression?
Yes, with a Poisson GLM (log linear model) you can fit multinomial models. Hence multinomial logistic or log linear Poisson models are equivalent. You need to see random counts $y_{ij}$ as Poisson random variables with means $μ_{ij}$ and specify the following the following log-linear model $\log(μ_{ij}) = o + p_i + c_j + x_iβ_j$ To get a multinomial logit model the parameters are: A parameter $p_i$ for each multinomial observation, for example individuals or group. This assures exact reproduction of the multinomial denominators and actually establishes the equivalence of Poisson and multinomial model. They are fixed in the multinomial likelihood, but random in the Poisson likelihood. A parameter $c_j$ for each response category. This way the counts can be different for each response category and the margins can be non-uniform. What you are really interested in are the interaction terms $x_iβ_j$ that represent the effects of $x_i$ on the log-odds of response $j$. The log-odds can be simply calculated by $\log(μ_{ij}/μ_{ik}) = (c_j-c_k) +x_i(β_j-β_k)$. It is the log odds that observation i will fall in response category j relative to the response category $k$. Then, the parameters in the multinomial logit model (denoted in latin letters) can be obtained as differences between the parameters in the corresponding log-linear model, i.e. $a_j = α_j-α_k$ and $b_j = β_j-β_k$.
Can I use glm algorithms to do a multinomial logistic regression?
Yes, with a Poisson GLM (log linear model) you can fit multinomial models. Hence multinomial logistic or log linear Poisson models are equivalent. You need to see random counts $y_{ij}$ as Poisson ra
Can I use glm algorithms to do a multinomial logistic regression? Yes, with a Poisson GLM (log linear model) you can fit multinomial models. Hence multinomial logistic or log linear Poisson models are equivalent. You need to see random counts $y_{ij}$ as Poisson random variables with means $μ_{ij}$ and specify the following the following log-linear model $\log(μ_{ij}) = o + p_i + c_j + x_iβ_j$ To get a multinomial logit model the parameters are: A parameter $p_i$ for each multinomial observation, for example individuals or group. This assures exact reproduction of the multinomial denominators and actually establishes the equivalence of Poisson and multinomial model. They are fixed in the multinomial likelihood, but random in the Poisson likelihood. A parameter $c_j$ for each response category. This way the counts can be different for each response category and the margins can be non-uniform. What you are really interested in are the interaction terms $x_iβ_j$ that represent the effects of $x_i$ on the log-odds of response $j$. The log-odds can be simply calculated by $\log(μ_{ij}/μ_{ik}) = (c_j-c_k) +x_i(β_j-β_k)$. It is the log odds that observation i will fall in response category j relative to the response category $k$. Then, the parameters in the multinomial logit model (denoted in latin letters) can be obtained as differences between the parameters in the corresponding log-linear model, i.e. $a_j = α_j-α_k$ and $b_j = β_j-β_k$.
Can I use glm algorithms to do a multinomial logistic regression? Yes, with a Poisson GLM (log linear model) you can fit multinomial models. Hence multinomial logistic or log linear Poisson models are equivalent. You need to see random counts $y_{ij}$ as Poisson ra
15,713
Can I use glm algorithms to do a multinomial logistic regression?
Yes you can, and in fact this is precisely what the R package GLMNET does for multinomial logistic regression. Writing the log-likelihood function as: $$LogL=\sum_i\sum_cn_{ic}\log(p_{ic})$$ Where $i$ denotes observations and $c$ denotes the multinomial categories $n_{ic}$ is the observed count for observation $i$ in category $c$. The observations are defined by their unique covariate combinations - or alternatively we can allow duplicates and set each $n_{ic}=1$ so that we have categorical "binary" data (....don't know what the plural of binary is....). For logistic regression the probabilities are defined as: $$p_{ic}=\frac{\exp\left(x_{i}^T\beta_{c}\right)}{\sum_{c'}\exp\left(x_{i}^T\beta_{c'}\right)}$$ This is a less than full rank parameterisation and can be useful if you are using penalised likelihood (such as GLMNET). We could in principle use IRLS/newton rhapson on the full beta matrix $(\beta_1,\dots,\beta_{C})$, however you end up with non-diagonal weight matrices. Alternatively we can optimise "Gibbs-style" by fixing all categories betas except for one, and then optimising just over that category. Then proceed to the next category, and so on. You can see that because the probabilities have the form $$p_{ic}=\frac{\exp\left(x_{i}^T\beta_{c}\right)}{\exp\left(x_{i}^T\beta_{c}\right)+A}\text{ where }\frac{\partial A}{\partial \beta_c}=0$$ $$p_{ic'}=\frac{B}{\exp\left(x_{i}^T\beta_{c}\right)+A}\text{ where }\frac{\partial B}{\partial \beta_c}=0$$ That the quadratic expansion about $\beta_c$ will have the same form as for logistic regression, but with the IRLS weights calculated differently - although we still have $W_{ii,c}=n_{ic}p_{ic}(1-p_{ic})$ in the usual $(X^TWX)^{-1}X^TWY$ update of beta.
Can I use glm algorithms to do a multinomial logistic regression?
Yes you can, and in fact this is precisely what the R package GLMNET does for multinomial logistic regression. Writing the log-likelihood function as: $$LogL=\sum_i\sum_cn_{ic}\log(p_{ic})$$ Where $i
Can I use glm algorithms to do a multinomial logistic regression? Yes you can, and in fact this is precisely what the R package GLMNET does for multinomial logistic regression. Writing the log-likelihood function as: $$LogL=\sum_i\sum_cn_{ic}\log(p_{ic})$$ Where $i$ denotes observations and $c$ denotes the multinomial categories $n_{ic}$ is the observed count for observation $i$ in category $c$. The observations are defined by their unique covariate combinations - or alternatively we can allow duplicates and set each $n_{ic}=1$ so that we have categorical "binary" data (....don't know what the plural of binary is....). For logistic regression the probabilities are defined as: $$p_{ic}=\frac{\exp\left(x_{i}^T\beta_{c}\right)}{\sum_{c'}\exp\left(x_{i}^T\beta_{c'}\right)}$$ This is a less than full rank parameterisation and can be useful if you are using penalised likelihood (such as GLMNET). We could in principle use IRLS/newton rhapson on the full beta matrix $(\beta_1,\dots,\beta_{C})$, however you end up with non-diagonal weight matrices. Alternatively we can optimise "Gibbs-style" by fixing all categories betas except for one, and then optimising just over that category. Then proceed to the next category, and so on. You can see that because the probabilities have the form $$p_{ic}=\frac{\exp\left(x_{i}^T\beta_{c}\right)}{\exp\left(x_{i}^T\beta_{c}\right)+A}\text{ where }\frac{\partial A}{\partial \beta_c}=0$$ $$p_{ic'}=\frac{B}{\exp\left(x_{i}^T\beta_{c}\right)+A}\text{ where }\frac{\partial B}{\partial \beta_c}=0$$ That the quadratic expansion about $\beta_c$ will have the same form as for logistic regression, but with the IRLS weights calculated differently - although we still have $W_{ii,c}=n_{ic}p_{ic}(1-p_{ic})$ in the usual $(X^TWX)^{-1}X^TWY$ update of beta.
Can I use glm algorithms to do a multinomial logistic regression? Yes you can, and in fact this is precisely what the R package GLMNET does for multinomial logistic regression. Writing the log-likelihood function as: $$LogL=\sum_i\sum_cn_{ic}\log(p_{ic})$$ Where $i
15,714
On George Box, Galit Shmueli and the scientific method?
Let me start with the pithy quote by George Box, that "all models are wrong, but some are useful". This statement is an encapsulation of the methodological approach of "positivism", which is a philosophical approach that is highly influential in the sciences. This approach is described in detail (in the context of economic theory) in the classic methodological essay of Friedman (1966). In that essay, Friedman argues that any useful scientific theory necessarily constitutes a simplification of reality, and thus its assumptions must always depart from reality to some degree, and may even depart substantially from reality. He argues that the value of a scientific theory should not be judged by the closeness of its assumptions to reality --- instead it should be judged by its simplicity in reducing the complexity of the world to a manageable set of principles, and its accuracy in making predictions about reality, and generating new testable hypotheses about reality. Thus, Friedman argues that "all models are wrong" insofar as they all contain assumptions that simplify (and therefore depart from) reality, but that "some are useful" insofar as they give a simple framework to make useful predictions about reality. Now, if you read Box (1976) (the paper where he first states that "all models are wrong"), you will see that he does not cite Friedman, nor does he mention methodological positivism. Nevertheless, his explanation of the scientific method and its characteristics is extremely close to that developed by Friedman. In particular, both authors stress that a scientific theory will make predictions about reality that can be tested against observed facts, and the error in the prediction can then be used as a basis for revision of the theory. Now, on to the dichotomy discussed by Galit Shmueli in Shmueli (2001). In this paper, Shmueli compares causal explanation and prediction of observed outcomes and argues that these are distinct activities. Specifically, she argues that causal relations are based on underlying constructs that do not manifest directly in measureable outcomes, and so "measurable data are not accurate representations of their underlying constructs" (p. 293). She therefore argues that there is an aspect of statistical analysis that involves making inferences about unobservable underlying causal relations that are not manifested in measureable counterfactual differences in outcomes. Unless I am misunderstanding something, I think it is fair to say that this idea is in tension with the positivist views of Box and Friedman, as represented in the quote by Box. The positivist viewpoint essentially says that there are no admissible metaphysical "constructs" beyond those that manifest in measureable outcomes. Positivism confines itself to consideration of observable data, and concepts built on this data; it excludes consideration of a priori metaphysical concepts. Thus, a positivist would argue that the concept of causality can only be valid to the extent that it is defined in terms of measureable outcomes in reality --- to the extent it is defined as something distinct from this (as Shmueli treats it), this would be regarded as metaphysical speculation, and would be treated as inadmissible in scientific discourse. So I think you're right --- these two approaches are essentially in conflict. The positivist approach used by Box insists that valid scientific concepts be grounded entirely in their manifestations in reality, whereas the alternative approach used by Shmueli says that there are some "constructs" that are important scientific concepts (that we want to explain) but which cannot be perfectly represented when they are "operationalised" by relating them to measureable outcomes in reality.
On George Box, Galit Shmueli and the scientific method?
Let me start with the pithy quote by George Box, that "all models are wrong, but some are useful". This statement is an encapsulation of the methodological approach of "positivism", which is a philos
On George Box, Galit Shmueli and the scientific method? Let me start with the pithy quote by George Box, that "all models are wrong, but some are useful". This statement is an encapsulation of the methodological approach of "positivism", which is a philosophical approach that is highly influential in the sciences. This approach is described in detail (in the context of economic theory) in the classic methodological essay of Friedman (1966). In that essay, Friedman argues that any useful scientific theory necessarily constitutes a simplification of reality, and thus its assumptions must always depart from reality to some degree, and may even depart substantially from reality. He argues that the value of a scientific theory should not be judged by the closeness of its assumptions to reality --- instead it should be judged by its simplicity in reducing the complexity of the world to a manageable set of principles, and its accuracy in making predictions about reality, and generating new testable hypotheses about reality. Thus, Friedman argues that "all models are wrong" insofar as they all contain assumptions that simplify (and therefore depart from) reality, but that "some are useful" insofar as they give a simple framework to make useful predictions about reality. Now, if you read Box (1976) (the paper where he first states that "all models are wrong"), you will see that he does not cite Friedman, nor does he mention methodological positivism. Nevertheless, his explanation of the scientific method and its characteristics is extremely close to that developed by Friedman. In particular, both authors stress that a scientific theory will make predictions about reality that can be tested against observed facts, and the error in the prediction can then be used as a basis for revision of the theory. Now, on to the dichotomy discussed by Galit Shmueli in Shmueli (2001). In this paper, Shmueli compares causal explanation and prediction of observed outcomes and argues that these are distinct activities. Specifically, she argues that causal relations are based on underlying constructs that do not manifest directly in measureable outcomes, and so "measurable data are not accurate representations of their underlying constructs" (p. 293). She therefore argues that there is an aspect of statistical analysis that involves making inferences about unobservable underlying causal relations that are not manifested in measureable counterfactual differences in outcomes. Unless I am misunderstanding something, I think it is fair to say that this idea is in tension with the positivist views of Box and Friedman, as represented in the quote by Box. The positivist viewpoint essentially says that there are no admissible metaphysical "constructs" beyond those that manifest in measureable outcomes. Positivism confines itself to consideration of observable data, and concepts built on this data; it excludes consideration of a priori metaphysical concepts. Thus, a positivist would argue that the concept of causality can only be valid to the extent that it is defined in terms of measureable outcomes in reality --- to the extent it is defined as something distinct from this (as Shmueli treats it), this would be regarded as metaphysical speculation, and would be treated as inadmissible in scientific discourse. So I think you're right --- these two approaches are essentially in conflict. The positivist approach used by Box insists that valid scientific concepts be grounded entirely in their manifestations in reality, whereas the alternative approach used by Shmueli says that there are some "constructs" that are important scientific concepts (that we want to explain) but which cannot be perfectly represented when they are "operationalised" by relating them to measureable outcomes in reality.
On George Box, Galit Shmueli and the scientific method? Let me start with the pithy quote by George Box, that "all models are wrong, but some are useful". This statement is an encapsulation of the methodological approach of "positivism", which is a philos
15,715
On George Box, Galit Shmueli and the scientific method?
A model, when used to explain things, is a simplification of reality. Simplification is just another word for "wrong in some useful way". For example, if we round the number 3.1415926535898 to 3.14 we are making an error, but this error allows us humans to focus on the most important part of that number. This is how models are used in explaining, it provides insights on some problem, but by necessity has to abstract away from a lot of other things: We humans are just not very good at looking at a thousands things simultaneously. If we primarily care about predicting we want to include those thousands things whenever possible, but with explaining the trade-off is different.
On George Box, Galit Shmueli and the scientific method?
A model, when used to explain things, is a simplification of reality. Simplification is just another word for "wrong in some useful way". For example, if we round the number 3.1415926535898 to 3.14 w
On George Box, Galit Shmueli and the scientific method? A model, when used to explain things, is a simplification of reality. Simplification is just another word for "wrong in some useful way". For example, if we round the number 3.1415926535898 to 3.14 we are making an error, but this error allows us humans to focus on the most important part of that number. This is how models are used in explaining, it provides insights on some problem, but by necessity has to abstract away from a lot of other things: We humans are just not very good at looking at a thousands things simultaneously. If we primarily care about predicting we want to include those thousands things whenever possible, but with explaining the trade-off is different.
On George Box, Galit Shmueli and the scientific method? A model, when used to explain things, is a simplification of reality. Simplification is just another word for "wrong in some useful way". For example, if we round the number 3.1415926535898 to 3.14 w
15,716
On George Box, Galit Shmueli and the scientific method?
An example of a model that is excellent at prediction but does not explain anything is given in the Wikipedia article “All models are wrong”. The example is Newton’s model of gravitation. Newton’s model almost always gives predictions that are indistinguishable from empirical observations. Yet the model is extremely implausible: because it postulates a force that can act instantaneously over arbitrarily large distances. Newton’s model has been supplanted by the model given in Einstein’s general theory of relativity. With general relativity, gravitational forces travel through space at finite speed (the speed of light). Newton’s model is not a simplification of the general-relativistic model. To illustrate that, consider an apple falling down from a tree. According to general relativity, the apple falls without Earth exerting any force on the apple. (The primary reason the apple falls is that Earth warps time, so that clocks near the base of the tree run more slowly than clocks high up in the tree.) Thus, as the Wikipedia article notes, Newton’s model is completely wrong from an explanatory perspective. The paper by Shmueli [2010] presumes that there are two purposes for a model: prediction and explanation. In fact, several authors have stated that there are three purposes (see e.g. Konishi & Kitagawa [Information Criteria and Statistical Modeling, 2008: §1.1] and Friendly & Meyer [Discrete Data Analysis, 2016: §11.6]). The three purposes correspond to the three kinds of logical reasoning: prediction (corresponding to deduction); parameter estimation (corresponding to induction); description of structure (corresponding to abduction).
On George Box, Galit Shmueli and the scientific method?
An example of a model that is excellent at prediction but does not explain anything is given in the Wikipedia article “All models are wrong”. The example is Newton’s model of gravitation. Newton’s mod
On George Box, Galit Shmueli and the scientific method? An example of a model that is excellent at prediction but does not explain anything is given in the Wikipedia article “All models are wrong”. The example is Newton’s model of gravitation. Newton’s model almost always gives predictions that are indistinguishable from empirical observations. Yet the model is extremely implausible: because it postulates a force that can act instantaneously over arbitrarily large distances. Newton’s model has been supplanted by the model given in Einstein’s general theory of relativity. With general relativity, gravitational forces travel through space at finite speed (the speed of light). Newton’s model is not a simplification of the general-relativistic model. To illustrate that, consider an apple falling down from a tree. According to general relativity, the apple falls without Earth exerting any force on the apple. (The primary reason the apple falls is that Earth warps time, so that clocks near the base of the tree run more slowly than clocks high up in the tree.) Thus, as the Wikipedia article notes, Newton’s model is completely wrong from an explanatory perspective. The paper by Shmueli [2010] presumes that there are two purposes for a model: prediction and explanation. In fact, several authors have stated that there are three purposes (see e.g. Konishi & Kitagawa [Information Criteria and Statistical Modeling, 2008: §1.1] and Friendly & Meyer [Discrete Data Analysis, 2016: §11.6]). The three purposes correspond to the three kinds of logical reasoning: prediction (corresponding to deduction); parameter estimation (corresponding to induction); description of structure (corresponding to abduction).
On George Box, Galit Shmueli and the scientific method? An example of a model that is excellent at prediction but does not explain anything is given in the Wikipedia article “All models are wrong”. The example is Newton’s model of gravitation. Newton’s mod
15,717
On George Box, Galit Shmueli and the scientific method?
I'm an undergraduate in Statistics, so I won't call myself an expert, but here are my two cents. Models don't explain themselves; humans interpret them. Linear models are easier to understand than neural networks and random forests because they are closer to how we make decisions. Indeed, ANNs imitate the human brain, but you don't decide which restaurant to go tomorrow by doing a series of matrix multiplications. Instead, you weight some factors in your mind by their importance, which is essentially a linear combination. "Explanatory power" measures how well a model gets along with humans' intuition, whereas "predictive power" measures how well it aligns with the underlying mechanism of the process in interest. The contradiction between them is essentially the gap between what the world is and how we can perceive/understand it. I hope this explains why "some models do a good job of explaining, even though they do a poor job at predicting". Ian Stewart once said, "If our brains were simple enough for us to understand them, we'd be so simple that we couldn't." Unfortunately, our little human brains are actually very simple compared to the universe, or even a stock market (which involves a lot of brains :). Up to now, all models are products of human brains, so it must be more-or-less inaccurate, which leads to Box's "All models are wrong". On the other hand, a model doesn't have to be technically correct to be useful. For example, Newton's laws of motion has been disproved by Einstein, but it remains useful when an object is not ridiculously big or fast. To address your question, I honestly can't see the incompatibility between Box and Shmueli's points. It seems that you consider "explanatory power" and "predictive power" to be binomial properties, but I think they sit at the two ends of a spectrum.
On George Box, Galit Shmueli and the scientific method?
I'm an undergraduate in Statistics, so I won't call myself an expert, but here are my two cents. Models don't explain themselves; humans interpret them. Linear models are easier to understand than neu
On George Box, Galit Shmueli and the scientific method? I'm an undergraduate in Statistics, so I won't call myself an expert, but here are my two cents. Models don't explain themselves; humans interpret them. Linear models are easier to understand than neural networks and random forests because they are closer to how we make decisions. Indeed, ANNs imitate the human brain, but you don't decide which restaurant to go tomorrow by doing a series of matrix multiplications. Instead, you weight some factors in your mind by their importance, which is essentially a linear combination. "Explanatory power" measures how well a model gets along with humans' intuition, whereas "predictive power" measures how well it aligns with the underlying mechanism of the process in interest. The contradiction between them is essentially the gap between what the world is and how we can perceive/understand it. I hope this explains why "some models do a good job of explaining, even though they do a poor job at predicting". Ian Stewart once said, "If our brains were simple enough for us to understand them, we'd be so simple that we couldn't." Unfortunately, our little human brains are actually very simple compared to the universe, or even a stock market (which involves a lot of brains :). Up to now, all models are products of human brains, so it must be more-or-less inaccurate, which leads to Box's "All models are wrong". On the other hand, a model doesn't have to be technically correct to be useful. For example, Newton's laws of motion has been disproved by Einstein, but it remains useful when an object is not ridiculously big or fast. To address your question, I honestly can't see the incompatibility between Box and Shmueli's points. It seems that you consider "explanatory power" and "predictive power" to be binomial properties, but I think they sit at the two ends of a spectrum.
On George Box, Galit Shmueli and the scientific method? I'm an undergraduate in Statistics, so I won't call myself an expert, but here are my two cents. Models don't explain themselves; humans interpret them. Linear models are easier to understand than neu
15,718
Boosting A Logistic Regression Model
Don't confuse the handling of the predictors (via base learners, e.g. stumps) and the handling of the loss function in boosting. Although AdaBoost can be thought of as finding combinations of base learners to minimize misclassification error, the "Additive Logistic Regression" paper you cite shows that it can also be formulated to minimize an exponential loss function. This insight opened up the boosting approach to a wide class of machine-learning problems that minimize differentiable loss functions, via gradient boosting. The residuals that are fit at each step are pseudo-residuals calculated from the gradient of the loss function. Even if the predictors are modeled as binary stumps, the output of the model thus need not be a binary choice. As another answer states, linear base learners might not work for boosting, but linear base learners are not required for "boosted regression" in either the standard or the logistic sense. Decidedly non-linear stumps can be combined as slow base learners to minimize appropriate loss functions. It's still called "boosted regression" even though it is far from a standard regression model linear in the coefficients of the predictors. The loss function can be functionally the same for linear models and "boosted regression" models with stumps or trees as predictors. Chapter 8 of ISLR makes this pretty clear. So if you want a logistic-regression equivalent to boosted regression, focus on the loss function rather than on the base learners. That's what the LogitBoost approach in the paper you cite does: minimize a log-loss rather than the exponential loss implicit in adaboost. The Wikipedia AdaBoost page describes this difference. Many participants in this site would argue that a log-odds/probability based prediction is highly preferable to a strict yes/no classification prediction, as the former more generally allows for different tradeoffs between the extra costs of false-positive and false-negative predictions. As the answer to your related question indicates, it is possible to obtain estimated probabilities from the strong classifier derived from AdaBoost, but LogitBoost may well give better performance. Implementations of gradient boosting for classification can provide information on the underlying probabilities. For example, this page on gradient boosting shows how sklearn code allows for a choice between deviance loss for logistic regression and exponential loss for AdaBoost, and documents functions to predict probabilities from the gradient-boosted model.
Boosting A Logistic Regression Model
Don't confuse the handling of the predictors (via base learners, e.g. stumps) and the handling of the loss function in boosting. Although AdaBoost can be thought of as finding combinations of base lea
Boosting A Logistic Regression Model Don't confuse the handling of the predictors (via base learners, e.g. stumps) and the handling of the loss function in boosting. Although AdaBoost can be thought of as finding combinations of base learners to minimize misclassification error, the "Additive Logistic Regression" paper you cite shows that it can also be formulated to minimize an exponential loss function. This insight opened up the boosting approach to a wide class of machine-learning problems that minimize differentiable loss functions, via gradient boosting. The residuals that are fit at each step are pseudo-residuals calculated from the gradient of the loss function. Even if the predictors are modeled as binary stumps, the output of the model thus need not be a binary choice. As another answer states, linear base learners might not work for boosting, but linear base learners are not required for "boosted regression" in either the standard or the logistic sense. Decidedly non-linear stumps can be combined as slow base learners to minimize appropriate loss functions. It's still called "boosted regression" even though it is far from a standard regression model linear in the coefficients of the predictors. The loss function can be functionally the same for linear models and "boosted regression" models with stumps or trees as predictors. Chapter 8 of ISLR makes this pretty clear. So if you want a logistic-regression equivalent to boosted regression, focus on the loss function rather than on the base learners. That's what the LogitBoost approach in the paper you cite does: minimize a log-loss rather than the exponential loss implicit in adaboost. The Wikipedia AdaBoost page describes this difference. Many participants in this site would argue that a log-odds/probability based prediction is highly preferable to a strict yes/no classification prediction, as the former more generally allows for different tradeoffs between the extra costs of false-positive and false-negative predictions. As the answer to your related question indicates, it is possible to obtain estimated probabilities from the strong classifier derived from AdaBoost, but LogitBoost may well give better performance. Implementations of gradient boosting for classification can provide information on the underlying probabilities. For example, this page on gradient boosting shows how sklearn code allows for a choice between deviance loss for logistic regression and exponential loss for AdaBoost, and documents functions to predict probabilities from the gradient-boosted model.
Boosting A Logistic Regression Model Don't confuse the handling of the predictors (via base learners, e.g. stumps) and the handling of the loss function in boosting. Although AdaBoost can be thought of as finding combinations of base lea
15,719
Boosting A Logistic Regression Model
In fact we have a very similar question here on regression case. And we had a very good answer by @Matthew Drury Gradient Boosting for Linear Regression - why does it not work? Linear model (such as logistic regression) is not good for boosting. The reason is if you add two linear models together, the result is another linear model. On the other hand, adding two decision stumps or trees, will have a more complicated and interesting model (not a tree any more.) Details can be found in this post. In this link I derived why adding two linear models are not interesting. And I am showing the effect of boosting on decision stump iteration by iteration. How does linear base learner works in boosting? And how does it works in the xgboost library? Note that, decision tree / stump is not a "linear model" similar to logistic regression. See this post for details Is a decision stump a linear model?
Boosting A Logistic Regression Model
In fact we have a very similar question here on regression case. And we had a very good answer by @Matthew Drury Gradient Boosting for Linear Regression - why does it not work? Linear model (such as l
Boosting A Logistic Regression Model In fact we have a very similar question here on regression case. And we had a very good answer by @Matthew Drury Gradient Boosting for Linear Regression - why does it not work? Linear model (such as logistic regression) is not good for boosting. The reason is if you add two linear models together, the result is another linear model. On the other hand, adding two decision stumps or trees, will have a more complicated and interesting model (not a tree any more.) Details can be found in this post. In this link I derived why adding two linear models are not interesting. And I am showing the effect of boosting on decision stump iteration by iteration. How does linear base learner works in boosting? And how does it works in the xgboost library? Note that, decision tree / stump is not a "linear model" similar to logistic regression. See this post for details Is a decision stump a linear model?
Boosting A Logistic Regression Model In fact we have a very similar question here on regression case. And we had a very good answer by @Matthew Drury Gradient Boosting for Linear Regression - why does it not work? Linear model (such as l
15,720
Data augmentation on training set only?
In terms of the concept of augmentation, ie making the data set bigger for some reason, we'd tend to only augment the training set. We'd evaluate the result of different augmentation approaches on a validation set. However, as @Łukasz Grad points out, we might need to perform a similar procedure to the test set as was done on the training set. This is typically so that the input data from the test set resembles as much as possible that of the training set. For example, @Łukasz Grad points out the example of image cropping, where we'd need to crop the test images too, so they are the same size as the training images. However, in the case of the training images, we might use each training image multiple times, with crops in different locations/offsets. At test time we'd likely either do a single centred crop, or do random crops and take an average. Running the augmentation procedure against test data is not to make the test data bigger/more accurate, but just to make the input data from the test set resemble that of the input data from the training set, so we can feed it into the same net (eg same dimensions). We'd never consider that the test set is 'better' in some way, by applying an augmentation procedure. At least, that's not something I've ever seen. On the other hand, for the training set, the point of the augmentation is to reduce overfitting during training. And we evaluate the quality of the augmentation by then running the trained model against our more-or-less fixed test/validation set.
Data augmentation on training set only?
In terms of the concept of augmentation, ie making the data set bigger for some reason, we'd tend to only augment the training set. We'd evaluate the result of different augmentation approaches on a v
Data augmentation on training set only? In terms of the concept of augmentation, ie making the data set bigger for some reason, we'd tend to only augment the training set. We'd evaluate the result of different augmentation approaches on a validation set. However, as @Łukasz Grad points out, we might need to perform a similar procedure to the test set as was done on the training set. This is typically so that the input data from the test set resembles as much as possible that of the training set. For example, @Łukasz Grad points out the example of image cropping, where we'd need to crop the test images too, so they are the same size as the training images. However, in the case of the training images, we might use each training image multiple times, with crops in different locations/offsets. At test time we'd likely either do a single centred crop, or do random crops and take an average. Running the augmentation procedure against test data is not to make the test data bigger/more accurate, but just to make the input data from the test set resemble that of the input data from the training set, so we can feed it into the same net (eg same dimensions). We'd never consider that the test set is 'better' in some way, by applying an augmentation procedure. At least, that's not something I've ever seen. On the other hand, for the training set, the point of the augmentation is to reduce overfitting during training. And we evaluate the quality of the augmentation by then running the trained model against our more-or-less fixed test/validation set.
Data augmentation on training set only? In terms of the concept of augmentation, ie making the data set bigger for some reason, we'd tend to only augment the training set. We'd evaluate the result of different augmentation approaches on a v
15,721
Data augmentation on training set only?
Typically, data augmentation for training convolutional neural networks is only done to the training set. I'm not sure what benefit augmenting the test data would achieve as the value of test data is primarily for model selection and evaluation and you're adding noise to your measurement of those quantities.
Data augmentation on training set only?
Typically, data augmentation for training convolutional neural networks is only done to the training set. I'm not sure what benefit augmenting the test data would achieve as the value of test data is
Data augmentation on training set only? Typically, data augmentation for training convolutional neural networks is only done to the training set. I'm not sure what benefit augmenting the test data would achieve as the value of test data is primarily for model selection and evaluation and you're adding noise to your measurement of those quantities.
Data augmentation on training set only? Typically, data augmentation for training convolutional neural networks is only done to the training set. I'm not sure what benefit augmenting the test data would achieve as the value of test data is
15,722
Data augmentation on training set only?
Complementing the answers, let my add my 2 cents regarding test-time data augmentation. Data augmentation can be also performed during test-time with the goal of reducing variance. It can be performed by taking the average of the predictions of modified versions of the input image. Dataset augmentation may be seen as a way of preprocessing the training set only. Dataset augmentation is an excellent way to reduce the generalization error of most computer vision models. A related idea applicable at test time is to show the model many different versions of the same input (for example, the same image cropped at slightly different locations) and have the different instantiations of the model vote to determine the output. This latter idea can be interpreted as an ensemble approach, and it helps to reduce generalization error. (Deep Learning Book, Chapter 12). It's a very common practice to apply test-time augmentation. AlexNet and ResNet do that with the 10-crop technique (taking patches from the four corners and the center of the original image and also mirroring them). Inception goes further and generate 144 patches instead of only 10. If you check Kaggle and other competitions, most winners also apply test-time augmentation. I'm the author of a paper on data augmentation (code) in which we experimented with training and testing augmentation for skin lesion classification (a low-data task). In some cases, using strong data augmentation on training alone is marginally better than not using data augmentation, while using train and test augmentation increases the performance of the model by a very significant margin.
Data augmentation on training set only?
Complementing the answers, let my add my 2 cents regarding test-time data augmentation. Data augmentation can be also performed during test-time with the goal of reducing variance. It can be performed
Data augmentation on training set only? Complementing the answers, let my add my 2 cents regarding test-time data augmentation. Data augmentation can be also performed during test-time with the goal of reducing variance. It can be performed by taking the average of the predictions of modified versions of the input image. Dataset augmentation may be seen as a way of preprocessing the training set only. Dataset augmentation is an excellent way to reduce the generalization error of most computer vision models. A related idea applicable at test time is to show the model many different versions of the same input (for example, the same image cropped at slightly different locations) and have the different instantiations of the model vote to determine the output. This latter idea can be interpreted as an ensemble approach, and it helps to reduce generalization error. (Deep Learning Book, Chapter 12). It's a very common practice to apply test-time augmentation. AlexNet and ResNet do that with the 10-crop technique (taking patches from the four corners and the center of the original image and also mirroring them). Inception goes further and generate 144 patches instead of only 10. If you check Kaggle and other competitions, most winners also apply test-time augmentation. I'm the author of a paper on data augmentation (code) in which we experimented with training and testing augmentation for skin lesion classification (a low-data task). In some cases, using strong data augmentation on training alone is marginally better than not using data augmentation, while using train and test augmentation increases the performance of the model by a very significant margin.
Data augmentation on training set only? Complementing the answers, let my add my 2 cents regarding test-time data augmentation. Data augmentation can be also performed during test-time with the goal of reducing variance. It can be performed
15,723
What are real life examples of "non-parametric statistical models"?
As Johnnyboycurtis has answerd, non-parametric methods are those if it makes no assumption on the population distribution or sample size to generate a model. A k-NN model is an example of a non-parametric model as it does not consider any assumptions to develop a model. A Naive Bayes or K-means is an example of parametric as it assumes a distribution for creating a model. For instance, K-means assumes the following to develop a model All clusters are spherical (i.i.d. Gaussian). All axes have the same distribution and thus variance. All clusters are evenly sized. As for k-NN, it uses the complete training set for prediction. It calculates the nearest neighbors from the test point for prediction. It assumes no distribution for creating a model. For more info: http://pages.cs.wisc.edu/~jerryzhu/cs731/stat.pdf https://stats.stackexchange.com/a/133841/86202 https://stats.stackexchange.com/a/133694/86202
What are real life examples of "non-parametric statistical models"?
As Johnnyboycurtis has answerd, non-parametric methods are those if it makes no assumption on the population distribution or sample size to generate a model. A k-NN model is an example of a non-param
What are real life examples of "non-parametric statistical models"? As Johnnyboycurtis has answerd, non-parametric methods are those if it makes no assumption on the population distribution or sample size to generate a model. A k-NN model is an example of a non-parametric model as it does not consider any assumptions to develop a model. A Naive Bayes or K-means is an example of parametric as it assumes a distribution for creating a model. For instance, K-means assumes the following to develop a model All clusters are spherical (i.i.d. Gaussian). All axes have the same distribution and thus variance. All clusters are evenly sized. As for k-NN, it uses the complete training set for prediction. It calculates the nearest neighbors from the test point for prediction. It assumes no distribution for creating a model. For more info: http://pages.cs.wisc.edu/~jerryzhu/cs731/stat.pdf https://stats.stackexchange.com/a/133841/86202 https://stats.stackexchange.com/a/133694/86202
What are real life examples of "non-parametric statistical models"? As Johnnyboycurtis has answerd, non-parametric methods are those if it makes no assumption on the population distribution or sample size to generate a model. A k-NN model is an example of a non-param
15,724
What are real life examples of "non-parametric statistical models"?
I'm currently taking a course on Machine learning, where we use the following definition of nonparametric models: "Nonparametric models grow in complexity with the size of the data". Parametric model To see what it mean let's have a look at linear regression, a parametric model: There we try to predict a function parametrized in $ w \in ℝ ^d $: $$ f(x) = w^Tx $$ The dimensionality of w is independent of the number of observations, or the size of your data. Nonparametric models Instead kernel regression tries to predict the following function: $$ f(x) = \sum_{i=1}^n \alpha_i k(x_i, x) $$ where we have $n$ data points, $\alpha_i$ are the weights and $k(x_i, x)$ is the kernel function. Here the number of parameters $\alpha_i$ is dependent on the number of data points $n$. The same is true for the kernelized perceptron: $$ f(x) = sign( \sum_{i=1}^n \alpha_i y_i k(x_i,x))) $$ Let's come back to your definition and say d was the number of $\alpha_i$. If we let $ n \to \infty $ then $d \to \infty$. That's exactly what the wikipedia definition asks for. I took the kernel regression function from my lecture slides and the kernelized perceptron function from wikipedia: https://en.wikipedia.org/wiki/Kernel_method
What are real life examples of "non-parametric statistical models"?
I'm currently taking a course on Machine learning, where we use the following definition of nonparametric models: "Nonparametric models grow in complexity with the size of the data". Parametric model
What are real life examples of "non-parametric statistical models"? I'm currently taking a course on Machine learning, where we use the following definition of nonparametric models: "Nonparametric models grow in complexity with the size of the data". Parametric model To see what it mean let's have a look at linear regression, a parametric model: There we try to predict a function parametrized in $ w \in ℝ ^d $: $$ f(x) = w^Tx $$ The dimensionality of w is independent of the number of observations, or the size of your data. Nonparametric models Instead kernel regression tries to predict the following function: $$ f(x) = \sum_{i=1}^n \alpha_i k(x_i, x) $$ where we have $n$ data points, $\alpha_i$ are the weights and $k(x_i, x)$ is the kernel function. Here the number of parameters $\alpha_i$ is dependent on the number of data points $n$. The same is true for the kernelized perceptron: $$ f(x) = sign( \sum_{i=1}^n \alpha_i y_i k(x_i,x))) $$ Let's come back to your definition and say d was the number of $\alpha_i$. If we let $ n \to \infty $ then $d \to \infty$. That's exactly what the wikipedia definition asks for. I took the kernel regression function from my lecture slides and the kernelized perceptron function from wikipedia: https://en.wikipedia.org/wiki/Kernel_method
What are real life examples of "non-parametric statistical models"? I'm currently taking a course on Machine learning, where we use the following definition of nonparametric models: "Nonparametric models grow in complexity with the size of the data". Parametric model
15,725
What are real life examples of "non-parametric statistical models"?
So, I think you're missing a few points. First, and most importantly, A statistical method is called non-parametric if it makes no assumption on the population distribution or sample size. Here is a simple (applied) tutorial on some nonparmetric models: http://www.r-tutor.com/elementary-statistics/non-parametric-methods A researcher may decide to use a nonparemtric model vs a parametric model, say, nonparamtric regression vs linear regression, is because the data violates assumptions held by the parametric model. Since you're coming from a ML background, I'll just assume you never learned the typical linear regression model assumptions. Here is a reference: https://statistics.laerd.com/spss-tutorials/linear-regression-using-spss-statistics.php Violating assumptions can skew your parameter estimates, and ultimately increase the risk of invalid conclusions. A nonparametric model is more robust to outliers, nonlinear relationships, and does not depend on many population distribution assumptions, hence, can provide more trust worthy results when trying to make inferences or predictions. For a quick tutorial on nonparametric regression, I recommend these slides: http://socserv.socsci.mcmaster.ca/jfox/Courses/Oxford-2005/slides-handout.pdf
What are real life examples of "non-parametric statistical models"?
So, I think you're missing a few points. First, and most importantly, A statistical method is called non-parametric if it makes no assumption on the population distribution or sample size. Here i
What are real life examples of "non-parametric statistical models"? So, I think you're missing a few points. First, and most importantly, A statistical method is called non-parametric if it makes no assumption on the population distribution or sample size. Here is a simple (applied) tutorial on some nonparmetric models: http://www.r-tutor.com/elementary-statistics/non-parametric-methods A researcher may decide to use a nonparemtric model vs a parametric model, say, nonparamtric regression vs linear regression, is because the data violates assumptions held by the parametric model. Since you're coming from a ML background, I'll just assume you never learned the typical linear regression model assumptions. Here is a reference: https://statistics.laerd.com/spss-tutorials/linear-regression-using-spss-statistics.php Violating assumptions can skew your parameter estimates, and ultimately increase the risk of invalid conclusions. A nonparametric model is more robust to outliers, nonlinear relationships, and does not depend on many population distribution assumptions, hence, can provide more trust worthy results when trying to make inferences or predictions. For a quick tutorial on nonparametric regression, I recommend these slides: http://socserv.socsci.mcmaster.ca/jfox/Courses/Oxford-2005/slides-handout.pdf
What are real life examples of "non-parametric statistical models"? So, I think you're missing a few points. First, and most importantly, A statistical method is called non-parametric if it makes no assumption on the population distribution or sample size. Here i
15,726
How do I detrend time series?
If the trend is deterministic (e.g. a linear trend) you could run a regression of the data on the deterministic trend (e.g. a constant plus time index) to estimate the trend and remove it from the data. If the trend is stochastic you should detrend the series by taking first differences on it. The ADF test and the KPSS test can give you some information to determine whether the trend is deterministic or stochastic. As the null hypothesis of the KPSS test is the opposite of the null in the ADF test, the following way to proceed can be determined beforehand: Apply the KPSS to test the null that the series is stationary or stationary around a trend. If the null is rejected (at a predetermined level of significance) conclude that the trend is stochastic, otherwise go to step 2. Apply the ADF test to test the null that a unit root exists. If the null hypothesis is rejected, then conclude that there is no unit root (stationarity), otherwise the result of the procedure is not informative since none of the tests rejected the corresponding null hypothesis. In that case it may be more cautions to consider the existence of a unit root and detrend the series by taking first differences. In the context of structural time series models you could fit a local-level model or a local-trend model to the data to get an estimate of the trend and remove it from the series. The local-trend model is defined as follows (the local-level model is obtained with $\sigma^2_\zeta=0$): \begin{eqnarray} \begin{array}{rll} \hbox{observed series:} & y_t = \mu_t + \gamma_t + \epsilon_t , & \epsilon_t \sim \hbox{NID}(0,\, \sigma^2_\epsilon) ; \\ \hbox{latent level:} & \mu_t = \mu_{t-1} + \beta_{t-1} + \xi_t , & \xi_t \sim \hbox{NID}(0,\, \sigma^2_\xi) ; \\ \hbox{latent drift:} & \beta_t = \beta_{t-1} + \zeta_t , & \zeta_t \sim \hbox{NID}(0,\, \sigma^2_\zeta) ; \\ \end{array} \end{eqnarray}
How do I detrend time series?
If the trend is deterministic (e.g. a linear trend) you could run a regression of the data on the deterministic trend (e.g. a constant plus time index) to estimate the trend and remove it from the dat
How do I detrend time series? If the trend is deterministic (e.g. a linear trend) you could run a regression of the data on the deterministic trend (e.g. a constant plus time index) to estimate the trend and remove it from the data. If the trend is stochastic you should detrend the series by taking first differences on it. The ADF test and the KPSS test can give you some information to determine whether the trend is deterministic or stochastic. As the null hypothesis of the KPSS test is the opposite of the null in the ADF test, the following way to proceed can be determined beforehand: Apply the KPSS to test the null that the series is stationary or stationary around a trend. If the null is rejected (at a predetermined level of significance) conclude that the trend is stochastic, otherwise go to step 2. Apply the ADF test to test the null that a unit root exists. If the null hypothesis is rejected, then conclude that there is no unit root (stationarity), otherwise the result of the procedure is not informative since none of the tests rejected the corresponding null hypothesis. In that case it may be more cautions to consider the existence of a unit root and detrend the series by taking first differences. In the context of structural time series models you could fit a local-level model or a local-trend model to the data to get an estimate of the trend and remove it from the series. The local-trend model is defined as follows (the local-level model is obtained with $\sigma^2_\zeta=0$): \begin{eqnarray} \begin{array}{rll} \hbox{observed series:} & y_t = \mu_t + \gamma_t + \epsilon_t , & \epsilon_t \sim \hbox{NID}(0,\, \sigma^2_\epsilon) ; \\ \hbox{latent level:} & \mu_t = \mu_{t-1} + \beta_{t-1} + \xi_t , & \xi_t \sim \hbox{NID}(0,\, \sigma^2_\xi) ; \\ \hbox{latent drift:} & \beta_t = \beta_{t-1} + \zeta_t , & \zeta_t \sim \hbox{NID}(0,\, \sigma^2_\zeta) ; \\ \end{array} \end{eqnarray}
How do I detrend time series? If the trend is deterministic (e.g. a linear trend) you could run a regression of the data on the deterministic trend (e.g. a constant plus time index) to estimate the trend and remove it from the dat
15,727
How do I detrend time series?
Perhaps there is more than one trend . Perhaps there is a level shift . Perhaps the error variance has changed over time In any case a simple de-trending might be inappropriate. Good exploratory analysis along the line of http://www.unc.edu/~jbhill/tsay.pdf should be used to discover the nature of the data/model.
How do I detrend time series?
Perhaps there is more than one trend . Perhaps there is a level shift . Perhaps the error variance has changed over time In any case a simple de-trending might be inappropriate. Good exploratory anal
How do I detrend time series? Perhaps there is more than one trend . Perhaps there is a level shift . Perhaps the error variance has changed over time In any case a simple de-trending might be inappropriate. Good exploratory analysis along the line of http://www.unc.edu/~jbhill/tsay.pdf should be used to discover the nature of the data/model.
How do I detrend time series? Perhaps there is more than one trend . Perhaps there is a level shift . Perhaps the error variance has changed over time In any case a simple de-trending might be inappropriate. Good exploratory anal
15,728
How do I detrend time series?
You have several ways of detrending a time-series with the aim of making it stationary: The linear detrending is what you copied. It may not give you what you desire as you arbitrarily fix a deterministic linear trend. The quadratic detrending is in some ways similar to the linear detrending, except that you add a "time^2" and supposes a exponential-type behavior. The HP-filter from Hodrick and Prescott (1980) allows you to extract the non-deterministic long-term component of the series. The residual series is thus the cyclical component. Be aware that, as it is an optimal weighted average, it suffers from endpoint bias (the first and last 4 observations are wrongly estimated.) The Bandpass filter of Baxter and King (1995) which is essentialy a Moving Average filter where you exclude high and low frequencies. The Christiano-Fitzgerald filter. To sum up, it depends on what your intention is and some filters may be better suited to your needs than others.
How do I detrend time series?
You have several ways of detrending a time-series with the aim of making it stationary: The linear detrending is what you copied. It may not give you what you desire as you arbitrarily fix a determin
How do I detrend time series? You have several ways of detrending a time-series with the aim of making it stationary: The linear detrending is what you copied. It may not give you what you desire as you arbitrarily fix a deterministic linear trend. The quadratic detrending is in some ways similar to the linear detrending, except that you add a "time^2" and supposes a exponential-type behavior. The HP-filter from Hodrick and Prescott (1980) allows you to extract the non-deterministic long-term component of the series. The residual series is thus the cyclical component. Be aware that, as it is an optimal weighted average, it suffers from endpoint bias (the first and last 4 observations are wrongly estimated.) The Bandpass filter of Baxter and King (1995) which is essentialy a Moving Average filter where you exclude high and low frequencies. The Christiano-Fitzgerald filter. To sum up, it depends on what your intention is and some filters may be better suited to your needs than others.
How do I detrend time series? You have several ways of detrending a time-series with the aim of making it stationary: The linear detrending is what you copied. It may not give you what you desire as you arbitrarily fix a determin
15,729
How do I detrend time series?
I suggest to take a look at Singular Spectrum analysis. It is a nonparametric technique which can be very roughly seen as PCA for time series. One of useful properties is that it can effectively de-trend series.
How do I detrend time series?
I suggest to take a look at Singular Spectrum analysis. It is a nonparametric technique which can be very roughly seen as PCA for time series. One of useful properties is that it can effectively de-tr
How do I detrend time series? I suggest to take a look at Singular Spectrum analysis. It is a nonparametric technique which can be very roughly seen as PCA for time series. One of useful properties is that it can effectively de-trend series.
How do I detrend time series? I suggest to take a look at Singular Spectrum analysis. It is a nonparametric technique which can be very roughly seen as PCA for time series. One of useful properties is that it can effectively de-tr
15,730
How do I detrend time series?
You need to research this subject carefully and can start here. http://www.stat.pitt.edu/stoffer/tsa3/ The key thing you are looking for is stationarity or non-stationarity because most statistical tests assume that data is distributed normally. There are different ways to transform data to make it stationary. Detrending is one of the methods but would be inappropriate for some kinds of non-stationary data. If the data is a random walk with trend then you may have to use differencing. If the data shows a deterministic trend with a seasonal or other deviation from the trend you should start with detrending. You may have to experiment with different approaches.
How do I detrend time series?
You need to research this subject carefully and can start here. http://www.stat.pitt.edu/stoffer/tsa3/ The key thing you are looking for is stationarity or non-stationarity because most statistical te
How do I detrend time series? You need to research this subject carefully and can start here. http://www.stat.pitt.edu/stoffer/tsa3/ The key thing you are looking for is stationarity or non-stationarity because most statistical tests assume that data is distributed normally. There are different ways to transform data to make it stationary. Detrending is one of the methods but would be inappropriate for some kinds of non-stationary data. If the data is a random walk with trend then you may have to use differencing. If the data shows a deterministic trend with a seasonal or other deviation from the trend you should start with detrending. You may have to experiment with different approaches.
How do I detrend time series? You need to research this subject carefully and can start here. http://www.stat.pitt.edu/stoffer/tsa3/ The key thing you are looking for is stationarity or non-stationarity because most statistical te
15,731
Sum of Bernoulli variables with different success probabilities [duplicate]
Yes, in fact, the distribution is known as the Poisson binomial distribution, which is a generalization of the binomial distribution. The distribution's mean and variance are intuitive and are given by $$ \begin{align} E\left[\sum_i x_i\right] &= \sum_i E[x_i] = \sum_i p_i\\ V\left[\sum_i x_i\right] &= \sum_i V[x_i] = \sum_i p_i(1-p_i). \end{align} $$ The expectation is straightforward because it is a linear operator. The variance is also straightforward because of the independence assumption.
Sum of Bernoulli variables with different success probabilities [duplicate]
Yes, in fact, the distribution is known as the Poisson binomial distribution, which is a generalization of the binomial distribution. The distribution's mean and variance are intuitive and are given b
Sum of Bernoulli variables with different success probabilities [duplicate] Yes, in fact, the distribution is known as the Poisson binomial distribution, which is a generalization of the binomial distribution. The distribution's mean and variance are intuitive and are given by $$ \begin{align} E\left[\sum_i x_i\right] &= \sum_i E[x_i] = \sum_i p_i\\ V\left[\sum_i x_i\right] &= \sum_i V[x_i] = \sum_i p_i(1-p_i). \end{align} $$ The expectation is straightforward because it is a linear operator. The variance is also straightforward because of the independence assumption.
Sum of Bernoulli variables with different success probabilities [duplicate] Yes, in fact, the distribution is known as the Poisson binomial distribution, which is a generalization of the binomial distribution. The distribution's mean and variance are intuitive and are given b
15,732
Sum of Bernoulli variables with different success probabilities [duplicate]
I'm not aware of a closed formula to exist. If n becomes relevant you can apply Central Theorem Limit so approximating the sum distribution with a normal distribution having mean the sum of p_i and variance the sum of p_i * ( 1 - p_i).
Sum of Bernoulli variables with different success probabilities [duplicate]
I'm not aware of a closed formula to exist. If n becomes relevant you can apply Central Theorem Limit so approximating the sum distribution with a normal distribution having mean the sum of p_i and va
Sum of Bernoulli variables with different success probabilities [duplicate] I'm not aware of a closed formula to exist. If n becomes relevant you can apply Central Theorem Limit so approximating the sum distribution with a normal distribution having mean the sum of p_i and variance the sum of p_i * ( 1 - p_i).
Sum of Bernoulli variables with different success probabilities [duplicate] I'm not aware of a closed formula to exist. If n becomes relevant you can apply Central Theorem Limit so approximating the sum distribution with a normal distribution having mean the sum of p_i and va
15,733
How to estimate Poisson process using R? (Or: how to use NHPoisson package?)
Fitting a stationary Poisson process First of all it is important to realize, what sort of input data NHPoisson needs. Foremost, NHPoisson needs a list of indices of event moments. If we record time interval and number of events in the time interval, than I we must translate it into a single column of dates, possibly "smearing" the dates over the interval they are recorded on. For the simplicity I'll assume, that we use time measured in seconds, and that the "second" is the natural unit of $\lambda$. Let's simulate data for a simple, stationary Poisson process, which has $\lambda=1$ events per minute: lambda=1/60 #1 event per minute time.span=60*60*24 #24 hours, with time granularity one second aux<-simNHP.fun(rep(lambda,time.span)) The simNHP.fun makes the simulation. We use to get aux$posNH, a variable with indices of moments of simulated event firing. We can see that we roughly have 60*24 = 1440 events, by checking `length(aux$posNH). Now let's reverse-engineer the $\lambda$ with fitPP.fun: out<-fitPP.fun(posE=aux$posNH,n=time.span,start=list(b0=0)) # b0=0 is our guess at initial value for optimization, which is internally made with `nlminb` function Because the function only takes events' indices, it needs also a measure of how many possible indices are possible. And this is a very confusing part, because in the true Poisson process it is possible to have infinite number of possible events (if only $\lambda>0$). But from the perspective of the fitPP we need to choose some small enough time unit. We choose it so small, that we can assume maximum one event per unit of time. So what we do in fact is that we approximate the Poisson process with granular sequence of binomial events, each event spans exactly one unit of time, in analogy to the mechanism in which Poisson distribution can be seen as a limit of binomial distribution in the law of rare events. Once we understand it, the rest is much simpler (at least for me). To get the approximation of our $\lambda$ me need to take exponent of the fitted parameter beta, exp(coef(out)[1]). And here comes another important piece of information, that is missing in the manual: with NHPoisson we fit to the logarithm of $\lambda$, not to $\lambda$ itself. Fitting a non-stationary Poisson process NHPoisson fits the following model: $\lambda = \exp(\vec{P}^T \cdot \vec{\beta} )$ i.e. it fits linear combination of parameters $\vec{P}$ (called covariates) to the logarithm of the $\lambda$. Now let's prepare non-stationary Poisson process. time.span=60*60*24 #24 hours, with time granularity one second all.seconds<-seq(1,time.span,length.out=time.span) lambdas=0.05*exp(-0.0001*all.seconds) #we can't model a linear regression with NHPoisson. It must have the form with exp. aux<-simNHP.fun(lambdas) Just as before, aux$posNH would give us indices of events, but this time we will notice, that the intensity of the events diminish exponentially with time. And the rate of this diminishing is a parameter we want to estimate. out<-fitPP.fun(tind=TRUE,covariates=cbind(all.seconds), posE=aux$posNH, start=list(b0=0,b1=0),modSim=TRUE) It is important to note, that we need to put all.seconds as a covariate, not lambdas. The exponentiation/logaritmization is done internally by the fitPP.fun. BTW, apart from predicted values, the function makes two graphs by default. The last piece is a swiss-knife function for model validation, globalval.fun. aux<-globalval.fun(obFPP=out,lint=2000, covariates=cbind(all.seconds),typeI='Disjoint', typeRes='Raw',typeResLV='Raw',resqqplot=FALSE) Among other things, the function divides the time into intervals, each lint samples long, so it is possible to create crude graphs that compare predicted intensity with observed intensity.
How to estimate Poisson process using R? (Or: how to use NHPoisson package?)
Fitting a stationary Poisson process First of all it is important to realize, what sort of input data NHPoisson needs. Foremost, NHPoisson needs a list of indices of event moments. If we record time
How to estimate Poisson process using R? (Or: how to use NHPoisson package?) Fitting a stationary Poisson process First of all it is important to realize, what sort of input data NHPoisson needs. Foremost, NHPoisson needs a list of indices of event moments. If we record time interval and number of events in the time interval, than I we must translate it into a single column of dates, possibly "smearing" the dates over the interval they are recorded on. For the simplicity I'll assume, that we use time measured in seconds, and that the "second" is the natural unit of $\lambda$. Let's simulate data for a simple, stationary Poisson process, which has $\lambda=1$ events per minute: lambda=1/60 #1 event per minute time.span=60*60*24 #24 hours, with time granularity one second aux<-simNHP.fun(rep(lambda,time.span)) The simNHP.fun makes the simulation. We use to get aux$posNH, a variable with indices of moments of simulated event firing. We can see that we roughly have 60*24 = 1440 events, by checking `length(aux$posNH). Now let's reverse-engineer the $\lambda$ with fitPP.fun: out<-fitPP.fun(posE=aux$posNH,n=time.span,start=list(b0=0)) # b0=0 is our guess at initial value for optimization, which is internally made with `nlminb` function Because the function only takes events' indices, it needs also a measure of how many possible indices are possible. And this is a very confusing part, because in the true Poisson process it is possible to have infinite number of possible events (if only $\lambda>0$). But from the perspective of the fitPP we need to choose some small enough time unit. We choose it so small, that we can assume maximum one event per unit of time. So what we do in fact is that we approximate the Poisson process with granular sequence of binomial events, each event spans exactly one unit of time, in analogy to the mechanism in which Poisson distribution can be seen as a limit of binomial distribution in the law of rare events. Once we understand it, the rest is much simpler (at least for me). To get the approximation of our $\lambda$ me need to take exponent of the fitted parameter beta, exp(coef(out)[1]). And here comes another important piece of information, that is missing in the manual: with NHPoisson we fit to the logarithm of $\lambda$, not to $\lambda$ itself. Fitting a non-stationary Poisson process NHPoisson fits the following model: $\lambda = \exp(\vec{P}^T \cdot \vec{\beta} )$ i.e. it fits linear combination of parameters $\vec{P}$ (called covariates) to the logarithm of the $\lambda$. Now let's prepare non-stationary Poisson process. time.span=60*60*24 #24 hours, with time granularity one second all.seconds<-seq(1,time.span,length.out=time.span) lambdas=0.05*exp(-0.0001*all.seconds) #we can't model a linear regression with NHPoisson. It must have the form with exp. aux<-simNHP.fun(lambdas) Just as before, aux$posNH would give us indices of events, but this time we will notice, that the intensity of the events diminish exponentially with time. And the rate of this diminishing is a parameter we want to estimate. out<-fitPP.fun(tind=TRUE,covariates=cbind(all.seconds), posE=aux$posNH, start=list(b0=0,b1=0),modSim=TRUE) It is important to note, that we need to put all.seconds as a covariate, not lambdas. The exponentiation/logaritmization is done internally by the fitPP.fun. BTW, apart from predicted values, the function makes two graphs by default. The last piece is a swiss-knife function for model validation, globalval.fun. aux<-globalval.fun(obFPP=out,lint=2000, covariates=cbind(all.seconds),typeI='Disjoint', typeRes='Raw',typeResLV='Raw',resqqplot=FALSE) Among other things, the function divides the time into intervals, each lint samples long, so it is possible to create crude graphs that compare predicted intensity with observed intensity.
How to estimate Poisson process using R? (Or: how to use NHPoisson package?) Fitting a stationary Poisson process First of all it is important to realize, what sort of input data NHPoisson needs. Foremost, NHPoisson needs a list of indices of event moments. If we record time
15,734
Does it make sense for a partial correlation to be larger than a zero-order correlation?
Looking at the wikipedia page we have the partial correlation between $X$ and $Y$ given $Z$ is given by: $$\rho_{XY|Z}=\frac{\rho_{XY}-\rho_{XZ}\rho_{YZ}}{\sqrt{1-\rho_{XZ}^{2}}\sqrt{1-\rho_{YZ}^{2}}}>\rho_{XY}$$ So we simply require $$\rho_{XY}>\frac{\rho_{XZ}\rho_{YZ}}{1-\sqrt{1-\rho_{XZ}^{2}}\sqrt{1-\rho_{YZ}^{2}}}$$ The right hand side has a global minimum when $\rho_{XZ}=-\rho_{YZ}$. This global minimum is $-1$. I think this should explain what's going on. If the correlation between $Z$ and $Y$ is the opposite sign to the correlation between $Z$ and $X$ (but same magnitude), then the partial correlation between $X$ and $Y$ given $Z$ will always be greater than or equal to the correlation between $X$ and $Y$. In some sense the "plus" and "minus" conditional correlation tend to cancel out in the unconditional correlation. UPDATE I did some mucking around with R, and here is some code to generate a few plots. partial.plot <- function(r){ r.xz<- as.vector(rep(-99:99/100,199)) r.yz<- sort(r.xz) r.xy.z <- (r-r.xz*r.yz)/sqrt(1-r.xz^2)/sqrt(1-r.yz^2) tmp2 <- ifelse(abs(r.xy.z)<1,ifelse(abs(r.xy.z)<abs(r),2,1),0) r.all <-cbind(r.xz,r.yz,r.xy.z,tmp2) mycol <- tmp2 mycol[mycol==0] <- "red" mycol[mycol==1] <- "blue" mycol[mycol==2] <- "green" plot(r.xz,r.yz,type="n") text(r.all[,1],r.all[,2],labels=r.all[,4],col=mycol) } so you submit partial.plot(0.5) to see when a marginal correlation of 0.5 corresponds to in partial correlation. The plot is color coded so that red area represents the "impossible" partial correlation, blue area where $|\rho|<|\rho_{XY|Z}|<1$ and the green area where $1>|\rho|>|\rho_{XY|Z}|$ Below is an example for $\rho_{XY}=r=0.5$
Does it make sense for a partial correlation to be larger than a zero-order correlation?
Looking at the wikipedia page we have the partial correlation between $X$ and $Y$ given $Z$ is given by: $$\rho_{XY|Z}=\frac{\rho_{XY}-\rho_{XZ}\rho_{YZ}}{\sqrt{1-\rho_{XZ}^{2}}\sqrt{1-\rho_{YZ}^{2}}}
Does it make sense for a partial correlation to be larger than a zero-order correlation? Looking at the wikipedia page we have the partial correlation between $X$ and $Y$ given $Z$ is given by: $$\rho_{XY|Z}=\frac{\rho_{XY}-\rho_{XZ}\rho_{YZ}}{\sqrt{1-\rho_{XZ}^{2}}\sqrt{1-\rho_{YZ}^{2}}}>\rho_{XY}$$ So we simply require $$\rho_{XY}>\frac{\rho_{XZ}\rho_{YZ}}{1-\sqrt{1-\rho_{XZ}^{2}}\sqrt{1-\rho_{YZ}^{2}}}$$ The right hand side has a global minimum when $\rho_{XZ}=-\rho_{YZ}$. This global minimum is $-1$. I think this should explain what's going on. If the correlation between $Z$ and $Y$ is the opposite sign to the correlation between $Z$ and $X$ (but same magnitude), then the partial correlation between $X$ and $Y$ given $Z$ will always be greater than or equal to the correlation between $X$ and $Y$. In some sense the "plus" and "minus" conditional correlation tend to cancel out in the unconditional correlation. UPDATE I did some mucking around with R, and here is some code to generate a few plots. partial.plot <- function(r){ r.xz<- as.vector(rep(-99:99/100,199)) r.yz<- sort(r.xz) r.xy.z <- (r-r.xz*r.yz)/sqrt(1-r.xz^2)/sqrt(1-r.yz^2) tmp2 <- ifelse(abs(r.xy.z)<1,ifelse(abs(r.xy.z)<abs(r),2,1),0) r.all <-cbind(r.xz,r.yz,r.xy.z,tmp2) mycol <- tmp2 mycol[mycol==0] <- "red" mycol[mycol==1] <- "blue" mycol[mycol==2] <- "green" plot(r.xz,r.yz,type="n") text(r.all[,1],r.all[,2],labels=r.all[,4],col=mycol) } so you submit partial.plot(0.5) to see when a marginal correlation of 0.5 corresponds to in partial correlation. The plot is color coded so that red area represents the "impossible" partial correlation, blue area where $|\rho|<|\rho_{XY|Z}|<1$ and the green area where $1>|\rho|>|\rho_{XY|Z}|$ Below is an example for $\rho_{XY}=r=0.5$
Does it make sense for a partial correlation to be larger than a zero-order correlation? Looking at the wikipedia page we have the partial correlation between $X$ and $Y$ given $Z$ is given by: $$\rho_{XY|Z}=\frac{\rho_{XY}-\rho_{XZ}\rho_{YZ}}{\sqrt{1-\rho_{XZ}^{2}}\sqrt{1-\rho_{YZ}^{2}}}
15,735
Does it make sense for a partial correlation to be larger than a zero-order correlation?
People are more prone to think of confounders and mediators when it comes to these situations, in the sense that by adjusting for them you're blocking paths, removing indirect associations and therefore getting the direct correlation between the two variables of interest. The issue is that sometimes the variable we are adjusting for is neither a confounder or a mediator: It is a collider. Run the R code below: N = 1000 X <- rnorm(N) Y <- rnorm(N) Z <- X + Y + rnorm(N) In the code above, we're describing X and Y as independent variables but that, together, cause Z. The respective causal diagram would be the one below: As the name implies, a collider is a node whose incoming arrows collide with it. This path is blocked. You do not need to adjust for Z to measure the direct correlation between X and Y. But if you adjust, you open the path and you add spurious correlation to your estimate. Let's check this with some R code. library(ppcor) cor.test(X,Y) You will get a correlation of 0.04571798. pcor.test(X,Y,Z) You will get a partial correlation of -0.4641393 of X and Y adjusting for Z. We had barely anything, and now we have a reasonable correlation. One may think: Ok, but can we have barely anything and then a strong positive correlation with collider-adjustment? Sure! N <- 1000 X <- rnorm(N) Y <- rnorm(N) Z <- X - Y + rnorm(N) cor.test(X,Y) pcor.test(X,Y,Z) THe correlation between X and Y is -0.01578202 and the partial correlation of X and Y, given Z, is 0.5008563. We could check what happens with mediators and confounders. Ready? Let's make Z a confounder variable in respect to the association between X and Y. N = 1000 Z <- rnorm(N) X <- Z + rnorm(N) Y <- Z + rnorm(N) X <- Z -> Y cor.test(X,Y) 0.524119 library(ppcor) pcor.test(X,Y,Z) -0.02022428 See? You blocked the confounding path, in a way that there is practically no relationship between X and Y (which is expected, based on the way we created such relationships). Now for a mediator: N = 1000 X <- rnorm(N) Z <- X + rnorm(N) Y <- Z + rnorm(N) X -> Z -> Y cor.test(X,Y) 0.577676 pcor.test(X,Y,Z) -0.01984836 The take away message is that in such simple cases of unshielded triples, if we know the causal model, we should not adjust for the collider Z if we want the direct association between X and Y. We should adjust for the confounder Z if we want the direct association of X and Y and we could adjust for the mediator if we want the direct association, but sometimes we want the TOTAL association and therefore we could adjust for the mediator Z or not, depending on what is our goal.
Does it make sense for a partial correlation to be larger than a zero-order correlation?
People are more prone to think of confounders and mediators when it comes to these situations, in the sense that by adjusting for them you're blocking paths, removing indirect associations and therefo
Does it make sense for a partial correlation to be larger than a zero-order correlation? People are more prone to think of confounders and mediators when it comes to these situations, in the sense that by adjusting for them you're blocking paths, removing indirect associations and therefore getting the direct correlation between the two variables of interest. The issue is that sometimes the variable we are adjusting for is neither a confounder or a mediator: It is a collider. Run the R code below: N = 1000 X <- rnorm(N) Y <- rnorm(N) Z <- X + Y + rnorm(N) In the code above, we're describing X and Y as independent variables but that, together, cause Z. The respective causal diagram would be the one below: As the name implies, a collider is a node whose incoming arrows collide with it. This path is blocked. You do not need to adjust for Z to measure the direct correlation between X and Y. But if you adjust, you open the path and you add spurious correlation to your estimate. Let's check this with some R code. library(ppcor) cor.test(X,Y) You will get a correlation of 0.04571798. pcor.test(X,Y,Z) You will get a partial correlation of -0.4641393 of X and Y adjusting for Z. We had barely anything, and now we have a reasonable correlation. One may think: Ok, but can we have barely anything and then a strong positive correlation with collider-adjustment? Sure! N <- 1000 X <- rnorm(N) Y <- rnorm(N) Z <- X - Y + rnorm(N) cor.test(X,Y) pcor.test(X,Y,Z) THe correlation between X and Y is -0.01578202 and the partial correlation of X and Y, given Z, is 0.5008563. We could check what happens with mediators and confounders. Ready? Let's make Z a confounder variable in respect to the association between X and Y. N = 1000 Z <- rnorm(N) X <- Z + rnorm(N) Y <- Z + rnorm(N) X <- Z -> Y cor.test(X,Y) 0.524119 library(ppcor) pcor.test(X,Y,Z) -0.02022428 See? You blocked the confounding path, in a way that there is practically no relationship between X and Y (which is expected, based on the way we created such relationships). Now for a mediator: N = 1000 X <- rnorm(N) Z <- X + rnorm(N) Y <- Z + rnorm(N) X -> Z -> Y cor.test(X,Y) 0.577676 pcor.test(X,Y,Z) -0.01984836 The take away message is that in such simple cases of unshielded triples, if we know the causal model, we should not adjust for the collider Z if we want the direct association between X and Y. We should adjust for the confounder Z if we want the direct association of X and Y and we could adjust for the mediator if we want the direct association, but sometimes we want the TOTAL association and therefore we could adjust for the mediator Z or not, depending on what is our goal.
Does it make sense for a partial correlation to be larger than a zero-order correlation? People are more prone to think of confounders and mediators when it comes to these situations, in the sense that by adjusting for them you're blocking paths, removing indirect associations and therefo
15,736
Does it make sense for a partial correlation to be larger than a zero-order correlation?
I think that variable z in the question is a suppresor variable. I suggest having a look at: Tzelgov, J., & Henik, A. (1991).Suppression situations in psychological research: Definitions, implications, and applications, Psychological Bulletin, 109 (3), 524-536. http://doi.apa.org/psycinfo/1991-20289-001 See also: http://dionysus.psych.wisc.edu/lit/articles/TzelgovJ1991a.pdf HTH, dror
Does it make sense for a partial correlation to be larger than a zero-order correlation?
I think that variable z in the question is a suppresor variable. I suggest having a look at: Tzelgov, J., & Henik, A. (1991).Suppression situations in psychological research: Definitions, implication
Does it make sense for a partial correlation to be larger than a zero-order correlation? I think that variable z in the question is a suppresor variable. I suggest having a look at: Tzelgov, J., & Henik, A. (1991).Suppression situations in psychological research: Definitions, implications, and applications, Psychological Bulletin, 109 (3), 524-536. http://doi.apa.org/psycinfo/1991-20289-001 See also: http://dionysus.psych.wisc.edu/lit/articles/TzelgovJ1991a.pdf HTH, dror
Does it make sense for a partial correlation to be larger than a zero-order correlation? I think that variable z in the question is a suppresor variable. I suggest having a look at: Tzelgov, J., & Henik, A. (1991).Suppression situations in psychological research: Definitions, implication
15,737
Does it make sense for a partial correlation to be larger than a zero-order correlation?
I think you need to know about moderator and mediator variables. The classic paper is Baron and Kenny [cited 21,659 times] A moderator variable "In general terms, a moderator is a qualitative (e.g., sex, race, class) or quantitative (e.g., level of reward) variable that affects the direction and/or strength of the relation between an independent or predictor variable and a dependent or criterion variable. Specifically within a correlational analysis framework, a moderator is a third variable that affects the zero-order correlation between two other variables. ... In the more familiar analysis of variance (ANOVA) terms, a basic moderator effect can be represented as an interaction between a focal independent variable and a factor that specifies the appropriate conditions for its operation." p. 1174 A mediator variable "In general, a given variable may be said to function as a mediator to the extent that it accounts for the relation between the predictor and the criterion. Mediators explain how external physical events take on internal psychological significance. Whereas moderator variables specify when certain effects will hold, mediators speak to how or why such effects occur." p. 1176
Does it make sense for a partial correlation to be larger than a zero-order correlation?
I think you need to know about moderator and mediator variables. The classic paper is Baron and Kenny [cited 21,659 times] A moderator variable "In general terms, a moderator is a qualitative (e.g
Does it make sense for a partial correlation to be larger than a zero-order correlation? I think you need to know about moderator and mediator variables. The classic paper is Baron and Kenny [cited 21,659 times] A moderator variable "In general terms, a moderator is a qualitative (e.g., sex, race, class) or quantitative (e.g., level of reward) variable that affects the direction and/or strength of the relation between an independent or predictor variable and a dependent or criterion variable. Specifically within a correlational analysis framework, a moderator is a third variable that affects the zero-order correlation between two other variables. ... In the more familiar analysis of variance (ANOVA) terms, a basic moderator effect can be represented as an interaction between a focal independent variable and a factor that specifies the appropriate conditions for its operation." p. 1174 A mediator variable "In general, a given variable may be said to function as a mediator to the extent that it accounts for the relation between the predictor and the criterion. Mediators explain how external physical events take on internal psychological significance. Whereas moderator variables specify when certain effects will hold, mediators speak to how or why such effects occur." p. 1176
Does it make sense for a partial correlation to be larger than a zero-order correlation? I think you need to know about moderator and mediator variables. The classic paper is Baron and Kenny [cited 21,659 times] A moderator variable "In general terms, a moderator is a qualitative (e.g
15,738
Fitting models in R where coefficients are subject to linear restriction(s)?
Suppose your model is $ Y(t) = \beta_0 + \beta_1 \cdot X_1(t) + \beta_2 \cdot X_2(t) + \varepsilon(t)$ and you are planning to restrict the coefficients, for instance like: $ \beta_1 = 2 \beta_2$ inserting the restriction, rewriting the original regression model you will get $ Y(t) = \beta_0 + 2 \beta_2 \cdot X_1(t) + \beta_2 \cdot X_2(t) + \varepsilon(t) $ $ Y(t) = \beta_0 + \beta_2 (2 \cdot X_1(t) + X_2(t)) + \varepsilon(t)$ introduce a new variable $Z(t) = 2 \cdot X_1(t) + X_2(t)$ and your model with restriction will be $ Y(t) = \beta_0 + \beta_2 Z(t) + \varepsilon(t)$ In this way you can handle any exact restrictions, because the number of equal signs reduces the number of unknown parameters by the same number. Playing with R formulas you can do directly by I() function lm(formula = Y ~ I(1 + 2*X1) + X2 + X3 - 1, data = <your data>) lm(formula = Y ~ I(2*X1 + X2) + X3, data = <your data>)
Fitting models in R where coefficients are subject to linear restriction(s)?
Suppose your model is $ Y(t) = \beta_0 + \beta_1 \cdot X_1(t) + \beta_2 \cdot X_2(t) + \varepsilon(t)$ and you are planning to restrict the coefficients, for instance like: $ \beta_1 = 2 \beta_2$ inse
Fitting models in R where coefficients are subject to linear restriction(s)? Suppose your model is $ Y(t) = \beta_0 + \beta_1 \cdot X_1(t) + \beta_2 \cdot X_2(t) + \varepsilon(t)$ and you are planning to restrict the coefficients, for instance like: $ \beta_1 = 2 \beta_2$ inserting the restriction, rewriting the original regression model you will get $ Y(t) = \beta_0 + 2 \beta_2 \cdot X_1(t) + \beta_2 \cdot X_2(t) + \varepsilon(t) $ $ Y(t) = \beta_0 + \beta_2 (2 \cdot X_1(t) + X_2(t)) + \varepsilon(t)$ introduce a new variable $Z(t) = 2 \cdot X_1(t) + X_2(t)$ and your model with restriction will be $ Y(t) = \beta_0 + \beta_2 Z(t) + \varepsilon(t)$ In this way you can handle any exact restrictions, because the number of equal signs reduces the number of unknown parameters by the same number. Playing with R formulas you can do directly by I() function lm(formula = Y ~ I(1 + 2*X1) + X2 + X3 - 1, data = <your data>) lm(formula = Y ~ I(2*X1 + X2) + X3, data = <your data>)
Fitting models in R where coefficients are subject to linear restriction(s)? Suppose your model is $ Y(t) = \beta_0 + \beta_1 \cdot X_1(t) + \beta_2 \cdot X_2(t) + \varepsilon(t)$ and you are planning to restrict the coefficients, for instance like: $ \beta_1 = 2 \beta_2$ inse
15,739
Why binary crossentropy can be used as the loss function in autoencoders? [duplicate]
I thought a regression loss function such as mean squared error or mean absolute error must be used instead, which have a value of zero when labels and predictions are the same. That's exactly the misconception you have. You think that in order for a loss function to be used in a model like an autoencoder, it must have a value of zero when predictions equal to true labels. That's simply wrong since in most of the machine learning models (including autoencoders) we are trying to minimize a loss/cost function. And we are doing this with the assumption that the loss function we are using when reaches its minimum point, implies that the predictions and true labels are the same. That's the condition for using a function as a loss function in a model trained based on minimzing loss function. Note that the value of loss function at this minimum point may not be zero at all, however we don't care about this as long as it implies in that point predictions and true labels are the same. Now let's verify this is the case for binary crossentropy: we need to show that when we reach the minimum point of binary crossentropy it implies that $y = p$, i.e. predictions equal to true labels. To find the minimum point, we take the derivative with respect to $p$ and set it equal to zero (note that in the following calculations I have assumed that the $log$ is natural logarithm function to make calculations a little easier): $$\begin{align}&\frac{\partial BCE(y,p)}{\partial p} = 0\\ &\implies -y.\dfrac{1}{p} - (1-y).\dfrac{-1}{1-p} = 0\\ &\implies -y.(1-p) + (1-y).p = 0\\ &\implies -y + y.p + p - y.p = 0\\ &\implies p - y = 0\\ &\implies y = p \end{align}$$
Why binary crossentropy can be used as the loss function in autoencoders? [duplicate]
I thought a regression loss function such as mean squared error or mean absolute error must be used instead, which have a value of zero when labels and predictions are the same. That's exactly th
Why binary crossentropy can be used as the loss function in autoencoders? [duplicate] I thought a regression loss function such as mean squared error or mean absolute error must be used instead, which have a value of zero when labels and predictions are the same. That's exactly the misconception you have. You think that in order for a loss function to be used in a model like an autoencoder, it must have a value of zero when predictions equal to true labels. That's simply wrong since in most of the machine learning models (including autoencoders) we are trying to minimize a loss/cost function. And we are doing this with the assumption that the loss function we are using when reaches its minimum point, implies that the predictions and true labels are the same. That's the condition for using a function as a loss function in a model trained based on minimzing loss function. Note that the value of loss function at this minimum point may not be zero at all, however we don't care about this as long as it implies in that point predictions and true labels are the same. Now let's verify this is the case for binary crossentropy: we need to show that when we reach the minimum point of binary crossentropy it implies that $y = p$, i.e. predictions equal to true labels. To find the minimum point, we take the derivative with respect to $p$ and set it equal to zero (note that in the following calculations I have assumed that the $log$ is natural logarithm function to make calculations a little easier): $$\begin{align}&\frac{\partial BCE(y,p)}{\partial p} = 0\\ &\implies -y.\dfrac{1}{p} - (1-y).\dfrac{-1}{1-p} = 0\\ &\implies -y.(1-p) + (1-y).p = 0\\ &\implies -y + y.p + p - y.p = 0\\ &\implies p - y = 0\\ &\implies y = p \end{align}$$
Why binary crossentropy can be used as the loss function in autoencoders? [duplicate] I thought a regression loss function such as mean squared error or mean absolute error must be used instead, which have a value of zero when labels and predictions are the same. That's exactly th
15,740
Why binary crossentropy can be used as the loss function in autoencoders? [duplicate]
As @today pointed out, loss value doesn't have to be 0 when the solution is optimal, it is enough that it is minimal. One thing I would like to add is why one would prefer binary crossentropy over MSE. Normally, the activation function of the last layer is sigmoid, which can lead to loss saturation ("plateau"). This saturation could prevent gradient-based learning algorithms from making progress. In order to avoid it, it is then good to have a log in the objective function to undo the exp in sigmoid, and this is why binary crossentropy is preferred (because it uses log, unlike MSE). I have read this in the Deep Learning Book, but I now can't find where exactly (I think chapter 8).
Why binary crossentropy can be used as the loss function in autoencoders? [duplicate]
As @today pointed out, loss value doesn't have to be 0 when the solution is optimal, it is enough that it is minimal. One thing I would like to add is why one would prefer binary crossentropy over MSE
Why binary crossentropy can be used as the loss function in autoencoders? [duplicate] As @today pointed out, loss value doesn't have to be 0 when the solution is optimal, it is enough that it is minimal. One thing I would like to add is why one would prefer binary crossentropy over MSE. Normally, the activation function of the last layer is sigmoid, which can lead to loss saturation ("plateau"). This saturation could prevent gradient-based learning algorithms from making progress. In order to avoid it, it is then good to have a log in the objective function to undo the exp in sigmoid, and this is why binary crossentropy is preferred (because it uses log, unlike MSE). I have read this in the Deep Learning Book, but I now can't find where exactly (I think chapter 8).
Why binary crossentropy can be used as the loss function in autoencoders? [duplicate] As @today pointed out, loss value doesn't have to be 0 when the solution is optimal, it is enough that it is minimal. One thing I would like to add is why one would prefer binary crossentropy over MSE
15,741
What does a 'tractable' distribution mean?
To my best memory, I've never come across a formal definition for this in a statistical text, but I think you can stitch one together from a few contextual readings. Start with Bayesian Data Analysis, p. 261: Bayesian computation revolves around two steps: computation of the posterior distribution, $p(\theta|y)$, and computation of the posterior predictive distribution, $p(\hat y|y)$. So far we have considered examples where these could computed analytically in closed form[.] The obstacle is generally the marginal likelihood, the denominator on the right-hand side of Bayes' rule, which could involve an integral that cannot be analytically expressed. For a more I think you'll find wiki's article on closed-form expression helpful for context (emphasis mine): In mathematics, a closed-form expression is a mathematical expression that can be evaluated in a finite number of operations. It may contain constants, variables, certain "well-known" operations (e.g., + − × ÷), and functions (e.g., nth root, exponent, logarithm, trigonometric functions, and inverse hyperbolic functions), but usually no limit. The set of operations and functions admitted in a closed-form expression may vary with author and context. Problems are said to be tractable if they can be solved in terms of a closed-form expression. If you read on, you'll see a table of classes of expressions, and "Analytic expressions" includes several involved in the normalizing constants of exponential family distributions. E.g., the gamma function in the gamma distribution, and the Bessel function in the von-Mises Fisher. Meaning, we're willing to admit at least these into our definition of "tractability." (There may be other distributions that involve the classes of operations classified as "analytic expressions"; I confess I'm not familiar.)
What does a 'tractable' distribution mean?
To my best memory, I've never come across a formal definition for this in a statistical text, but I think you can stitch one together from a few contextual readings. Start with Bayesian Data Analysis,
What does a 'tractable' distribution mean? To my best memory, I've never come across a formal definition for this in a statistical text, but I think you can stitch one together from a few contextual readings. Start with Bayesian Data Analysis, p. 261: Bayesian computation revolves around two steps: computation of the posterior distribution, $p(\theta|y)$, and computation of the posterior predictive distribution, $p(\hat y|y)$. So far we have considered examples where these could computed analytically in closed form[.] The obstacle is generally the marginal likelihood, the denominator on the right-hand side of Bayes' rule, which could involve an integral that cannot be analytically expressed. For a more I think you'll find wiki's article on closed-form expression helpful for context (emphasis mine): In mathematics, a closed-form expression is a mathematical expression that can be evaluated in a finite number of operations. It may contain constants, variables, certain "well-known" operations (e.g., + − × ÷), and functions (e.g., nth root, exponent, logarithm, trigonometric functions, and inverse hyperbolic functions), but usually no limit. The set of operations and functions admitted in a closed-form expression may vary with author and context. Problems are said to be tractable if they can be solved in terms of a closed-form expression. If you read on, you'll see a table of classes of expressions, and "Analytic expressions" includes several involved in the normalizing constants of exponential family distributions. E.g., the gamma function in the gamma distribution, and the Bessel function in the von-Mises Fisher. Meaning, we're willing to admit at least these into our definition of "tractability." (There may be other distributions that involve the classes of operations classified as "analytic expressions"; I confess I'm not familiar.)
What does a 'tractable' distribution mean? To my best memory, I've never come across a formal definition for this in a statistical text, but I think you can stitch one together from a few contextual readings. Start with Bayesian Data Analysis,
15,742
What does a 'tractable' distribution mean?
In addition to Sean Easter's answer, I will try to shed some light from the perspective of computational cost. First of all, let's define what tractable and intractable problems are (Reference: http://www.cs.ucc.ie/~dgb/courses/toc/handout29.pdf). Tractable Problem: a problem that is solvable by a polynomial-time algorithm. The upper bound is polynomial. Intractable Problem: a problem that cannot be solved by a polynomial-time algorithm. The lower bound is exponential. From this perspective, a definition for tractable distribution is that it takes polynomial-time to calculate the probability of this distribution at any given point. If a distribution is in a closed-form expression, the probability of this distribution can definitely be calculated in polynomial-time, which, in the world of academia, means the distribution is tractable. Intractable distributions take equal to or more than exponential-time, which usually means that with existing computational resources, we can never calculate the probability at a given point with relatively "short" time (any time longer than polynomial-time is long...).
What does a 'tractable' distribution mean?
In addition to Sean Easter's answer, I will try to shed some light from the perspective of computational cost. First of all, let's define what tractable and intractable problems are (Reference: http:/
What does a 'tractable' distribution mean? In addition to Sean Easter's answer, I will try to shed some light from the perspective of computational cost. First of all, let's define what tractable and intractable problems are (Reference: http://www.cs.ucc.ie/~dgb/courses/toc/handout29.pdf). Tractable Problem: a problem that is solvable by a polynomial-time algorithm. The upper bound is polynomial. Intractable Problem: a problem that cannot be solved by a polynomial-time algorithm. The lower bound is exponential. From this perspective, a definition for tractable distribution is that it takes polynomial-time to calculate the probability of this distribution at any given point. If a distribution is in a closed-form expression, the probability of this distribution can definitely be calculated in polynomial-time, which, in the world of academia, means the distribution is tractable. Intractable distributions take equal to or more than exponential-time, which usually means that with existing computational resources, we can never calculate the probability at a given point with relatively "short" time (any time longer than polynomial-time is long...).
What does a 'tractable' distribution mean? In addition to Sean Easter's answer, I will try to shed some light from the perspective of computational cost. First of all, let's define what tractable and intractable problems are (Reference: http:/
15,743
What does a 'tractable' distribution mean?
A distribution is called tractable if any marginal probability induced by it can be computed in linear time
What does a 'tractable' distribution mean?
A distribution is called tractable if any marginal probability induced by it can be computed in linear time
What does a 'tractable' distribution mean? A distribution is called tractable if any marginal probability induced by it can be computed in linear time
What does a 'tractable' distribution mean? A distribution is called tractable if any marginal probability induced by it can be computed in linear time
15,744
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and how this makes linear separation possible
Let $h(x)$ be the projection to high dimension space $\mathcal{F}$. Basically the kernel function $K(x_1,x_2)=\langle h(x_1),h(x_2)\rangle$, which is the inner-product. So it's not used to project data points, but rather an outcome of the projection. It can be considered a measure of similarity, but in an SVM, it's more than that. The optimization for finding the best separating hyperplane in $\mathcal{F}$ involves $h(x)$ only through the inner-product form. That's to say, if you know $K(\cdot,\cdot)$, you don't need to know the exact form of $h(x)$, which makes the optimization easier. Each kernel $K(\cdot,\cdot)$ has a corresponding $h(x)$ as well. So if you're using an SVM with that kernel, then you're implicitly finding the linear decision line in the space that $h(x)$ maps into. Chapter 12 of Elements of Statistical Learning gives a brief introduction to SVM . This gives more detail about the connection between kernel and feature mapping: http://statweb.stanford.edu/~tibs/ElemStatLearn/
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and
Let $h(x)$ be the projection to high dimension space $\mathcal{F}$. Basically the kernel function $K(x_1,x_2)=\langle h(x_1),h(x_2)\rangle$, which is the inner-product. So it's not used to project da
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and how this makes linear separation possible Let $h(x)$ be the projection to high dimension space $\mathcal{F}$. Basically the kernel function $K(x_1,x_2)=\langle h(x_1),h(x_2)\rangle$, which is the inner-product. So it's not used to project data points, but rather an outcome of the projection. It can be considered a measure of similarity, but in an SVM, it's more than that. The optimization for finding the best separating hyperplane in $\mathcal{F}$ involves $h(x)$ only through the inner-product form. That's to say, if you know $K(\cdot,\cdot)$, you don't need to know the exact form of $h(x)$, which makes the optimization easier. Each kernel $K(\cdot,\cdot)$ has a corresponding $h(x)$ as well. So if you're using an SVM with that kernel, then you're implicitly finding the linear decision line in the space that $h(x)$ maps into. Chapter 12 of Elements of Statistical Learning gives a brief introduction to SVM . This gives more detail about the connection between kernel and feature mapping: http://statweb.stanford.edu/~tibs/ElemStatLearn/
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and Let $h(x)$ be the projection to high dimension space $\mathcal{F}$. Basically the kernel function $K(x_1,x_2)=\langle h(x_1),h(x_2)\rangle$, which is the inner-product. So it's not used to project da
15,745
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and how this makes linear separation possible
The useful properties of kernel SVM are not universal - they depend on the choice of kernel. To get intuition it's helpful to look at one of the most commonly used kernels, the Gaussian kernel. Remarkably, this kernel turns SVM into something very much like a k-nearest neighbor classifier. This answer explains the following: Why perfect separation of positive and negative training data is always possible with a Gaussian kernel of sufficiently small bandwidth (at the cost of overfitting) How this separation may be interpreted as linear in a feature space. How the kernel is used to construct the mapping from data space to feature space. Spoiler: the feature space is a very mathematically abstract object, with an unusual abstract inner product based on the kernel. 1. Achieving perfect separation Perfect separation is always possible with a Gaussian kernel because of the kernel's locality properties, which lead to an arbitrarily flexible decision boundary. For sufficiently small kernel bandwidth, the decision boundary will look like you just drew little circles around the points whenever they are needed to separate the positive and negative examples: (Credit: Andrew Ng's online machine learning course). So, why does this occur from a mathematical perspective? Consider the standard setup: you have a Gaussian kernel $K(\mathbf{x},\mathbf{z}) = \exp(- ||\mathbf{x}-\mathbf{z}||^2 / \sigma^2)$ and training data $(\mathbf{x}^{(1)},y^{(1)}), (\mathbf{x}^{(2)},y^{(2)}), \ldots, (\mathbf{x}^{(n)},y^{(n)})$ where the $y^{(i)}$ values are $\pm 1$. We want to learn a classifier function $$\hat{y}(\mathbf{x}) = \sum_i w_i y^{(i)} K(\mathbf{x}^{(i)},\mathbf{x})$$ Now how will we ever assign the weights $w_i$? Do we need infinite dimensional spaces and a quadratic programming algorithm? No, because I just want to show that I can separate the points perfectly. So I make $\sigma$ a billion times smaller than the smallest separation $||\mathbf{x}^{(i)} - \mathbf{x}^{(j)}||$ between any two training examples, and I just set $w_i = 1$. This means that all the training points are a billion sigmas apart as far as the kernel is concerned, and each point completely controls the sign of $\hat{y}$ in its neighborhood. Formally, we have $$ \hat{y}(\mathbf{x}^{(k)}) = \sum_{i=1}^n y^{(k)} K(\mathbf{x}^{(i)},\mathbf{x}^{(k)}) = y^{(k)} K(\mathbf{x}^{(k)},\mathbf{x}^{(k)}) + \sum_{i \neq k} y^{(i)} K(\mathbf{x}^{(i)},\mathbf{x}^{(k)}) = y^{(k)} + \epsilon$$ where $\epsilon$ is some arbitrarily tiny value. We know $\epsilon$ is tiny because $\mathbf{x}^{(k)}$ is a billion sigmas away from any other point, so for all $i \neq k$ we have $$K(\mathbf{x}^{(i)},\mathbf{x}^{(k)}) = \exp(- ||\mathbf{x}^{(i)} - \mathbf{x}^{(k)}||^2 / \sigma^2) \approx 0.$$ Since $\epsilon$ is so small, $\hat{y}(\mathbf{x}^{(k)})$ definitely has the same sign as $y^{(k)}$, and the classifier achieves perfect accuracy on the training data. In practice this would be terribly overfitting but it shows the tremendous flexibility of the Gaussian kernel SVM, and how it can act very similar to a nearest neighbor classifier. 2. Kernel SVM learning as linear separation The fact that this can be interpreted as "perfect linear separation in an infinite dimensional feature space" comes from the kernel trick, which allows you to interpret the kernel as an abstract inner product some new feature space: $$K(\mathbf{x}^{(i)},\mathbf{x}^{(j)}) = \langle\Phi(\mathbf{x}^{(i)}),\Phi(\mathbf{x}^{(j)})\rangle$$ where $\Phi(\mathbf{x})$ is the mapping from the data space into the feature space. It follows immediately that the $\hat{y}(\mathbf{x})$ function as a linear function in the feature space: $$ \hat{y}(\mathbf{x}) = \sum_i w_i y^{(i)} \langle\Phi(\mathbf{x}^{(i)}),\Phi(\mathbf{x})\rangle = L(\Phi(\mathbf{x}))$$ where the linear function $L(\mathbf{v})$ is defined on feature space vectors $\mathbf{v}$ as $$ L(\mathbf{v}) = \sum_i w_i y^{(i)} \langle\Phi(\mathbf{x}^{(i)}),\mathbf{v}\rangle$$ This function is linear in $\mathbf{v}$ because it's just a linear combination of inner products with fixed vectors. In the feature space, the decision boundary $\hat{y}(\mathbf{x}) = 0$ is just $L(\mathbf{v}) = 0$, the level set of a linear function. This is the very definition of a hyperplane in the feature space. 3. How the kernel is used to construct the feature space Kernel methods never actually "find" or "compute" the feature space or the mapping $\Phi$ explicitly. Kernel learning methods such as SVM do not need them to work; they only need the kernel function $K$. It is possible to write down a formula for $\Phi$ but the feature space it maps to is quite abstract and is only really used for proving theoretical results about SVM. If you're still interested, here's how it works. Basically we define an abstract vector space $V$ where each vector is a function from $\mathcal{X}$ to $\mathbb{R}$. A vector $f$ in $V$ is a function formed from a finite linear combination of kernel slices: $$f(\mathbf{x}) = \sum_{i=1}^n \alpha_i K(\mathbf{x}^{(i)},\mathbf{x})$$ (Here the $\mathbf{x}^{(i)}$ are just an arbitrary set of points and need not be the same as the training set.) It is convenient to write $f$ more compactly as $$f = \sum_{i=1}^n \alpha_i K_{\mathbf{x}^{(i)}}$$ where $K_\mathbf{x}(\mathbf{y}) = K(\mathbf{x},\mathbf{y})$ is a function giving a "slice" of the kernel at $\mathbf{x}$. The inner product on the space is not the ordinary dot product, but an abstract inner product based on the kernel: $$\langle \sum_{i=1}^n \alpha_i K_{\mathbf{x}^{(i)}}, \sum_{j=1}^n \beta_j K_{\mathbf{x}^{(j)}} \rangle = \sum_{i,j} \alpha_i \beta_j K(\mathbf{x}^{(i)},\mathbf{x}^{(j)})$$ This definition is very deliberate: its construction ensures the identity we need for linear separation, $\langle \Phi(\mathbf{x}), \Phi(\mathbf{y}) \rangle = K(\mathbf{x},\mathbf{y})$. With the feature space defined in this way, $\Phi$ is a mapping $\mathcal{X} \rightarrow V$, taking each point $\mathbf{x}$ to the "kernel slice" at that point: $$\Phi(\mathbf{x}) = K_\mathbf{x}, \quad \text{where} \quad K_\mathbf{x}(\mathbf{y}) = K(\mathbf{x},\mathbf{y}). $$ You can prove that $V$ is an inner product space when $K$ is a positive definite kernel. See this paper for details.
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and
The useful properties of kernel SVM are not universal - they depend on the choice of kernel. To get intuition it's helpful to look at one of the most commonly used kernels, the Gaussian kernel. Remark
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and how this makes linear separation possible The useful properties of kernel SVM are not universal - they depend on the choice of kernel. To get intuition it's helpful to look at one of the most commonly used kernels, the Gaussian kernel. Remarkably, this kernel turns SVM into something very much like a k-nearest neighbor classifier. This answer explains the following: Why perfect separation of positive and negative training data is always possible with a Gaussian kernel of sufficiently small bandwidth (at the cost of overfitting) How this separation may be interpreted as linear in a feature space. How the kernel is used to construct the mapping from data space to feature space. Spoiler: the feature space is a very mathematically abstract object, with an unusual abstract inner product based on the kernel. 1. Achieving perfect separation Perfect separation is always possible with a Gaussian kernel because of the kernel's locality properties, which lead to an arbitrarily flexible decision boundary. For sufficiently small kernel bandwidth, the decision boundary will look like you just drew little circles around the points whenever they are needed to separate the positive and negative examples: (Credit: Andrew Ng's online machine learning course). So, why does this occur from a mathematical perspective? Consider the standard setup: you have a Gaussian kernel $K(\mathbf{x},\mathbf{z}) = \exp(- ||\mathbf{x}-\mathbf{z}||^2 / \sigma^2)$ and training data $(\mathbf{x}^{(1)},y^{(1)}), (\mathbf{x}^{(2)},y^{(2)}), \ldots, (\mathbf{x}^{(n)},y^{(n)})$ where the $y^{(i)}$ values are $\pm 1$. We want to learn a classifier function $$\hat{y}(\mathbf{x}) = \sum_i w_i y^{(i)} K(\mathbf{x}^{(i)},\mathbf{x})$$ Now how will we ever assign the weights $w_i$? Do we need infinite dimensional spaces and a quadratic programming algorithm? No, because I just want to show that I can separate the points perfectly. So I make $\sigma$ a billion times smaller than the smallest separation $||\mathbf{x}^{(i)} - \mathbf{x}^{(j)}||$ between any two training examples, and I just set $w_i = 1$. This means that all the training points are a billion sigmas apart as far as the kernel is concerned, and each point completely controls the sign of $\hat{y}$ in its neighborhood. Formally, we have $$ \hat{y}(\mathbf{x}^{(k)}) = \sum_{i=1}^n y^{(k)} K(\mathbf{x}^{(i)},\mathbf{x}^{(k)}) = y^{(k)} K(\mathbf{x}^{(k)},\mathbf{x}^{(k)}) + \sum_{i \neq k} y^{(i)} K(\mathbf{x}^{(i)},\mathbf{x}^{(k)}) = y^{(k)} + \epsilon$$ where $\epsilon$ is some arbitrarily tiny value. We know $\epsilon$ is tiny because $\mathbf{x}^{(k)}$ is a billion sigmas away from any other point, so for all $i \neq k$ we have $$K(\mathbf{x}^{(i)},\mathbf{x}^{(k)}) = \exp(- ||\mathbf{x}^{(i)} - \mathbf{x}^{(k)}||^2 / \sigma^2) \approx 0.$$ Since $\epsilon$ is so small, $\hat{y}(\mathbf{x}^{(k)})$ definitely has the same sign as $y^{(k)}$, and the classifier achieves perfect accuracy on the training data. In practice this would be terribly overfitting but it shows the tremendous flexibility of the Gaussian kernel SVM, and how it can act very similar to a nearest neighbor classifier. 2. Kernel SVM learning as linear separation The fact that this can be interpreted as "perfect linear separation in an infinite dimensional feature space" comes from the kernel trick, which allows you to interpret the kernel as an abstract inner product some new feature space: $$K(\mathbf{x}^{(i)},\mathbf{x}^{(j)}) = \langle\Phi(\mathbf{x}^{(i)}),\Phi(\mathbf{x}^{(j)})\rangle$$ where $\Phi(\mathbf{x})$ is the mapping from the data space into the feature space. It follows immediately that the $\hat{y}(\mathbf{x})$ function as a linear function in the feature space: $$ \hat{y}(\mathbf{x}) = \sum_i w_i y^{(i)} \langle\Phi(\mathbf{x}^{(i)}),\Phi(\mathbf{x})\rangle = L(\Phi(\mathbf{x}))$$ where the linear function $L(\mathbf{v})$ is defined on feature space vectors $\mathbf{v}$ as $$ L(\mathbf{v}) = \sum_i w_i y^{(i)} \langle\Phi(\mathbf{x}^{(i)}),\mathbf{v}\rangle$$ This function is linear in $\mathbf{v}$ because it's just a linear combination of inner products with fixed vectors. In the feature space, the decision boundary $\hat{y}(\mathbf{x}) = 0$ is just $L(\mathbf{v}) = 0$, the level set of a linear function. This is the very definition of a hyperplane in the feature space. 3. How the kernel is used to construct the feature space Kernel methods never actually "find" or "compute" the feature space or the mapping $\Phi$ explicitly. Kernel learning methods such as SVM do not need them to work; they only need the kernel function $K$. It is possible to write down a formula for $\Phi$ but the feature space it maps to is quite abstract and is only really used for proving theoretical results about SVM. If you're still interested, here's how it works. Basically we define an abstract vector space $V$ where each vector is a function from $\mathcal{X}$ to $\mathbb{R}$. A vector $f$ in $V$ is a function formed from a finite linear combination of kernel slices: $$f(\mathbf{x}) = \sum_{i=1}^n \alpha_i K(\mathbf{x}^{(i)},\mathbf{x})$$ (Here the $\mathbf{x}^{(i)}$ are just an arbitrary set of points and need not be the same as the training set.) It is convenient to write $f$ more compactly as $$f = \sum_{i=1}^n \alpha_i K_{\mathbf{x}^{(i)}}$$ where $K_\mathbf{x}(\mathbf{y}) = K(\mathbf{x},\mathbf{y})$ is a function giving a "slice" of the kernel at $\mathbf{x}$. The inner product on the space is not the ordinary dot product, but an abstract inner product based on the kernel: $$\langle \sum_{i=1}^n \alpha_i K_{\mathbf{x}^{(i)}}, \sum_{j=1}^n \beta_j K_{\mathbf{x}^{(j)}} \rangle = \sum_{i,j} \alpha_i \beta_j K(\mathbf{x}^{(i)},\mathbf{x}^{(j)})$$ This definition is very deliberate: its construction ensures the identity we need for linear separation, $\langle \Phi(\mathbf{x}), \Phi(\mathbf{y}) \rangle = K(\mathbf{x},\mathbf{y})$. With the feature space defined in this way, $\Phi$ is a mapping $\mathcal{X} \rightarrow V$, taking each point $\mathbf{x}$ to the "kernel slice" at that point: $$\Phi(\mathbf{x}) = K_\mathbf{x}, \quad \text{where} \quad K_\mathbf{x}(\mathbf{y}) = K(\mathbf{x},\mathbf{y}). $$ You can prove that $V$ is an inner product space when $K$ is a positive definite kernel. See this paper for details.
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and The useful properties of kernel SVM are not universal - they depend on the choice of kernel. To get intuition it's helpful to look at one of the most commonly used kernels, the Gaussian kernel. Remark
15,746
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and how this makes linear separation possible
For the background and the notations I refer to How to calculate decision boundary from support vectors?. So the features in the 'original' space are the vectors $x_i$, the binary outcome $y_i \in \{-1, +1\}$ and the Lagrange multipliers are $\alpha_i$. As said by @Lii (+1) the Kernel can be written as $K(x,y)=h(x) \cdot h(y)$ ('$\cdot$' represents the inner product. I will try to give some 'intuitive' explanation of what this $h$ looks like, so this answer is no formal proof, it just wants to give some feeling of how I think that this works. Do not hesitate to correct me if I am wrong. I have to 'transform' my feature space (so my $x_i$) into some 'new' feature space in which the linear separation will be solved. For each observation $x_i$, I define functions $\phi_i(x)=K(x_i,x)$, so I have a function $\phi_i$ for each element of my training sample. These functions $\phi_i$ span a vector space. The vector space spanned by the $\phi_i$, note it $V=span(\phi_{i, i=1,2,\dots N})$. I will try to argue that is the vector space in which linear separation will be possible. By definition of the span, each vector in the vector space $V$ can be written as as a linear combination of the $\phi_i$, i.e.: $\sum_{i=1}^N \gamma_i \phi_i$, where $\gamma_i$ are real numbers. $N$ is the size of the training sample and therefore the dimension of the vector space $V$ can go up to $N$, depending on whether the $\phi_i$ are linear independent. As $\phi_i(x)=K(x_i,x)$ (see supra, we defined $\phi$ in this way), this means that the dimension of $V$ depends on the kernel used and can go up to the size of the training sample. The transformation, that maps my original feature space to $V$ is defined as $\Phi: x_i \to \phi(x)=K(x_i, x)$. This map $\Phi$ maps my original feature space onto a vector space that can have a dimension that goed up to the size of my training sample. Obviously, this transformation (a) depends on the kernel, (b) depends on the values $x_i$ in the training sample and (c) can, depending on my kernel, have a dimension that goes up to the size of my training sample and (d) the vectors of $V$ look like $\sum_{i=1}^N \gamma_i \phi_i$, where $\gamma_i$, $\gamma_i$ are real numbers. Looking at the function $f(x)$ in How to calculate decision boundary from support vectors? it can be seen that $f(x)=\sum_i y_i \alpha_i \phi_i(x)+b$. In other words, $f(x)$ is a linear combination of the $\phi_i$ and this is a linear separator in the V-space : it is a particular choice of the $\gamma_i$ namely $\gamma_i=\alpha_i y_i$ ! The $y_i$ are known from our observations, the $\alpha_i$ are the Lagrange multipliers that the SVM has found. In other words SVM find, through the use of a kernel and by solving a quadratic programming problem, a linear separation in the $V$-spave. This is my intuitive understanding of how the 'kernel trick' allows one to 'implicitly' transform the original feature space into a new feature space $V$, with a different dimension. This dimension depends on the kernel you use and for the RBF kernel this dimension can go up to the size of the training sample. So kernels are a technique that allows SVM to transform your feature space , see also What makes the Gaussian kernel so magical for PCA, and also in general?
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and
For the background and the notations I refer to How to calculate decision boundary from support vectors?. So the features in the 'original' space are the vectors $x_i$, the binary outcome $y_i \in \{
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and how this makes linear separation possible For the background and the notations I refer to How to calculate decision boundary from support vectors?. So the features in the 'original' space are the vectors $x_i$, the binary outcome $y_i \in \{-1, +1\}$ and the Lagrange multipliers are $\alpha_i$. As said by @Lii (+1) the Kernel can be written as $K(x,y)=h(x) \cdot h(y)$ ('$\cdot$' represents the inner product. I will try to give some 'intuitive' explanation of what this $h$ looks like, so this answer is no formal proof, it just wants to give some feeling of how I think that this works. Do not hesitate to correct me if I am wrong. I have to 'transform' my feature space (so my $x_i$) into some 'new' feature space in which the linear separation will be solved. For each observation $x_i$, I define functions $\phi_i(x)=K(x_i,x)$, so I have a function $\phi_i$ for each element of my training sample. These functions $\phi_i$ span a vector space. The vector space spanned by the $\phi_i$, note it $V=span(\phi_{i, i=1,2,\dots N})$. I will try to argue that is the vector space in which linear separation will be possible. By definition of the span, each vector in the vector space $V$ can be written as as a linear combination of the $\phi_i$, i.e.: $\sum_{i=1}^N \gamma_i \phi_i$, where $\gamma_i$ are real numbers. $N$ is the size of the training sample and therefore the dimension of the vector space $V$ can go up to $N$, depending on whether the $\phi_i$ are linear independent. As $\phi_i(x)=K(x_i,x)$ (see supra, we defined $\phi$ in this way), this means that the dimension of $V$ depends on the kernel used and can go up to the size of the training sample. The transformation, that maps my original feature space to $V$ is defined as $\Phi: x_i \to \phi(x)=K(x_i, x)$. This map $\Phi$ maps my original feature space onto a vector space that can have a dimension that goed up to the size of my training sample. Obviously, this transformation (a) depends on the kernel, (b) depends on the values $x_i$ in the training sample and (c) can, depending on my kernel, have a dimension that goes up to the size of my training sample and (d) the vectors of $V$ look like $\sum_{i=1}^N \gamma_i \phi_i$, where $\gamma_i$, $\gamma_i$ are real numbers. Looking at the function $f(x)$ in How to calculate decision boundary from support vectors? it can be seen that $f(x)=\sum_i y_i \alpha_i \phi_i(x)+b$. In other words, $f(x)$ is a linear combination of the $\phi_i$ and this is a linear separator in the V-space : it is a particular choice of the $\gamma_i$ namely $\gamma_i=\alpha_i y_i$ ! The $y_i$ are known from our observations, the $\alpha_i$ are the Lagrange multipliers that the SVM has found. In other words SVM find, through the use of a kernel and by solving a quadratic programming problem, a linear separation in the $V$-spave. This is my intuitive understanding of how the 'kernel trick' allows one to 'implicitly' transform the original feature space into a new feature space $V$, with a different dimension. This dimension depends on the kernel you use and for the RBF kernel this dimension can go up to the size of the training sample. So kernels are a technique that allows SVM to transform your feature space , see also What makes the Gaussian kernel so magical for PCA, and also in general?
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and For the background and the notations I refer to How to calculate decision boundary from support vectors?. So the features in the 'original' space are the vectors $x_i$, the binary outcome $y_i \in \{
15,747
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and how this makes linear separation possible
Transform predictors (input data) to a high-dimensional feature space. It is sufficient to just specify the kernel for this step and the data is never explicitly transformed to the feature space. This process is commonly known as the kernel trick. Let me explain it. The kernel trick is the key here. Consider the case of a Radial Basis Function (RBF) Kernel here. It transforms the input to infinite dimensional space. The transformation of input $x$ to $\phi(x)$ can be represented as shown below (taken from http://www.csie.ntu.edu.tw/~cjlin/talks/kuleuven_svm.pdf) The input space is finite dimensional but the transformed space is infinite dimensional. Transforming the input to an infinite dimensional space is something that happens as a result of the kernel trick. Here $x$ which is the input and $\phi$ is the transformed input. But $\phi$ is not computed as it is, instead the product $\phi(x_i)^T\phi(x)$ is computed which is just the exponential of the norm between $x_i$ and $x$. There is a related question Feature map for the Gaussian kernel to which there is a nice answer https://stats.stackexchange.com/a/69767/86202. The output or decision function is a function of the kernel matrix $K(x_i,x)=\phi(x_i)^T\phi(x)$ and not of the input $x$ or transformed input $\phi$ directly.
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and
Transform predictors (input data) to a high-dimensional feature space. It is sufficient to just specify the kernel for this step and the data is never explicitly transformed to the feature space. This
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and how this makes linear separation possible Transform predictors (input data) to a high-dimensional feature space. It is sufficient to just specify the kernel for this step and the data is never explicitly transformed to the feature space. This process is commonly known as the kernel trick. Let me explain it. The kernel trick is the key here. Consider the case of a Radial Basis Function (RBF) Kernel here. It transforms the input to infinite dimensional space. The transformation of input $x$ to $\phi(x)$ can be represented as shown below (taken from http://www.csie.ntu.edu.tw/~cjlin/talks/kuleuven_svm.pdf) The input space is finite dimensional but the transformed space is infinite dimensional. Transforming the input to an infinite dimensional space is something that happens as a result of the kernel trick. Here $x$ which is the input and $\phi$ is the transformed input. But $\phi$ is not computed as it is, instead the product $\phi(x_i)^T\phi(x)$ is computed which is just the exponential of the norm between $x_i$ and $x$. There is a related question Feature map for the Gaussian kernel to which there is a nice answer https://stats.stackexchange.com/a/69767/86202. The output or decision function is a function of the kernel matrix $K(x_i,x)=\phi(x_i)^T\phi(x)$ and not of the input $x$ or transformed input $\phi$ directly.
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and Transform predictors (input data) to a high-dimensional feature space. It is sufficient to just specify the kernel for this step and the data is never explicitly transformed to the feature space. This
15,748
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and how this makes linear separation possible
Mapping to a higher dimension is merely a trick to solve a problem that is defined in the original dimension; so concerns such as overfitting your data by going into a dimension with too many degrees of freedom are not a byproduct of the mapping process, but are inherent in your problem definition. Basically, all that mapping does is converting conditional classification in the original dimension to a plane definition in the higher dimension, and because there is a 1 to 1 relationship between the plane in the higher dimension and your conditions in the lower dimension, you can always move between the two. Taking the problem of overfitting, clearly, you can overfit any set of observations by defining enough conditions to isolate each observation into its own class, which is equivalent of mapping your data to (n-1)D where n is the number of your observations. Taking the simplest problem, where your observations are [[1,-1], [0,0], [1,1]] [[feature, value]], by moving into the 2D dimension and separating your data with a line, your are simply turning the conditional classification of feature < 1 && feature > -1 : 0 to defining a line that passes through (-1 + epsilon, 1 - epsilon). If you had more data points and needed more condition, you just needed to add one more degree of freedom to your higher dimension by each new condition that your define. You can replace the process of mapping to a higher dimension with any process that provides you with a 1 to 1 relationship between the conditions and the degrees of freedom of your new problem. Kernel tricks simply do that.
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and
Mapping to a higher dimension is merely a trick to solve a problem that is defined in the original dimension; so concerns such as overfitting your data by going into a dimension with too many degrees
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and how this makes linear separation possible Mapping to a higher dimension is merely a trick to solve a problem that is defined in the original dimension; so concerns such as overfitting your data by going into a dimension with too many degrees of freedom are not a byproduct of the mapping process, but are inherent in your problem definition. Basically, all that mapping does is converting conditional classification in the original dimension to a plane definition in the higher dimension, and because there is a 1 to 1 relationship between the plane in the higher dimension and your conditions in the lower dimension, you can always move between the two. Taking the problem of overfitting, clearly, you can overfit any set of observations by defining enough conditions to isolate each observation into its own class, which is equivalent of mapping your data to (n-1)D where n is the number of your observations. Taking the simplest problem, where your observations are [[1,-1], [0,0], [1,1]] [[feature, value]], by moving into the 2D dimension and separating your data with a line, your are simply turning the conditional classification of feature < 1 && feature > -1 : 0 to defining a line that passes through (-1 + epsilon, 1 - epsilon). If you had more data points and needed more condition, you just needed to add one more degree of freedom to your higher dimension by each new condition that your define. You can replace the process of mapping to a higher dimension with any process that provides you with a 1 to 1 relationship between the conditions and the degrees of freedom of your new problem. Kernel tricks simply do that.
Kernel SVM: I want an intuitive understanding of mapping to a higher-dimensional feature space, and Mapping to a higher dimension is merely a trick to solve a problem that is defined in the original dimension; so concerns such as overfitting your data by going into a dimension with too many degrees
15,749
How does regularization reduce overfitting? [duplicate]
This is related to the Bias-Variance tradeoff. The expected error can be decomposed as $$ \mathrm{E}[(y - f(x))^2] = \mathrm{Bias}(f(x))^2 + \mathrm{Var}(f(x)) + \sigma^2, $$ where the bias is the systematic deviation of our estimator, $f$, from the true value, i.e. $E[f^* - f]$, where $f^*$ is the true estimator, and the variance is essentially how sensitive our estimator is to deviations in the training set. The $\sigma^2$ term is the residual noise term; this term is irreducible and can not be made to impact less with mathematics (if your samples are noise, there might be something you can do in regards to collecting the data, though). Overfitting happens when your model is too complicated to generalise for new data. When your model fits your data perfectly, it is unlikely to fit new data well. Underfit happens when your model is not complicated enough. This introduces a bias in the model, such that there is systematic deviation from the true underlying estimator. Regularization attemts to reduce the variance of the estimator by simplifying it, something that will increase the bias, in such a way that the expected error decreases. Often this is done in cases when the problem is ill-posed, e.g. when the number of parameters is greater than the number of samples. Whether or not you obtain a successful reduction in expected variance depends on your estimator and the regularisation used. For instance, for multiple linear regression and $\ell_2$ regularisation, it is possible to prove that there is a solution that reduces the expected error by properly selecting the regularisation parameter.
How does regularization reduce overfitting? [duplicate]
This is related to the Bias-Variance tradeoff. The expected error can be decomposed as $$ \mathrm{E}[(y - f(x))^2] = \mathrm{Bias}(f(x))^2 + \mathrm{Var}(f(x)) + \sigma^2, $$ where the bias is the
How does regularization reduce overfitting? [duplicate] This is related to the Bias-Variance tradeoff. The expected error can be decomposed as $$ \mathrm{E}[(y - f(x))^2] = \mathrm{Bias}(f(x))^2 + \mathrm{Var}(f(x)) + \sigma^2, $$ where the bias is the systematic deviation of our estimator, $f$, from the true value, i.e. $E[f^* - f]$, where $f^*$ is the true estimator, and the variance is essentially how sensitive our estimator is to deviations in the training set. The $\sigma^2$ term is the residual noise term; this term is irreducible and can not be made to impact less with mathematics (if your samples are noise, there might be something you can do in regards to collecting the data, though). Overfitting happens when your model is too complicated to generalise for new data. When your model fits your data perfectly, it is unlikely to fit new data well. Underfit happens when your model is not complicated enough. This introduces a bias in the model, such that there is systematic deviation from the true underlying estimator. Regularization attemts to reduce the variance of the estimator by simplifying it, something that will increase the bias, in such a way that the expected error decreases. Often this is done in cases when the problem is ill-posed, e.g. when the number of parameters is greater than the number of samples. Whether or not you obtain a successful reduction in expected variance depends on your estimator and the regularisation used. For instance, for multiple linear regression and $\ell_2$ regularisation, it is possible to prove that there is a solution that reduces the expected error by properly selecting the regularisation parameter.
How does regularization reduce overfitting? [duplicate] This is related to the Bias-Variance tradeoff. The expected error can be decomposed as $$ \mathrm{E}[(y - f(x))^2] = \mathrm{Bias}(f(x))^2 + \mathrm{Var}(f(x)) + \sigma^2, $$ where the bias is the
15,750
From exp (coefficients) to Odds Ratio and their interpretation in Logistic Regression with factors
I've been working on answering my question by calculating manually the odds and odds ratios: Acceptance blue red Grand Total 0 158 102 260 1 112 177 289 Total 270 279 549 So the Odds Ratio of getting into the school of Red over Blue is: $$ \frac{\rm Odds\ Accept\ If\ Red}{\rm Odds\ Acccept\ If\ Blue} = \frac{^{177}/_{102}}{^{112}/_{158}} = \frac {1.7353}{0.7089} = 2.448 $$ And this is the Backgroundredreturn of: fit <- glm(Accepted~Background, data=dat, family="binomial") exp(cbind(Odds_and_OR=coef(fit), confint(fit))) Odds_and_OR 2.5 % 97.5 % (Intercept) 0.7088608 0.5553459 0.9017961 Backgroundred 2.4480042 1.7397640 3.4595454 At the same time, the (Intercept)corresponds to the numerator of the odds ratio, which is exactly the odds of getting in being of 'blue' family background: $112/158 = 0.7089$. If instead, I run: fit2 <- glm(Accepted~Background-1, data=dat, family="binomial") exp(cbind(Odds=coef(fit2), confint(fit2))) Odds 2.5 % 97.5 % Backgroundblue 0.7088608 0.5553459 0.9017961 Backgroundred 1.7352941 1.3632702 2.2206569 The returns are precisely the odds of getting in being 'blue': Backgroundblue (0.7089) and the odds of being accepted being 'red': Backgroundred (1.7353). No Odds Ratio there. Therefore the two return values are not expected to be reciprocal. Finally, How to read the results if there are 3 factors in the categorical regressor? Same manual versus [R] calculation: I created a different fictitious data set with the same premise, but this time there were three ethnic backgrounds: "red", "blue" and "orange", and ran the same sequence: First, the contingency table: Acceptance blue orange red Total 0 86 65 130 281 1 64 42 162 268 Total 150 107 292 549 And calculated the Odds of getting in for each ethnic group: Odds Accept If Red = 1.246154; Odds Accept If Blue = 0.744186; Odds Accept If Orange = 0.646154 As well as the different Odds Ratios: OR red v blue = 1.674519; OR red v orange = 1.928571; OR blue v red = 0.597186; OR blue v orange = 1.151717; OR orange v red = 0.518519; and OR orange v blue = 0.868269 And proceeded with the now routine logistic regression followed by exponentiation of coefficients: fit <- glm(Accepted~Background, data=dat, family="binomial") exp(cbind(ODDS=coef(fit), confint(fit))) ODDS 2.5 % 97.5 % (Intercept) 0.7441860 0.5367042 1.026588 Backgroundorange 0.8682692 0.5223358 1.437108 Backgroundred 1.6745192 1.1271430 2.497853 Yielding the odds of getting in for "blues" as the (Intercept), and the Odds Ratios of Orange versus Blue in Backgroundorange, and the OR of Red v Blue in Backgroundred . On the other hand, the regression without intercept predictably returned just the three independent odds: fit2 <- glm(Accepted~Background-1, data=dat, family="binomial") exp(cbind(ODDS=coef(fit2), confint(fit2))) ODDS 2.5 % 97.5 % Backgroundblue 0.7441860 0.5367042 1.0265875 Backgroundorange 0.6461538 0.4354366 0.9484999 Backgroundred 1.2461538 0.9900426 1.5715814
From exp (coefficients) to Odds Ratio and their interpretation in Logistic Regression with factors
I've been working on answering my question by calculating manually the odds and odds ratios: Acceptance blue red Grand Total 0 158 102 260
From exp (coefficients) to Odds Ratio and their interpretation in Logistic Regression with factors I've been working on answering my question by calculating manually the odds and odds ratios: Acceptance blue red Grand Total 0 158 102 260 1 112 177 289 Total 270 279 549 So the Odds Ratio of getting into the school of Red over Blue is: $$ \frac{\rm Odds\ Accept\ If\ Red}{\rm Odds\ Acccept\ If\ Blue} = \frac{^{177}/_{102}}{^{112}/_{158}} = \frac {1.7353}{0.7089} = 2.448 $$ And this is the Backgroundredreturn of: fit <- glm(Accepted~Background, data=dat, family="binomial") exp(cbind(Odds_and_OR=coef(fit), confint(fit))) Odds_and_OR 2.5 % 97.5 % (Intercept) 0.7088608 0.5553459 0.9017961 Backgroundred 2.4480042 1.7397640 3.4595454 At the same time, the (Intercept)corresponds to the numerator of the odds ratio, which is exactly the odds of getting in being of 'blue' family background: $112/158 = 0.7089$. If instead, I run: fit2 <- glm(Accepted~Background-1, data=dat, family="binomial") exp(cbind(Odds=coef(fit2), confint(fit2))) Odds 2.5 % 97.5 % Backgroundblue 0.7088608 0.5553459 0.9017961 Backgroundred 1.7352941 1.3632702 2.2206569 The returns are precisely the odds of getting in being 'blue': Backgroundblue (0.7089) and the odds of being accepted being 'red': Backgroundred (1.7353). No Odds Ratio there. Therefore the two return values are not expected to be reciprocal. Finally, How to read the results if there are 3 factors in the categorical regressor? Same manual versus [R] calculation: I created a different fictitious data set with the same premise, but this time there were three ethnic backgrounds: "red", "blue" and "orange", and ran the same sequence: First, the contingency table: Acceptance blue orange red Total 0 86 65 130 281 1 64 42 162 268 Total 150 107 292 549 And calculated the Odds of getting in for each ethnic group: Odds Accept If Red = 1.246154; Odds Accept If Blue = 0.744186; Odds Accept If Orange = 0.646154 As well as the different Odds Ratios: OR red v blue = 1.674519; OR red v orange = 1.928571; OR blue v red = 0.597186; OR blue v orange = 1.151717; OR orange v red = 0.518519; and OR orange v blue = 0.868269 And proceeded with the now routine logistic regression followed by exponentiation of coefficients: fit <- glm(Accepted~Background, data=dat, family="binomial") exp(cbind(ODDS=coef(fit), confint(fit))) ODDS 2.5 % 97.5 % (Intercept) 0.7441860 0.5367042 1.026588 Backgroundorange 0.8682692 0.5223358 1.437108 Backgroundred 1.6745192 1.1271430 2.497853 Yielding the odds of getting in for "blues" as the (Intercept), and the Odds Ratios of Orange versus Blue in Backgroundorange, and the OR of Red v Blue in Backgroundred . On the other hand, the regression without intercept predictably returned just the three independent odds: fit2 <- glm(Accepted~Background-1, data=dat, family="binomial") exp(cbind(ODDS=coef(fit2), confint(fit2))) ODDS 2.5 % 97.5 % Backgroundblue 0.7441860 0.5367042 1.0265875 Backgroundorange 0.6461538 0.4354366 0.9484999 Backgroundred 1.2461538 0.9900426 1.5715814
From exp (coefficients) to Odds Ratio and their interpretation in Logistic Regression with factors I've been working on answering my question by calculating manually the odds and odds ratios: Acceptance blue red Grand Total 0 158 102 260
15,751
Choosing optimal K for KNN
If you carry on going, you will eventually end up with the CV error beginning to go up again. This is because the larger you make $k$, the more smoothing takes place, and eventually you will smooth so much that you will get a model that under-fits the data rather than over-fitting it (make $k$ big enough and the output will be constant regardless of the attribute values). I'd extend the plot until the CV error starts to go noticably up again, just to be sure, and then pick the $k$ that minimizes the CV error. The bigger you make $k$ the smoother the decision boundary and the more simple the model, so if computational expense is not an issue, I would go for a larger value of $k$ than a smaller one, if the difference in their CV errors is negligible. If the CV error doesn't start to rise again, that probably means the attributes are not informative (at least for that distance metric) and giving constant outputs is the best that it can do.
Choosing optimal K for KNN
If you carry on going, you will eventually end up with the CV error beginning to go up again. This is because the larger you make $k$, the more smoothing takes place, and eventually you will smooth s
Choosing optimal K for KNN If you carry on going, you will eventually end up with the CV error beginning to go up again. This is because the larger you make $k$, the more smoothing takes place, and eventually you will smooth so much that you will get a model that under-fits the data rather than over-fitting it (make $k$ big enough and the output will be constant regardless of the attribute values). I'd extend the plot until the CV error starts to go noticably up again, just to be sure, and then pick the $k$ that minimizes the CV error. The bigger you make $k$ the smoother the decision boundary and the more simple the model, so if computational expense is not an issue, I would go for a larger value of $k$ than a smaller one, if the difference in their CV errors is negligible. If the CV error doesn't start to rise again, that probably means the attributes are not informative (at least for that distance metric) and giving constant outputs is the best that it can do.
Choosing optimal K for KNN If you carry on going, you will eventually end up with the CV error beginning to go up again. This is because the larger you make $k$, the more smoothing takes place, and eventually you will smooth s
15,752
Choosing optimal K for KNN
Why not choose $K=17$? It looks like the CV error goes down until then and flattens out afterwards. If all you care about is predictive accuracy then I would not choose $K=3$ because it looks pretty clear that you can do better.
Choosing optimal K for KNN
Why not choose $K=17$? It looks like the CV error goes down until then and flattens out afterwards. If all you care about is predictive accuracy then I would not choose $K=3$ because it looks pretty c
Choosing optimal K for KNN Why not choose $K=17$? It looks like the CV error goes down until then and flattens out afterwards. If all you care about is predictive accuracy then I would not choose $K=3$ because it looks pretty clear that you can do better.
Choosing optimal K for KNN Why not choose $K=17$? It looks like the CV error goes down until then and flattens out afterwards. If all you care about is predictive accuracy then I would not choose $K=3$ because it looks pretty c
15,753
Choosing optimal K for KNN
Is there any physical or natural meaning behind the number of clusters? If I am not wrong, it is only natural that as K increases, error decreases - kind of like overfitting. Rather than fishing for the optimal K, its probably better to pick K based on domain knowledge or some intuition?
Choosing optimal K for KNN
Is there any physical or natural meaning behind the number of clusters? If I am not wrong, it is only natural that as K increases, error decreases - kind of like overfitting. Rather than fishing for t
Choosing optimal K for KNN Is there any physical or natural meaning behind the number of clusters? If I am not wrong, it is only natural that as K increases, error decreases - kind of like overfitting. Rather than fishing for the optimal K, its probably better to pick K based on domain knowledge or some intuition?
Choosing optimal K for KNN Is there any physical or natural meaning behind the number of clusters? If I am not wrong, it is only natural that as K increases, error decreases - kind of like overfitting. Rather than fishing for t
15,754
When is Fisher's z-transform appropriate?
For questions like these I would just run a simulation and see if the $p$-values behave as I expect them to. The $p$-value is the probability of randomly drawing a sample that deviates at least as much from the null-hypothesis as the data you observed if the null-hypothesis is true. So if we had many such samples, and one of them had a $p$-value of .04 then we would expect 4% of those samples to have a value less than .04. The same is true for all other possible $p$-values. Below is a simulation in Stata. The graphs check whether the $p$-values measure what they are supposed to measure, that is, they shows how much the proportion of samples with $p$-values less than the nominal $p$-value deviates from the nominal $p$-value. As you can see that test is somewhat problematic with such small number of observations. Whether or not it is too problematic for your research is your judgement call. clear all set more off program define sim, rclass tempname z se foreach i of numlist 5/10 20(10)50 { drop _all set obs `i' gen x = rnormal() gen y = rnormal() corr x y scalar `z' = atanh(r(rho)) scalar `se' = 1/sqrt(r(N)-3) return scalar p`i' = 2*normal(-abs(`z'/`se')) } end simulate p5 =r(p5) p6 =r(p6) p7 =r(p7) /// p8 =r(p8) p9 =r(p9) p10 =r(p10) /// p20=r(p20) p30=r(p30) p40 =r(p40) /// p50=r(p50), reps(200000) nodots: sim simpplot p5 p6 p7 p8 p9 p10, name(small, replace) /// scheme(s2color) ylabel(,angle(horizontal)) simpplot p20 p30 p40 p50 , name(less_small, replace) /// scheme(s2color) ylabel(,angle(horizontal))
When is Fisher's z-transform appropriate?
For questions like these I would just run a simulation and see if the $p$-values behave as I expect them to. The $p$-value is the probability of randomly drawing a sample that deviates at least as muc
When is Fisher's z-transform appropriate? For questions like these I would just run a simulation and see if the $p$-values behave as I expect them to. The $p$-value is the probability of randomly drawing a sample that deviates at least as much from the null-hypothesis as the data you observed if the null-hypothesis is true. So if we had many such samples, and one of them had a $p$-value of .04 then we would expect 4% of those samples to have a value less than .04. The same is true for all other possible $p$-values. Below is a simulation in Stata. The graphs check whether the $p$-values measure what they are supposed to measure, that is, they shows how much the proportion of samples with $p$-values less than the nominal $p$-value deviates from the nominal $p$-value. As you can see that test is somewhat problematic with such small number of observations. Whether or not it is too problematic for your research is your judgement call. clear all set more off program define sim, rclass tempname z se foreach i of numlist 5/10 20(10)50 { drop _all set obs `i' gen x = rnormal() gen y = rnormal() corr x y scalar `z' = atanh(r(rho)) scalar `se' = 1/sqrt(r(N)-3) return scalar p`i' = 2*normal(-abs(`z'/`se')) } end simulate p5 =r(p5) p6 =r(p6) p7 =r(p7) /// p8 =r(p8) p9 =r(p9) p10 =r(p10) /// p20=r(p20) p30=r(p30) p40 =r(p40) /// p50=r(p50), reps(200000) nodots: sim simpplot p5 p6 p7 p8 p9 p10, name(small, replace) /// scheme(s2color) ylabel(,angle(horizontal)) simpplot p20 p30 p40 p50 , name(less_small, replace) /// scheme(s2color) ylabel(,angle(horizontal))
When is Fisher's z-transform appropriate? For questions like these I would just run a simulation and see if the $p$-values behave as I expect them to. The $p$-value is the probability of randomly drawing a sample that deviates at least as muc
15,755
When is Fisher's z-transform appropriate?
FWIW I see the recommendation $N\ge 10$ in Myers & Well (research design and statistical analyses, second edition, 2003, p. 492). The footnote states: Strictly speaking, the $Z$ transformation is biased by an amount $r/(2(N-1))$: see Pearson and Hartley (1954, p. 29). This bias will generally be negligible unless $N$ is small and $\rho$ is large, and we ignore it here.
When is Fisher's z-transform appropriate?
FWIW I see the recommendation $N\ge 10$ in Myers & Well (research design and statistical analyses, second edition, 2003, p. 492). The footnote states: Strictly speaking, the $Z$ transformation is bi
When is Fisher's z-transform appropriate? FWIW I see the recommendation $N\ge 10$ in Myers & Well (research design and statistical analyses, second edition, 2003, p. 492). The footnote states: Strictly speaking, the $Z$ transformation is biased by an amount $r/(2(N-1))$: see Pearson and Hartley (1954, p. 29). This bias will generally be negligible unless $N$ is small and $\rho$ is large, and we ignore it here.
When is Fisher's z-transform appropriate? FWIW I see the recommendation $N\ge 10$ in Myers & Well (research design and statistical analyses, second edition, 2003, p. 492). The footnote states: Strictly speaking, the $Z$ transformation is bi
15,756
When is Fisher's z-transform appropriate?
Not sure whether a Fisher's $z$ transform is appropriate here. For $H_0: \rho=0$ (NB: null hypothesis is for population $\rho$, not sample $r$), the sampling distribution of the correlation coefficient is already symmetric, so no need to reduce skewness, which is what Fisher's $z$ aims to do, and you can use Student's $t$ approximation. Assuming you mean $H_0: \rho = \rho_0 \not = 0$, then the skewness of that PDF will depend on the proposed value of $\rho_0$, so there would then be no general answer of how large $n$ should be. Also, minimum values of $n$ would depend on the significance level $\alpha$ that you are working toward. You did not state its value. Nick's point is a fair one: the approximations and recommendations are always operating in some grey area. If, then, your Fisher approximation is good (=symmetric) enough, I would use the bound $n\geq (t_{\alpha/2} s/\epsilon)^2$ applicable to $t$-distributions, where $s$ is the sample standard deviation. If it is close enough to normality, this becomes $n \geq (1.96 s/\epsilon)^2$.
When is Fisher's z-transform appropriate?
Not sure whether a Fisher's $z$ transform is appropriate here. For $H_0: \rho=0$ (NB: null hypothesis is for population $\rho$, not sample $r$), the sampling distribution of the correlation coefficien
When is Fisher's z-transform appropriate? Not sure whether a Fisher's $z$ transform is appropriate here. For $H_0: \rho=0$ (NB: null hypothesis is for population $\rho$, not sample $r$), the sampling distribution of the correlation coefficient is already symmetric, so no need to reduce skewness, which is what Fisher's $z$ aims to do, and you can use Student's $t$ approximation. Assuming you mean $H_0: \rho = \rho_0 \not = 0$, then the skewness of that PDF will depend on the proposed value of $\rho_0$, so there would then be no general answer of how large $n$ should be. Also, minimum values of $n$ would depend on the significance level $\alpha$ that you are working toward. You did not state its value. Nick's point is a fair one: the approximations and recommendations are always operating in some grey area. If, then, your Fisher approximation is good (=symmetric) enough, I would use the bound $n\geq (t_{\alpha/2} s/\epsilon)^2$ applicable to $t$-distributions, where $s$ is the sample standard deviation. If it is close enough to normality, this becomes $n \geq (1.96 s/\epsilon)^2$.
When is Fisher's z-transform appropriate? Not sure whether a Fisher's $z$ transform is appropriate here. For $H_0: \rho=0$ (NB: null hypothesis is for population $\rho$, not sample $r$), the sampling distribution of the correlation coefficien
15,757
Are robust methods really any better?
In short, and from your description, you are comparing apple to oranges....in two ways. Let me address the first comparability issue briefly. The log transform does not address the outlier problem. However, it can help making heavily skewed data more symmetric, potentially improving the fit of any PCA method. In short, taking the $\log$ of your data is not a substitute for doing robust analysis and in some cases (skewed data) can well be a complement. To set aside this first confounder, for the rest of this post, I use the log transformed version of some asymmetric bi-variate data. Consider this example: library("MASS") library("copula") library("rrcov") p<-2;n<-100; eps<-0.2 l1<-list() l3<-list(rate=1) #generate assymetric data model<-mvdc(claytonCopula(1,dim=p),c("unif","exp"),list(l1,l3)); x1<-rMvdc(ceiling(n*(1-eps)),model); #adding 20% of outliers at the end: x1<-rbind(x1,mvrnorm(n-ceiling(n*(1-eps)),c(7,3),1/2*diag(2))) Now, fit the two models (ROBPCA and classic pca both on the log of the data): x2<-log(x1) v0<-PcaClassic(x2) v1<-PcaHubert(x2,mcd=FALSE,k=2) Now, consider the axis of smallest variation found by each method (here, for convenience, i plot it on the log-transformed space but you would get the same conclusions on the original space). Visibly, ROBPCA does a better job of handling the uncontaminated part of the data (the green dots): But now, I get to my second point. --calling $H_u$ the set of all green dots and $z_i$ ($w_i$) the robust (classical) pca score wrt to the axis of least variation -- you have that (this is quiet visible in the plot above): $$\sum_{i\in H_u}(z_i)^2<\sum_{i\in H_u}(w_i)^2\;\;\;(1)$$ But you seem to be surprised that: $$\sum_{i=1}^n(z_i)^2>\sum_{i=1}^n(w_i)^2\;\;\;(2)$$ --the way you described your testing procedure, you compute the fit assessment criterion on the whole dataset, so your evaluation criterion is a monotonous function of (2) where you should use a monotonous function of (1)-- In other words, do not expect a robust fit to have smaller sum of squared orthogonal residuals than a non robust procedure on your full dataset: the non robust estimator is already the unique minimizer of the SSOR on the full dataset.
Are robust methods really any better?
In short, and from your description, you are comparing apple to oranges....in two ways. Let me address the first comparability issue briefly. The log transform does not address the outlier problem.
Are robust methods really any better? In short, and from your description, you are comparing apple to oranges....in two ways. Let me address the first comparability issue briefly. The log transform does not address the outlier problem. However, it can help making heavily skewed data more symmetric, potentially improving the fit of any PCA method. In short, taking the $\log$ of your data is not a substitute for doing robust analysis and in some cases (skewed data) can well be a complement. To set aside this first confounder, for the rest of this post, I use the log transformed version of some asymmetric bi-variate data. Consider this example: library("MASS") library("copula") library("rrcov") p<-2;n<-100; eps<-0.2 l1<-list() l3<-list(rate=1) #generate assymetric data model<-mvdc(claytonCopula(1,dim=p),c("unif","exp"),list(l1,l3)); x1<-rMvdc(ceiling(n*(1-eps)),model); #adding 20% of outliers at the end: x1<-rbind(x1,mvrnorm(n-ceiling(n*(1-eps)),c(7,3),1/2*diag(2))) Now, fit the two models (ROBPCA and classic pca both on the log of the data): x2<-log(x1) v0<-PcaClassic(x2) v1<-PcaHubert(x2,mcd=FALSE,k=2) Now, consider the axis of smallest variation found by each method (here, for convenience, i plot it on the log-transformed space but you would get the same conclusions on the original space). Visibly, ROBPCA does a better job of handling the uncontaminated part of the data (the green dots): But now, I get to my second point. --calling $H_u$ the set of all green dots and $z_i$ ($w_i$) the robust (classical) pca score wrt to the axis of least variation -- you have that (this is quiet visible in the plot above): $$\sum_{i\in H_u}(z_i)^2<\sum_{i\in H_u}(w_i)^2\;\;\;(1)$$ But you seem to be surprised that: $$\sum_{i=1}^n(z_i)^2>\sum_{i=1}^n(w_i)^2\;\;\;(2)$$ --the way you described your testing procedure, you compute the fit assessment criterion on the whole dataset, so your evaluation criterion is a monotonous function of (2) where you should use a monotonous function of (1)-- In other words, do not expect a robust fit to have smaller sum of squared orthogonal residuals than a non robust procedure on your full dataset: the non robust estimator is already the unique minimizer of the SSOR on the full dataset.
Are robust methods really any better? In short, and from your description, you are comparing apple to oranges....in two ways. Let me address the first comparability issue briefly. The log transform does not address the outlier problem.
15,758
Contingency tables: what tests to do and when?
This is a good question, but a big one. I don't think I can provide a complete answer, but I will throw out some food for thought. First, under your top bullet point, the correction you are referring to is known as Yates' correction for continuity. The problem is that we calculate a discrete inferential statistic: $$ \chi^2=\sum\frac{(O-E)^2}{E} $$ (It is discrete because, with only a finite number of instances represented in a contingency table, there are a finite number of possible realized values that this statistic can take on.) Notwithstanding this fact, it is compared to a continuous reference distribution (viz., the $\chi^2$ distribution with degrees of freedom $(r-1)(c-1)$). This necessarily leads to a mismatch on some level. With a particularly small data set, and if some cells have expected values less than 5, it is possible that the p-value could be too small. Yates' correction adjusts for this. Ironically, the same underlying problem (discrete-continuous mismatch) can lead to p-values that are too high. Specifically, the p-value is conventionally defined as the probability of getting data that are as extreme or more than the observed data. With continuous data, it is understood that the probability of getting any exact value is vanishingly small, and thus we really have the probability of data that are more extreme. However, with discrete data there is a finite probability of getting data just like yours. Only calculating the probability of getting data more extreme than yours yields nominal p-values that are too low (leading to increased type I errors), but including the probability of getting data the same as yours leads to nominal p-values that are too high (which would lead to increased type II errors). These facts prompt the idea of the mid p-value. Under this approach, the p-value is the probability of data more extreme than yours plus half the probability of data just the same as yours. As you point out, there are many possibilities for testing contingency table data. The most comprehensive treatment of the pros and cons of the various approaches is here. That paper is specific to 2x2 tables, but you can still learn a lot about the options for contingency table data by reading it. I also do think it's worth considering models seriously. Older tests like chi-squared are quick, easy, and understood by many people, but do not leave you with as comprehensive an understanding of your data as you get from building an appropriate model. If it is reasonable to think of the rows [columns] of your contingency table as a response variable, and the columns [rows] as an explanatory / predictor variables, a modeling approach follows quite readily. For instance, if you had just two rows, you can build a logistic regression model; if there are several columns, you could use reference cell coding (dummy coding) to build an ANOVA-type model. On the other hand, if you have more than two rows, multinomial logistic regression can be used in the same manner. Should your rows have an intrinsic order, ordinal logistic regression would yield superior performance to multinomial. The log-linear model (Poisson regression) is probably less relevant unless you have contingency tables with more than two dimensions, in my opinion. For a comprehensive treatment of topics like these, the best sources are the books by Agresti: either his full-scale treatment (more rigorous), his intro book (easier but still comprehensive and very good), or possibly also his ordinal book. Update: Just for the sake of the completeness of list of possible tests, it occurs to me that we can add the likelihood ratio test (often called the '$G^2\text{-test}$'). It is: $$ G^2=\sum O\cdot\text{ln}\left(\frac{O}{E}\right) $$ This is also distributed as a chi-squared, and will almost always yield the same decision. The realized values of the two statistics will typically be similar, but slightly different. The question of which will be more powerful in a given situation is quite subtle. I gather it is the default choice by tradition in some fields. I do not necessarily advocate it's use over the traditional test; I'm only listing it for completeness, as I say.
Contingency tables: what tests to do and when?
This is a good question, but a big one. I don't think I can provide a complete answer, but I will throw out some food for thought. First, under your top bullet point, the correction you are referri
Contingency tables: what tests to do and when? This is a good question, but a big one. I don't think I can provide a complete answer, but I will throw out some food for thought. First, under your top bullet point, the correction you are referring to is known as Yates' correction for continuity. The problem is that we calculate a discrete inferential statistic: $$ \chi^2=\sum\frac{(O-E)^2}{E} $$ (It is discrete because, with only a finite number of instances represented in a contingency table, there are a finite number of possible realized values that this statistic can take on.) Notwithstanding this fact, it is compared to a continuous reference distribution (viz., the $\chi^2$ distribution with degrees of freedom $(r-1)(c-1)$). This necessarily leads to a mismatch on some level. With a particularly small data set, and if some cells have expected values less than 5, it is possible that the p-value could be too small. Yates' correction adjusts for this. Ironically, the same underlying problem (discrete-continuous mismatch) can lead to p-values that are too high. Specifically, the p-value is conventionally defined as the probability of getting data that are as extreme or more than the observed data. With continuous data, it is understood that the probability of getting any exact value is vanishingly small, and thus we really have the probability of data that are more extreme. However, with discrete data there is a finite probability of getting data just like yours. Only calculating the probability of getting data more extreme than yours yields nominal p-values that are too low (leading to increased type I errors), but including the probability of getting data the same as yours leads to nominal p-values that are too high (which would lead to increased type II errors). These facts prompt the idea of the mid p-value. Under this approach, the p-value is the probability of data more extreme than yours plus half the probability of data just the same as yours. As you point out, there are many possibilities for testing contingency table data. The most comprehensive treatment of the pros and cons of the various approaches is here. That paper is specific to 2x2 tables, but you can still learn a lot about the options for contingency table data by reading it. I also do think it's worth considering models seriously. Older tests like chi-squared are quick, easy, and understood by many people, but do not leave you with as comprehensive an understanding of your data as you get from building an appropriate model. If it is reasonable to think of the rows [columns] of your contingency table as a response variable, and the columns [rows] as an explanatory / predictor variables, a modeling approach follows quite readily. For instance, if you had just two rows, you can build a logistic regression model; if there are several columns, you could use reference cell coding (dummy coding) to build an ANOVA-type model. On the other hand, if you have more than two rows, multinomial logistic regression can be used in the same manner. Should your rows have an intrinsic order, ordinal logistic regression would yield superior performance to multinomial. The log-linear model (Poisson regression) is probably less relevant unless you have contingency tables with more than two dimensions, in my opinion. For a comprehensive treatment of topics like these, the best sources are the books by Agresti: either his full-scale treatment (more rigorous), his intro book (easier but still comprehensive and very good), or possibly also his ordinal book. Update: Just for the sake of the completeness of list of possible tests, it occurs to me that we can add the likelihood ratio test (often called the '$G^2\text{-test}$'). It is: $$ G^2=\sum O\cdot\text{ln}\left(\frac{O}{E}\right) $$ This is also distributed as a chi-squared, and will almost always yield the same decision. The realized values of the two statistics will typically be similar, but slightly different. The question of which will be more powerful in a given situation is quite subtle. I gather it is the default choice by tradition in some fields. I do not necessarily advocate it's use over the traditional test; I'm only listing it for completeness, as I say.
Contingency tables: what tests to do and when? This is a good question, but a big one. I don't think I can provide a complete answer, but I will throw out some food for thought. First, under your top bullet point, the correction you are referri
15,759
Contingency tables: what tests to do and when?
I will try to address some of your questions as best as I can from my perspective. First the Fisher-Irwin Test is just another name for Fisher's exact test. Except for the fact that it is sometimes computationally intense I generally prefer to use the Fisher test. If there is any issue with this test it is conditioning on the marginal totals. The beauty of the test is that under the null hypothesis the set of contingency tables with the same marginal totals as the observed table has a hypergeometric distribution. Some people argue that they don't see the rationale for restricting consideration to tables with the same marginal totals. Pearson's chi-square test is very commonly used to test for association in contingency tables. Like many other tests it is approximate and so the significance level is not always accurate. Cochran showed that in small samples when some cells are very sparse (e.g. containing fewer than 5 cases in some cells) the approximation will be poor. There are many other approximate tests. Typically when applying Fisher's test using SAS I get the results from all of these tests and they usually give almost the same results. But Fisher's test is always exact conditional on the marginal totals. Regarding Poisson regression, that is a model that relates the categorical variables to the cell totals. Like any model it depends on a set of assumptions. Most important is that the cell counts follow a Poisson distribution which means that the mean number of counts is equal to its variance. This is not generally true for cell count distributions. In the case of overdispersion (variance greater than mean) a negative binomial model might be more appropriate.
Contingency tables: what tests to do and when?
I will try to address some of your questions as best as I can from my perspective. First the Fisher-Irwin Test is just another name for Fisher's exact test. Except for the fact that it is sometimes co
Contingency tables: what tests to do and when? I will try to address some of your questions as best as I can from my perspective. First the Fisher-Irwin Test is just another name for Fisher's exact test. Except for the fact that it is sometimes computationally intense I generally prefer to use the Fisher test. If there is any issue with this test it is conditioning on the marginal totals. The beauty of the test is that under the null hypothesis the set of contingency tables with the same marginal totals as the observed table has a hypergeometric distribution. Some people argue that they don't see the rationale for restricting consideration to tables with the same marginal totals. Pearson's chi-square test is very commonly used to test for association in contingency tables. Like many other tests it is approximate and so the significance level is not always accurate. Cochran showed that in small samples when some cells are very sparse (e.g. containing fewer than 5 cases in some cells) the approximation will be poor. There are many other approximate tests. Typically when applying Fisher's test using SAS I get the results from all of these tests and they usually give almost the same results. But Fisher's test is always exact conditional on the marginal totals. Regarding Poisson regression, that is a model that relates the categorical variables to the cell totals. Like any model it depends on a set of assumptions. Most important is that the cell counts follow a Poisson distribution which means that the mean number of counts is equal to its variance. This is not generally true for cell count distributions. In the case of overdispersion (variance greater than mean) a negative binomial model might be more appropriate.
Contingency tables: what tests to do and when? I will try to address some of your questions as best as I can from my perspective. First the Fisher-Irwin Test is just another name for Fisher's exact test. Except for the fact that it is sometimes co
15,760
How is an ANOVA calculated for a repeated measures design: aov() vs lm() in R
One way to think about it is to treat the situation as a 3-factorial between subjects ANOVA with IVs participant, factor1, factor2, and a cell size of 1. anova(lm(value ~ factor1*factor2*participant, DFlong)) calculates all the SS for all effects in this 3-way ANOVA (3 main effects, 3 first-order interactions, 1 second-order interaction). Since there's only 1 person in each cell, the full model has no errors, and the above call to anova() cannot compute F-tests. But the SS are the same as in the 2-factorial within design. How does anova() actually compute the SS for an effect? Through sequential model comparisons (type I): It fits a restricted model without the effect in question, and an unrestricted model which includes that effect. The SS associated with this effect is the difference in error SS between both models. # get all SS from the 3-way between subjects ANOVA anova(lm(value ~ factor1*factor2*participant, DFlong)) dfL <- DFlong # just a shorter name for your data frame names(dfL) <- c("id", "group", "DV", "IV1", "IV2") # shorter variable names # sequential model comparisons (type I SS), restricted model is first, then unrestricted # main effects first anova(lm(DV ~ 1, dfL), lm(DV ~ id, dfL)) # SS for factor id anova(lm(DV ~ id, dfL), lm(DV ~ id+IV1, dfL)) # SS for factor IV1 anova(lm(DV ~ id+IV1, dfL), lm(DV ~ id+IV1+IV2, dfL)) # SS for factor IV2 # now first order interactions anova(lm(DV ~ id+IV1+IV2, dfL), lm(DV ~ id+IV1+IV2+id:IV1, dfL)) # SS for id:IV1 anova(lm(DV ~ id+IV1+IV2, dfL), lm(DV ~ id+IV1+IV2+id:IV2, dfL)) # SS for id:IV2 anova(lm(DV ~ id+IV1+IV2, dfL), lm(DV ~ id+IV1+IV2+IV1:IV2, dfL)) # SS for IV1:IV2 # finally the second-order interaction id:IV1:IV2 anova(lm(DV ~ id+IV1+IV2+id:IV1+id:IV2+IV1:IV2, dfL), lm(DV ~ id+IV1+IV2+id:IV1+id:IV2+IV1:IV2+id:IV1:IV2, dfL)) Now let's check the effect SS associated with the interaction id:IV1 by subtracting the error SS of the unrestricted model from the error SS of the restricted model. sum(residuals(lm(DV ~ id+IV1+IV2, dfL))^2) - sum(residuals(lm(DV ~ id+IV1+IV2+id:IV1, dfL))^2) Now that you have all the "raw" effect SS, you can build the within-subjects tests simply by choosing the correct error term to test an effect SS against. E.g., test the effect SS for factor1 against the interaction effect SS of participant:factor1. For an excellent introduction to the model comparison approach, I recommend Maxwell & Delaney (2004). Designing Experiments and Analyzing Data.
How is an ANOVA calculated for a repeated measures design: aov() vs lm() in R
One way to think about it is to treat the situation as a 3-factorial between subjects ANOVA with IVs participant, factor1, factor2, and a cell size of 1. anova(lm(value ~ factor1*factor2*participant,
How is an ANOVA calculated for a repeated measures design: aov() vs lm() in R One way to think about it is to treat the situation as a 3-factorial between subjects ANOVA with IVs participant, factor1, factor2, and a cell size of 1. anova(lm(value ~ factor1*factor2*participant, DFlong)) calculates all the SS for all effects in this 3-way ANOVA (3 main effects, 3 first-order interactions, 1 second-order interaction). Since there's only 1 person in each cell, the full model has no errors, and the above call to anova() cannot compute F-tests. But the SS are the same as in the 2-factorial within design. How does anova() actually compute the SS for an effect? Through sequential model comparisons (type I): It fits a restricted model without the effect in question, and an unrestricted model which includes that effect. The SS associated with this effect is the difference in error SS between both models. # get all SS from the 3-way between subjects ANOVA anova(lm(value ~ factor1*factor2*participant, DFlong)) dfL <- DFlong # just a shorter name for your data frame names(dfL) <- c("id", "group", "DV", "IV1", "IV2") # shorter variable names # sequential model comparisons (type I SS), restricted model is first, then unrestricted # main effects first anova(lm(DV ~ 1, dfL), lm(DV ~ id, dfL)) # SS for factor id anova(lm(DV ~ id, dfL), lm(DV ~ id+IV1, dfL)) # SS for factor IV1 anova(lm(DV ~ id+IV1, dfL), lm(DV ~ id+IV1+IV2, dfL)) # SS for factor IV2 # now first order interactions anova(lm(DV ~ id+IV1+IV2, dfL), lm(DV ~ id+IV1+IV2+id:IV1, dfL)) # SS for id:IV1 anova(lm(DV ~ id+IV1+IV2, dfL), lm(DV ~ id+IV1+IV2+id:IV2, dfL)) # SS for id:IV2 anova(lm(DV ~ id+IV1+IV2, dfL), lm(DV ~ id+IV1+IV2+IV1:IV2, dfL)) # SS for IV1:IV2 # finally the second-order interaction id:IV1:IV2 anova(lm(DV ~ id+IV1+IV2+id:IV1+id:IV2+IV1:IV2, dfL), lm(DV ~ id+IV1+IV2+id:IV1+id:IV2+IV1:IV2+id:IV1:IV2, dfL)) Now let's check the effect SS associated with the interaction id:IV1 by subtracting the error SS of the unrestricted model from the error SS of the restricted model. sum(residuals(lm(DV ~ id+IV1+IV2, dfL))^2) - sum(residuals(lm(DV ~ id+IV1+IV2+id:IV1, dfL))^2) Now that you have all the "raw" effect SS, you can build the within-subjects tests simply by choosing the correct error term to test an effect SS against. E.g., test the effect SS for factor1 against the interaction effect SS of participant:factor1. For an excellent introduction to the model comparison approach, I recommend Maxwell & Delaney (2004). Designing Experiments and Analyzing Data.
How is an ANOVA calculated for a repeated measures design: aov() vs lm() in R One way to think about it is to treat the situation as a 3-factorial between subjects ANOVA with IVs participant, factor1, factor2, and a cell size of 1. anova(lm(value ~ factor1*factor2*participant,
15,761
Estimating population size from the frequency of sampled duplicates and uniques
This is essentially a variant of the coupon collector's problem. If there are $n$ items in total and you have taken a sample size $s$ with replacement then the probability of having identified $u$ unique items is $$ Pr(U=u|n,s) = \frac{S_2(s,u) n! }{ (n-u)! n^s }$$ where $ S_2(s,u)$ gives Stirling numbers of the second kind Now all you need is a prior distribution for $Pr(N=n)$, apply Bayes theorem, and get a posterior distribution for $N$.
Estimating population size from the frequency of sampled duplicates and uniques
This is essentially a variant of the coupon collector's problem. If there are $n$ items in total and you have taken a sample size $s$ with replacement then the probability of having identified $u$ uni
Estimating population size from the frequency of sampled duplicates and uniques This is essentially a variant of the coupon collector's problem. If there are $n$ items in total and you have taken a sample size $s$ with replacement then the probability of having identified $u$ unique items is $$ Pr(U=u|n,s) = \frac{S_2(s,u) n! }{ (n-u)! n^s }$$ where $ S_2(s,u)$ gives Stirling numbers of the second kind Now all you need is a prior distribution for $Pr(N=n)$, apply Bayes theorem, and get a posterior distribution for $N$.
Estimating population size from the frequency of sampled duplicates and uniques This is essentially a variant of the coupon collector's problem. If there are $n$ items in total and you have taken a sample size $s$ with replacement then the probability of having identified $u$ uni
15,762
Estimating population size from the frequency of sampled duplicates and uniques
I have already give a suggestion based on Stirling numbers of the second kind and Bayesian methods. For those who find Stirling numbers too large or Bayesian methods too difficult, a rougher method might be to use $$E[U|n,s] = n\left( 1- \left(1-\frac{1}{n}\right)^s\right)$$ $$var[U|n,s] = n\left(1-\frac{1}{n}\right)^s + n^2 \left(1-\frac{1}{n}\right)\left(1-\frac{2}{n}\right)^s - n^2\left(1-\frac{1}{n}\right)^{2s} $$ and back-calculate using numerical methods. For example, taking GaBorgulya's example with $s=300$ and an observed $U = 265$, this might give us an estimate of $\hat{n} \approx 1180$ for the population. If that had been the population then it would have given us a variance for $U$ of about 25, and an arbitrary two standard deviations either side of 265 would be about 255 and 275 (as I said, this is a rough method). 255 would have given us a estimate for $n$ about 895, while 275 would have given about 1692. The example's 1000 is comfortably within this interval.
Estimating population size from the frequency of sampled duplicates and uniques
I have already give a suggestion based on Stirling numbers of the second kind and Bayesian methods. For those who find Stirling numbers too large or Bayesian methods too difficult, a rougher method
Estimating population size from the frequency of sampled duplicates and uniques I have already give a suggestion based on Stirling numbers of the second kind and Bayesian methods. For those who find Stirling numbers too large or Bayesian methods too difficult, a rougher method might be to use $$E[U|n,s] = n\left( 1- \left(1-\frac{1}{n}\right)^s\right)$$ $$var[U|n,s] = n\left(1-\frac{1}{n}\right)^s + n^2 \left(1-\frac{1}{n}\right)\left(1-\frac{2}{n}\right)^s - n^2\left(1-\frac{1}{n}\right)^{2s} $$ and back-calculate using numerical methods. For example, taking GaBorgulya's example with $s=300$ and an observed $U = 265$, this might give us an estimate of $\hat{n} \approx 1180$ for the population. If that had been the population then it would have given us a variance for $U$ of about 25, and an arbitrary two standard deviations either side of 265 would be about 255 and 275 (as I said, this is a rough method). 255 would have given us a estimate for $n$ about 895, while 275 would have given about 1692. The example's 1000 is comfortably within this interval.
Estimating population size from the frequency of sampled duplicates and uniques I have already give a suggestion based on Stirling numbers of the second kind and Bayesian methods. For those who find Stirling numbers too large or Bayesian methods too difficult, a rougher method
15,763
Estimating population size from the frequency of sampled duplicates and uniques
You can use the capture-recapture method, also implemented as the Rcapture R package. Here is an example, coded in R. Let's assume that the web service has N=1000 items. We will make n=300 requests. Generate a random sample where, numbering the elements from 1 to k, where k is how many different items we saw. N = 1000; population = 1:N # create a population of the integers from 1 to 1000 n = 300 # number of requests set.seed(20110406) observation = as.numeric(factor(sample(population, size=n, replace=TRUE))) # a random sample from the population, renumbered table(observation) # a table useful to see, not discussed k = length(unique(observation)) # number of unique items seen (t = table(table(observation))) The result of the simulation is 1 2 3 234 27 4 thus among the 300 requests there were 4 items seen 3 times, 27 items seen twice, and 234 items seen only once. Now estimate N from this sample: require(Rcapture) X = data.frame(t) X[,1]=as.numeric(X[,1]) desc=descriptive(X, dfreq=TRUE, dtype="nbcap", t=300) desc # useful to see, not discussed plot(desc) # useful to see, not discussed cp=closedp.0(X, dfreq=TRUE, dtype="nbcap", t=300, trace=TRUE) cp The result: Number of captured units: 265 Abundance estimations and model fits: abundance stderr deviance df AIC M0** 265.0 0.0 2.297787e+39 298 2.297787e+39 Mh Chao 1262.7 232.5 7.840000e-01 9 5.984840e+02 Mh Poisson2** 265.0 0.0 2.977883e+38 297 2.977883e+38 Mh Darroch** 553.9 37.1 7.299900e+01 297 9.469900e+01 Mh Gamma3.5** 5644623606.6 375581044.0 5.821861e+05 297 5.822078e+05 ** : The M0 model did not converge ** : The Mh Poisson2 model did not converge ** : The Mh Darroch model did not converge ** : The Mh Gamma3.5 model did not converge Note: 9 eta parameters has been set to zero in the Mh Chao model Thus only the Mh Chao model converged, it estimated $\hat{N}$=1262.7. EDIT: To check the reliability of the above method I ran the above code on 10000 generated samples. The Mh Chao model converged every time. Here is the summary: > round(quantile(Nhat, c(0, 0.025, 0.25, 0.50, 0.75, 0.975, 1)), 1) 0% 2.5% 25% 50% 75% 97.5% 100% 657.2 794.6 941.1 1034.0 1144.8 1445.2 2162.0 > mean(Nhat) [1] 1055.855 > sd(Nhat) [1] 166.8352
Estimating population size from the frequency of sampled duplicates and uniques
You can use the capture-recapture method, also implemented as the Rcapture R package. Here is an example, coded in R. Let's assume that the web service has N=1000 items. We will make n=300 requests. G
Estimating population size from the frequency of sampled duplicates and uniques You can use the capture-recapture method, also implemented as the Rcapture R package. Here is an example, coded in R. Let's assume that the web service has N=1000 items. We will make n=300 requests. Generate a random sample where, numbering the elements from 1 to k, where k is how many different items we saw. N = 1000; population = 1:N # create a population of the integers from 1 to 1000 n = 300 # number of requests set.seed(20110406) observation = as.numeric(factor(sample(population, size=n, replace=TRUE))) # a random sample from the population, renumbered table(observation) # a table useful to see, not discussed k = length(unique(observation)) # number of unique items seen (t = table(table(observation))) The result of the simulation is 1 2 3 234 27 4 thus among the 300 requests there were 4 items seen 3 times, 27 items seen twice, and 234 items seen only once. Now estimate N from this sample: require(Rcapture) X = data.frame(t) X[,1]=as.numeric(X[,1]) desc=descriptive(X, dfreq=TRUE, dtype="nbcap", t=300) desc # useful to see, not discussed plot(desc) # useful to see, not discussed cp=closedp.0(X, dfreq=TRUE, dtype="nbcap", t=300, trace=TRUE) cp The result: Number of captured units: 265 Abundance estimations and model fits: abundance stderr deviance df AIC M0** 265.0 0.0 2.297787e+39 298 2.297787e+39 Mh Chao 1262.7 232.5 7.840000e-01 9 5.984840e+02 Mh Poisson2** 265.0 0.0 2.977883e+38 297 2.977883e+38 Mh Darroch** 553.9 37.1 7.299900e+01 297 9.469900e+01 Mh Gamma3.5** 5644623606.6 375581044.0 5.821861e+05 297 5.822078e+05 ** : The M0 model did not converge ** : The Mh Poisson2 model did not converge ** : The Mh Darroch model did not converge ** : The Mh Gamma3.5 model did not converge Note: 9 eta parameters has been set to zero in the Mh Chao model Thus only the Mh Chao model converged, it estimated $\hat{N}$=1262.7. EDIT: To check the reliability of the above method I ran the above code on 10000 generated samples. The Mh Chao model converged every time. Here is the summary: > round(quantile(Nhat, c(0, 0.025, 0.25, 0.50, 0.75, 0.975, 1)), 1) 0% 2.5% 25% 50% 75% 97.5% 100% 657.2 794.6 941.1 1034.0 1144.8 1445.2 2162.0 > mean(Nhat) [1] 1055.855 > sd(Nhat) [1] 166.8352
Estimating population size from the frequency of sampled duplicates and uniques You can use the capture-recapture method, also implemented as the Rcapture R package. Here is an example, coded in R. Let's assume that the web service has N=1000 items. We will make n=300 requests. G
15,764
Intuitive explanation of contribution to sum of two normally distributed random variables
The question readily reduces to the case $\mu_X = \mu_Y = 0$ by looking at $X-\mu_X$ and $Y-\mu_Y$. Clearly the conditional distributions are Normal. Thus, the mean, median, and mode of each are coincident. The modes will occur at the coordinates of a local maximum of the bivariate PDF of $X$ and $Y$ constrained to the curve $g(x,y) = x+y = c$. This implies the contour of the bivariate PDF at this location and the constraint curve have parallel tangents. (This is the theory of Lagrange multipliers.) Because the equation of any contour is of the form $f(x,y) = x^2/(2\sigma_X^2) + y^2/(2\sigma_Y^2) = \rho$ for some constant $\rho$ (that is, all contours are ellipses), their gradients must be parallel, whence there exists $\lambda$ such that $$\left(\frac{x}{\sigma_X^2}, \frac{y}{\sigma_Y^2}\right) = \nabla f(x,y) = \lambda \nabla g(x,y) = \lambda(1,1).$$ It follows immediately that the modes of the conditional distributions (and therefore also the means) are determined by the ratio of the variances, not of the SDs. This analysis works for correlated $X$ and $Y$ as well and it applies to any linear constraints, not just the sum.
Intuitive explanation of contribution to sum of two normally distributed random variables
The question readily reduces to the case $\mu_X = \mu_Y = 0$ by looking at $X-\mu_X$ and $Y-\mu_Y$. Clearly the conditional distributions are Normal. Thus, the mean, median, and mode of each are coin
Intuitive explanation of contribution to sum of two normally distributed random variables The question readily reduces to the case $\mu_X = \mu_Y = 0$ by looking at $X-\mu_X$ and $Y-\mu_Y$. Clearly the conditional distributions are Normal. Thus, the mean, median, and mode of each are coincident. The modes will occur at the coordinates of a local maximum of the bivariate PDF of $X$ and $Y$ constrained to the curve $g(x,y) = x+y = c$. This implies the contour of the bivariate PDF at this location and the constraint curve have parallel tangents. (This is the theory of Lagrange multipliers.) Because the equation of any contour is of the form $f(x,y) = x^2/(2\sigma_X^2) + y^2/(2\sigma_Y^2) = \rho$ for some constant $\rho$ (that is, all contours are ellipses), their gradients must be parallel, whence there exists $\lambda$ such that $$\left(\frac{x}{\sigma_X^2}, \frac{y}{\sigma_Y^2}\right) = \nabla f(x,y) = \lambda \nabla g(x,y) = \lambda(1,1).$$ It follows immediately that the modes of the conditional distributions (and therefore also the means) are determined by the ratio of the variances, not of the SDs. This analysis works for correlated $X$ and $Y$ as well and it applies to any linear constraints, not just the sum.
Intuitive explanation of contribution to sum of two normally distributed random variables The question readily reduces to the case $\mu_X = \mu_Y = 0$ by looking at $X-\mu_X$ and $Y-\mu_Y$. Clearly the conditional distributions are Normal. Thus, the mean, median, and mode of each are coin
15,765
Assumptions of cluster analysis
Well, clustering techniques are not limited to distance-based methods where we seek groups of statistical units that are unusually close to each other, in a geometrical sense. There're also a range of techniques relying on density (clusters are seen as "regions" in the feature space) or probability distribution. The latter case is also know as model-based clustering; psychometricians use the term Latent Profile Analysis to denote this specific case of Finite Mixture Model, where we assume that the population is composed of different unobserved groups, or latent classes, and that the joint density of all manifest variables is a mixture of this class-specific density. Good implementation are available in the Mclust package or Mplus software. Different class-invariant covariance matrices can be used (in fact, Mclust uses the BIC criterion to select the optimal one while varying the number of clusters). The standard Latent Class Model also makes the assumption that observed data come from a mixture of g multivariate multinomial distributions. A good overview is available in Model-based cluster analysis: a Defence, by Gilles Celeux. Inasmuch these methods rely on distributional assumptions, this also render possible to use formal tests or goodness-of-fit indices to decide about the number of clusters or classes, which remains a difficult problem in distance-based cluster analysis, but see the following articles that discussed this issue: Handl, J., Knowles, J., and Kell, D.B. (2005). Computational cluster validation in post-genomic data analysis. Bioinformatics, 21(15), 3201-3212. Hennig, C. (2007) Cluster-wise assessment of cluster stability. Computational Statistics and Data Analysis, 52, 258-271. Hennig, C. (2008) Dissolution point and isolation robustness: robustness criteria for general cluster analysis methods. Journal of Multivariate Analysis, 99, 1154-1176.
Assumptions of cluster analysis
Well, clustering techniques are not limited to distance-based methods where we seek groups of statistical units that are unusually close to each other, in a geometrical sense. There're also a range of
Assumptions of cluster analysis Well, clustering techniques are not limited to distance-based methods where we seek groups of statistical units that are unusually close to each other, in a geometrical sense. There're also a range of techniques relying on density (clusters are seen as "regions" in the feature space) or probability distribution. The latter case is also know as model-based clustering; psychometricians use the term Latent Profile Analysis to denote this specific case of Finite Mixture Model, where we assume that the population is composed of different unobserved groups, or latent classes, and that the joint density of all manifest variables is a mixture of this class-specific density. Good implementation are available in the Mclust package or Mplus software. Different class-invariant covariance matrices can be used (in fact, Mclust uses the BIC criterion to select the optimal one while varying the number of clusters). The standard Latent Class Model also makes the assumption that observed data come from a mixture of g multivariate multinomial distributions. A good overview is available in Model-based cluster analysis: a Defence, by Gilles Celeux. Inasmuch these methods rely on distributional assumptions, this also render possible to use formal tests or goodness-of-fit indices to decide about the number of clusters or classes, which remains a difficult problem in distance-based cluster analysis, but see the following articles that discussed this issue: Handl, J., Knowles, J., and Kell, D.B. (2005). Computational cluster validation in post-genomic data analysis. Bioinformatics, 21(15), 3201-3212. Hennig, C. (2007) Cluster-wise assessment of cluster stability. Computational Statistics and Data Analysis, 52, 258-271. Hennig, C. (2008) Dissolution point and isolation robustness: robustness criteria for general cluster analysis methods. Journal of Multivariate Analysis, 99, 1154-1176.
Assumptions of cluster analysis Well, clustering techniques are not limited to distance-based methods where we seek groups of statistical units that are unusually close to each other, in a geometrical sense. There're also a range of
15,766
Assumptions of cluster analysis
There is a very wide variety of clustering methods, which are exploratory by nature, and I do not think that any of them, whether hierarchical or partition-based, relies on the kind of assumptions that one has to meet for analysing variance. Having a look at the [MV] documentation in Stata to answer your question, I found this amusing quote at page 85: Although some have said that there are as many cluster-analysis methods as there are people performing cluster analysis. This is a gross understatement! There exist infinitely more ways to perform a cluster analysis than people who perform them. In that context, I doubt that there are any assumptions applying across clustering method. The rest of the text just sets out as a general rule that you need some form of "dissimilarity measure", which need not even be a metric distance, to create clusters. There is one exception, though, which is when you are clustering observations as part of a post-estimation analysis. In Stata, the vce command comes with the following warning, at page 86 of the same source: If you are familiar with Stata’s large array of estimation commands, be careful to distinguish between cluster analysis (the cluster command) and the vce(cluster clustvar) option allowed with many estimation commands. Cluster analysis finds groups in data. The vce(cluster clustvar) option allowed with various estimation commands indicates that the observations are independent across the groups defined by the option but are not necessarily independent within those groups. A grouping variable produced by the cluster command will seldom satisfy the assumption behind the use of the vce(cluster clustvar) option. Based on that, I would assume that independent observations are not required outside of that particular case. Intuitively, I would add that cluster analysis might even be used to the precise purpose of exploring the extent to which the observations are independent or not. I'll finish by mentioning that, at page 356 of Statistics with Stata, Lawrence Hamilton mentions standardized variables as an "essential" aspect of cluster analysis, although he does not go into more depth on the issue.
Assumptions of cluster analysis
There is a very wide variety of clustering methods, which are exploratory by nature, and I do not think that any of them, whether hierarchical or partition-based, relies on the kind of assumptions tha
Assumptions of cluster analysis There is a very wide variety of clustering methods, which are exploratory by nature, and I do not think that any of them, whether hierarchical or partition-based, relies on the kind of assumptions that one has to meet for analysing variance. Having a look at the [MV] documentation in Stata to answer your question, I found this amusing quote at page 85: Although some have said that there are as many cluster-analysis methods as there are people performing cluster analysis. This is a gross understatement! There exist infinitely more ways to perform a cluster analysis than people who perform them. In that context, I doubt that there are any assumptions applying across clustering method. The rest of the text just sets out as a general rule that you need some form of "dissimilarity measure", which need not even be a metric distance, to create clusters. There is one exception, though, which is when you are clustering observations as part of a post-estimation analysis. In Stata, the vce command comes with the following warning, at page 86 of the same source: If you are familiar with Stata’s large array of estimation commands, be careful to distinguish between cluster analysis (the cluster command) and the vce(cluster clustvar) option allowed with many estimation commands. Cluster analysis finds groups in data. The vce(cluster clustvar) option allowed with various estimation commands indicates that the observations are independent across the groups defined by the option but are not necessarily independent within those groups. A grouping variable produced by the cluster command will seldom satisfy the assumption behind the use of the vce(cluster clustvar) option. Based on that, I would assume that independent observations are not required outside of that particular case. Intuitively, I would add that cluster analysis might even be used to the precise purpose of exploring the extent to which the observations are independent or not. I'll finish by mentioning that, at page 356 of Statistics with Stata, Lawrence Hamilton mentions standardized variables as an "essential" aspect of cluster analysis, although he does not go into more depth on the issue.
Assumptions of cluster analysis There is a very wide variety of clustering methods, which are exploratory by nature, and I do not think that any of them, whether hierarchical or partition-based, relies on the kind of assumptions tha
15,767
Assumptions of cluster analysis
Spatial cluster analysis uses geographically referenced observations and is a subset of cluster analysis that is not limited to exploratory analysis. Example 1 It can be used to make fair election districts. Example 2 Local spatial autocorrelation measures are used in the AMOEBA method of clustering. Aldstadt and Getis use the resulting clusters to create a spatial weights matrix that can be specified in spatial regressions to test a hypothesis. See Aldstadt, Jared and Arthur Getis (2006) “Using AMOEBA to create a spatial weights matrix and identify spatial clusters.” Geographical Analysis 38(4) 327-343 Example 3 Cluster analysis based on randomly growing regions given a set of criteria could be used as a probabilistic method to indicate unfairness in the design of institutional zones such as school attendance zones or election districts.
Assumptions of cluster analysis
Spatial cluster analysis uses geographically referenced observations and is a subset of cluster analysis that is not limited to exploratory analysis. Example 1 It can be used to make fair election di
Assumptions of cluster analysis Spatial cluster analysis uses geographically referenced observations and is a subset of cluster analysis that is not limited to exploratory analysis. Example 1 It can be used to make fair election districts. Example 2 Local spatial autocorrelation measures are used in the AMOEBA method of clustering. Aldstadt and Getis use the resulting clusters to create a spatial weights matrix that can be specified in spatial regressions to test a hypothesis. See Aldstadt, Jared and Arthur Getis (2006) “Using AMOEBA to create a spatial weights matrix and identify spatial clusters.” Geographical Analysis 38(4) 327-343 Example 3 Cluster analysis based on randomly growing regions given a set of criteria could be used as a probabilistic method to indicate unfairness in the design of institutional zones such as school attendance zones or election districts.
Assumptions of cluster analysis Spatial cluster analysis uses geographically referenced observations and is a subset of cluster analysis that is not limited to exploratory analysis. Example 1 It can be used to make fair election di
15,768
Assumptions of cluster analysis
Cluster analysis does not involve hypothesis testing per se, but is really just a collection of different similarity algorithms for exploratory analysis. You can force hypothesis testing somewhat but the results are often inconsistent, since cluster changes are very sensitive to changes in parameters. http://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_introclus_sect010.htm
Assumptions of cluster analysis
Cluster analysis does not involve hypothesis testing per se, but is really just a collection of different similarity algorithms for exploratory analysis. You can force hypothesis testing somewhat but
Assumptions of cluster analysis Cluster analysis does not involve hypothesis testing per se, but is really just a collection of different similarity algorithms for exploratory analysis. You can force hypothesis testing somewhat but the results are often inconsistent, since cluster changes are very sensitive to changes in parameters. http://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_introclus_sect010.htm
Assumptions of cluster analysis Cluster analysis does not involve hypothesis testing per se, but is really just a collection of different similarity algorithms for exploratory analysis. You can force hypothesis testing somewhat but
15,769
If an auto-regressive time series model is non-linear, does it still require stationarity?
If the purpose of your model is prediction and forecasting, then the short answer is YES, but the stationarity doesn't need to be on levels. I'll explain. If you boil down forecasting to its most basic form, it's going to be extraction of the invariant. Consider this: you cannot forecast what's changing. If I tell you tomorrow is going to be different than today in every imaginable aspect, you will not be able to produce any kind of forecast. It's only when you're able to extend something from today to tomorrow, you can produce any kind of a prediction. I'll give you a few examples. You know that the distribution of the tomorrow's average temperature is going to be about the same as today. In this case, you can take today's temperature as your prediction for tomorrow, the naive forecast $\hat x_{t+1}= x_t$ You observe a car at mile 10 on a road driving at the rate of speed $v=60 $ mph. In a minute it's probably going to be around mile 11 or 9. If you know that it's driving toward mile 11, then it's going to be around mile 11. Given that its speed and direction are constant. Note, that the location is not stationary here, only the rate of speed is. In this regard it's analogous to a difference model like ARIMA(p,1,q) or a constant trend model like $x_t\sim v t$ Your neighbor is drunk every Friday. Is he going to be drunk next Friday? Yes, as long as he doesn't change his behavior and so on In every case of a reasonable forecast, we first extract something that is constant from the process, and extend it to future. Hence, my answer: yes, the time series need to be stationary if variance and mean are the invariants that you are going to extend into the future from history. Moreover, you want the relationships to regressors to be stable too. Simply identify what is an invariant in your model, whether it's a mean level, a rate of change or something else. These things need to stay the same in future if you want your model to have any forecasting power. Holt Winters Example Holt Winters filter was mentioned in the comments. It's a popular choice for smoothing and forecasting certain kinds of seasonal series, and it can deal with nonstationary series. Particularly, it can handle series where the mean level grows linearly with time. In other words where the slope is stable. In my terminology the slope is one of the invariants that this approach extracts from the series. Let's see how it fails when the slope is unstable. In this plot I'm showing the deterministic series with exponential growth and additive seasonality. In other words, the slope keeps getting steeper with time: You can see how filter seems to fit the data very well. The fitted line is red. However, if you attempt to predict with this filter, it fails miserably. The true line is black, and the red if fitted with blue confidence bounds on the next plot: The reason why it fails is easy to see by examining Holt Winters model equations. It extracts the slope from past, and extends to future. This works very well when the slope is stable, but when it is consistently growing the filter can't keep up, it's one step behind and the effect accumulates into an increasing forecast error. R code: t=1:150 a = 0.04 x=ts(exp(a*t)+sin(t/5)*sin(t/2),deltat = 1/12,start=0) xt = window(x,0,99/12) plot(xt) (m <- HoltWinters(xt)) plot(m) plot(fitted(m)) xp = window(x,8.33) p <- predict(m, 50, prediction.interval = TRUE) plot(m, p) lines(xp,col="black") In this example you may be able to improve filter performance by simply taking a log of series. When you take a logarithm of exponentially growing series, you make its slope stable again, and give this filter a chance. Here's example: R code: t=1:150 a = 0.1 x=ts(exp(a*t)+sin(t/5)*sin(t/2),deltat = 1/12,start=0) xt = window(log(x),0,99/12) plot(xt) (m <- HoltWinters(xt)) plot(m) plot(fitted(m)) p <- predict(m, 50, prediction.interval = TRUE) plot(m, exp(p)) xp = window(x,8.33) lines(xp,col="black")
If an auto-regressive time series model is non-linear, does it still require stationarity?
If the purpose of your model is prediction and forecasting, then the short answer is YES, but the stationarity doesn't need to be on levels. I'll explain. If you boil down forecasting to its most basi
If an auto-regressive time series model is non-linear, does it still require stationarity? If the purpose of your model is prediction and forecasting, then the short answer is YES, but the stationarity doesn't need to be on levels. I'll explain. If you boil down forecasting to its most basic form, it's going to be extraction of the invariant. Consider this: you cannot forecast what's changing. If I tell you tomorrow is going to be different than today in every imaginable aspect, you will not be able to produce any kind of forecast. It's only when you're able to extend something from today to tomorrow, you can produce any kind of a prediction. I'll give you a few examples. You know that the distribution of the tomorrow's average temperature is going to be about the same as today. In this case, you can take today's temperature as your prediction for tomorrow, the naive forecast $\hat x_{t+1}= x_t$ You observe a car at mile 10 on a road driving at the rate of speed $v=60 $ mph. In a minute it's probably going to be around mile 11 or 9. If you know that it's driving toward mile 11, then it's going to be around mile 11. Given that its speed and direction are constant. Note, that the location is not stationary here, only the rate of speed is. In this regard it's analogous to a difference model like ARIMA(p,1,q) or a constant trend model like $x_t\sim v t$ Your neighbor is drunk every Friday. Is he going to be drunk next Friday? Yes, as long as he doesn't change his behavior and so on In every case of a reasonable forecast, we first extract something that is constant from the process, and extend it to future. Hence, my answer: yes, the time series need to be stationary if variance and mean are the invariants that you are going to extend into the future from history. Moreover, you want the relationships to regressors to be stable too. Simply identify what is an invariant in your model, whether it's a mean level, a rate of change or something else. These things need to stay the same in future if you want your model to have any forecasting power. Holt Winters Example Holt Winters filter was mentioned in the comments. It's a popular choice for smoothing and forecasting certain kinds of seasonal series, and it can deal with nonstationary series. Particularly, it can handle series where the mean level grows linearly with time. In other words where the slope is stable. In my terminology the slope is one of the invariants that this approach extracts from the series. Let's see how it fails when the slope is unstable. In this plot I'm showing the deterministic series with exponential growth and additive seasonality. In other words, the slope keeps getting steeper with time: You can see how filter seems to fit the data very well. The fitted line is red. However, if you attempt to predict with this filter, it fails miserably. The true line is black, and the red if fitted with blue confidence bounds on the next plot: The reason why it fails is easy to see by examining Holt Winters model equations. It extracts the slope from past, and extends to future. This works very well when the slope is stable, but when it is consistently growing the filter can't keep up, it's one step behind and the effect accumulates into an increasing forecast error. R code: t=1:150 a = 0.04 x=ts(exp(a*t)+sin(t/5)*sin(t/2),deltat = 1/12,start=0) xt = window(x,0,99/12) plot(xt) (m <- HoltWinters(xt)) plot(m) plot(fitted(m)) xp = window(x,8.33) p <- predict(m, 50, prediction.interval = TRUE) plot(m, p) lines(xp,col="black") In this example you may be able to improve filter performance by simply taking a log of series. When you take a logarithm of exponentially growing series, you make its slope stable again, and give this filter a chance. Here's example: R code: t=1:150 a = 0.1 x=ts(exp(a*t)+sin(t/5)*sin(t/2),deltat = 1/12,start=0) xt = window(log(x),0,99/12) plot(xt) (m <- HoltWinters(xt)) plot(m) plot(fitted(m)) p <- predict(m, 50, prediction.interval = TRUE) plot(m, exp(p)) xp = window(x,8.33) lines(xp,col="black")
If an auto-regressive time series model is non-linear, does it still require stationarity? If the purpose of your model is prediction and forecasting, then the short answer is YES, but the stationarity doesn't need to be on levels. I'll explain. If you boil down forecasting to its most basi
15,770
Methods to work around the problem of missing data in machine learning
The technique you describe is called imputation by sequential regressions or multiple imputation by chained equations. The technique was pioneered by Raghunathan (2001) and implemented in a well working R package called mice (van Buuren, 2012). A paper by Schafer and Graham (2002) explains well why mean imputation and listwise deletion (what you call line exclusion) usually are no good alternatives to the above mentioned techniques. Principally mean imputation is not conditional and thus can bias the imputed distributions towards the observed mean. It will also shrink the variance, among other undesirable impacts on the imputed distribution. Furthermore, listwise deletion indeed will only work if the data are missing completely at random, like by the flip of a coin. Also it will increase the sampling error, as the sample size is reduced. The authors quoted above usually recommend starting with the variable featuring the least missing values. Also, the technique is usually applied in a Bayesian way (i.e. an extension of your suggestion). Variables are visited more often in the imputation procedure, not only once. In particular, each variable is completed by draws from its conditional posterior predictive distribution, starting with the variable featuring least missing values. Once all variables in a data set have been completed, the algorithm again starts at the first variable and then re-iterates until convergence. The authors have shown that this algorithm is Gibbs, thus it usually converges to the correct multivariate distribution of the variables. Usually, because there are some untestable assumptions involved, in particular missing at random data (i.e. whether data are observed or not depends on the observed data only, and not on the unobaserved values). Also the procedures can be partially incompatible, which is why they have been called PIGS (partially incompatible Gibbs sampler). In practice Bayesian multiple imputation is still a good way to deal with multivariate non-monotone missing data problems. Also, non-parametric extensions such as predictive mean matching help to relax regression modeling assumptions. Raghunathan, T. E., Lepkowski, J., van Hoewyk, J., & Solenberger, P. (2001). A multivariate technique for multiply imputing missing values using a sequence of regression models. Survey Methodology, 27(1), 85–95. Schafer, J. L., & Graham, J. W. (2002). Missing data: Our view of the state of the art. Psychological Methods, 7(2), 147–177. https://doi.org/10.1037/1082-989X.7.2.147 van Buuren, S. (2012). Flexible Imputation of Missing Data. Boca Raton: CRC Press.
Methods to work around the problem of missing data in machine learning
The technique you describe is called imputation by sequential regressions or multiple imputation by chained equations. The technique was pioneered by Raghunathan (2001) and implemented in a well worki
Methods to work around the problem of missing data in machine learning The technique you describe is called imputation by sequential regressions or multiple imputation by chained equations. The technique was pioneered by Raghunathan (2001) and implemented in a well working R package called mice (van Buuren, 2012). A paper by Schafer and Graham (2002) explains well why mean imputation and listwise deletion (what you call line exclusion) usually are no good alternatives to the above mentioned techniques. Principally mean imputation is not conditional and thus can bias the imputed distributions towards the observed mean. It will also shrink the variance, among other undesirable impacts on the imputed distribution. Furthermore, listwise deletion indeed will only work if the data are missing completely at random, like by the flip of a coin. Also it will increase the sampling error, as the sample size is reduced. The authors quoted above usually recommend starting with the variable featuring the least missing values. Also, the technique is usually applied in a Bayesian way (i.e. an extension of your suggestion). Variables are visited more often in the imputation procedure, not only once. In particular, each variable is completed by draws from its conditional posterior predictive distribution, starting with the variable featuring least missing values. Once all variables in a data set have been completed, the algorithm again starts at the first variable and then re-iterates until convergence. The authors have shown that this algorithm is Gibbs, thus it usually converges to the correct multivariate distribution of the variables. Usually, because there are some untestable assumptions involved, in particular missing at random data (i.e. whether data are observed or not depends on the observed data only, and not on the unobaserved values). Also the procedures can be partially incompatible, which is why they have been called PIGS (partially incompatible Gibbs sampler). In practice Bayesian multiple imputation is still a good way to deal with multivariate non-monotone missing data problems. Also, non-parametric extensions such as predictive mean matching help to relax regression modeling assumptions. Raghunathan, T. E., Lepkowski, J., van Hoewyk, J., & Solenberger, P. (2001). A multivariate technique for multiply imputing missing values using a sequence of regression models. Survey Methodology, 27(1), 85–95. Schafer, J. L., & Graham, J. W. (2002). Missing data: Our view of the state of the art. Psychological Methods, 7(2), 147–177. https://doi.org/10.1037/1082-989X.7.2.147 van Buuren, S. (2012). Flexible Imputation of Missing Data. Boca Raton: CRC Press.
Methods to work around the problem of missing data in machine learning The technique you describe is called imputation by sequential regressions or multiple imputation by chained equations. The technique was pioneered by Raghunathan (2001) and implemented in a well worki
15,771
Methods to work around the problem of missing data in machine learning
I did not find anything that solved my problem so I wrote a function that mixes some solutions to a Pandas dataframe with missing numerical values (with fancyimpute) and categorical (with a random forest). import pandas as pd import numpy as np from sklearn.ensemble import RandomForestClassifier import fancyimpute as fi def separe_numeric_categoric(df): numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64'] df_n = df.select_dtypes(include=numerics) df_c = df.select_dtypes(exclude=numerics) print(f'The DF have {len(list(df_n))} numerical features and {len(list(df_c))} categorical fets') return df_n, df_c def find_missing(df): total = df.isnull().sum().sort_values(ascending=False) percent = (df.isnull().sum()/df.isnull().count()).sort_values(ascending=False) filter(lambda x: x>=minimum, percent) return percent def count_missing(df): missing = find_missing(df) total_columns_with_missing = 0 for i in (missing): if i>0: total_columns_with_missing += 1 return total_columns_with_missing def remove_missing_data(df,minimum=.1): percent = find_missing(df) number = len(list(filter(lambda x: x>=(1.0-minimum), percent))) names = list(percent.keys()[:number]) df = df.drop(names, 1, errors='ignore') print(f'{number} columns exclude because haven`t minimium data.') return df def one_hot(df, cols): for each in cols: dummies = pd.get_dummies(df[each], prefix=each, drop_first=False) df = pd.concat([df, dummies], axis=1) df = df.drop(cols, axis=1) return df def impute_missing_data(df,minimium_data=.1): columns_missing = count_missing(df) print(f'Total columns with missing values: {count_missing(df)} of a {len(list(df))} columns in df') # remove features without minimium size of information df = remove_missing_data(df,minimium_data) numerical_df, categorical_df = separe_numeric_categoric(df) # Autocomplete using MICE for numerical features. try: df_numerical_complete = fi.MICE(verbose=False).complete(numerical_df.values) n_missing = count_missing(df) print(f'{columns_missing-n_missing} numerical features imputated') # Complete the columns name. temp = pd.DataFrame(columns=numerical_df.columns, data=df_numerical_complete) # df temp com os dados numericos completados e os categóricos. df = pd.concat([temp, categorical_df], axis=1) except Exception as e: print(e) print('Without Missing data in numerical features') missing = find_missing(df) names = missing.keys() n = 0 for i, c in enumerate(missing): if c > 0: col = names[i] print(f'Start the prediction of {col}') clf = RandomForestClassifier() le = LabelEncoder() ## inverter a ordem da predição das categóricas pode melhorar a precisao. categorical_train = list(categorical_df.loc[:,categorical_df.columns != col]) temp = one_hot(df,categorical_train) df1 = temp[temp[col].notnull()] df2 = temp[temp[col].isnull()] df1_x = df1.loc[:, df1.columns != col] df2_x = df2.loc[:, df1.columns != col] df1_y = df1[col] le.fit(df1_y) df1_y = le.transform(df1_y) clf.fit(df1_x, df1_y) df2_yHat = clf.predict(df2_x) df2_yHat = le.inverse_transform(df2_yHat) df2_yHat = pd.DataFrame(data=df2_yHat, columns=[col]) df1_y = le.inverse_transform(df1_y) df1_y = pd.DataFrame(data=df1_y,columns=[col]) df2_x.reset_index(inplace=True) result2 = pd.concat([df2_yHat, df2_x], axis=1) try: del result2['index'] except: pass df1_x.reset_index(inplace=True) result1 = pd.concat([df1_y, df1_x], axis=1) try: del result1['index'] except: pass result = pd.concat([result1, result2]) result = result.set_index(['Id']) df.reset_index() try: df.set_index(['Id'],inplace=True) except: pass df[col] = result[col] n += 1 print(f'Number of columns categorical with missing data solved: {n}') return df df = impute_missing_data(df)
Methods to work around the problem of missing data in machine learning
I did not find anything that solved my problem so I wrote a function that mixes some solutions to a Pandas dataframe with missing numerical values (with fancyimpute) and categorical (with a random for
Methods to work around the problem of missing data in machine learning I did not find anything that solved my problem so I wrote a function that mixes some solutions to a Pandas dataframe with missing numerical values (with fancyimpute) and categorical (with a random forest). import pandas as pd import numpy as np from sklearn.ensemble import RandomForestClassifier import fancyimpute as fi def separe_numeric_categoric(df): numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64'] df_n = df.select_dtypes(include=numerics) df_c = df.select_dtypes(exclude=numerics) print(f'The DF have {len(list(df_n))} numerical features and {len(list(df_c))} categorical fets') return df_n, df_c def find_missing(df): total = df.isnull().sum().sort_values(ascending=False) percent = (df.isnull().sum()/df.isnull().count()).sort_values(ascending=False) filter(lambda x: x>=minimum, percent) return percent def count_missing(df): missing = find_missing(df) total_columns_with_missing = 0 for i in (missing): if i>0: total_columns_with_missing += 1 return total_columns_with_missing def remove_missing_data(df,minimum=.1): percent = find_missing(df) number = len(list(filter(lambda x: x>=(1.0-minimum), percent))) names = list(percent.keys()[:number]) df = df.drop(names, 1, errors='ignore') print(f'{number} columns exclude because haven`t minimium data.') return df def one_hot(df, cols): for each in cols: dummies = pd.get_dummies(df[each], prefix=each, drop_first=False) df = pd.concat([df, dummies], axis=1) df = df.drop(cols, axis=1) return df def impute_missing_data(df,minimium_data=.1): columns_missing = count_missing(df) print(f'Total columns with missing values: {count_missing(df)} of a {len(list(df))} columns in df') # remove features without minimium size of information df = remove_missing_data(df,minimium_data) numerical_df, categorical_df = separe_numeric_categoric(df) # Autocomplete using MICE for numerical features. try: df_numerical_complete = fi.MICE(verbose=False).complete(numerical_df.values) n_missing = count_missing(df) print(f'{columns_missing-n_missing} numerical features imputated') # Complete the columns name. temp = pd.DataFrame(columns=numerical_df.columns, data=df_numerical_complete) # df temp com os dados numericos completados e os categóricos. df = pd.concat([temp, categorical_df], axis=1) except Exception as e: print(e) print('Without Missing data in numerical features') missing = find_missing(df) names = missing.keys() n = 0 for i, c in enumerate(missing): if c > 0: col = names[i] print(f'Start the prediction of {col}') clf = RandomForestClassifier() le = LabelEncoder() ## inverter a ordem da predição das categóricas pode melhorar a precisao. categorical_train = list(categorical_df.loc[:,categorical_df.columns != col]) temp = one_hot(df,categorical_train) df1 = temp[temp[col].notnull()] df2 = temp[temp[col].isnull()] df1_x = df1.loc[:, df1.columns != col] df2_x = df2.loc[:, df1.columns != col] df1_y = df1[col] le.fit(df1_y) df1_y = le.transform(df1_y) clf.fit(df1_x, df1_y) df2_yHat = clf.predict(df2_x) df2_yHat = le.inverse_transform(df2_yHat) df2_yHat = pd.DataFrame(data=df2_yHat, columns=[col]) df1_y = le.inverse_transform(df1_y) df1_y = pd.DataFrame(data=df1_y,columns=[col]) df2_x.reset_index(inplace=True) result2 = pd.concat([df2_yHat, df2_x], axis=1) try: del result2['index'] except: pass df1_x.reset_index(inplace=True) result1 = pd.concat([df1_y, df1_x], axis=1) try: del result1['index'] except: pass result = pd.concat([result1, result2]) result = result.set_index(['Id']) df.reset_index() try: df.set_index(['Id'],inplace=True) except: pass df[col] = result[col] n += 1 print(f'Number of columns categorical with missing data solved: {n}') return df df = impute_missing_data(df)
Methods to work around the problem of missing data in machine learning I did not find anything that solved my problem so I wrote a function that mixes some solutions to a Pandas dataframe with missing numerical values (with fancyimpute) and categorical (with a random for
15,772
Methods to work around the problem of missing data in machine learning
Though typically more involved, you can try and created a Maximum Entropy Distribution based on what data you have. http://proceedings.mlr.press/v5/huang09a/huang09a.pdf
Methods to work around the problem of missing data in machine learning
Though typically more involved, you can try and created a Maximum Entropy Distribution based on what data you have. http://proceedings.mlr.press/v5/huang09a/huang09a.pdf
Methods to work around the problem of missing data in machine learning Though typically more involved, you can try and created a Maximum Entropy Distribution based on what data you have. http://proceedings.mlr.press/v5/huang09a/huang09a.pdf
Methods to work around the problem of missing data in machine learning Though typically more involved, you can try and created a Maximum Entropy Distribution based on what data you have. http://proceedings.mlr.press/v5/huang09a/huang09a.pdf
15,773
How to respond to reviewers asking for p-values in bayesian multilevel model?
First, a quick clarification: Although the likelihood is indeed not the posterior, p-values are not so much inconsistent with Bayesian inference as usually just a different thing, for all the reasons that confidence intervals may or may not line up with credible intervals. (Although not necessarily an entirely different thing, as shown by posterior predictive checking, which really does involve p-values.) However I'm guessing that this level of sophistication is not what the reviewer has in mind. I'd guess they just 'know' that statistical models are meant to have p-values, so they've asked for them. So the question remains: how to respond? When 'reviewer wants an X' I have found it useful to ask myself two related questions: Motivation: What do they want X to do for them? Rational reconstruction: What would be most similar-sounding sensible thing they could have asked for instead of X if they wanted to do that? Then give them that instead. The advantage of an ignorant reviewer (who may nevertheless be smart and right about the paper) is that they seldom have a clear idea of what they mean when they ask for X. This means that if you reconstruct them asking a better question, they'll be content to see you answer it instead. In your case, it's quite possible that the reviewer wants a parallel frequentist analysis, though I doubt it. What I think you want to work with is the reviewer's hint that they want p-values to 'to better understand the model'. Your job, I think, is to parse this in a way that makes the reviewer sound wise. Presumably there were a few following sentences noting what was unclear from the paper. Perhaps there were some effects of interest to the reviewer that could not be reconstructed from your parameter marginals, or some quantities that would illuminate what the model would say about cases of interest to them, or a lack single number summaries... If you can identify these concerns then you can wrap up your response in the following forms (original request in square brackets): "the reviewer [demands a p-value for an interaction term] was concerned that it was unclear from our presentation how A varied with B, so in Figure 2 we show..." or "the reviewer wondered [whether we could reject the hypothesis that the effect of A is zero] about the direction of the effect of A. Table 3 shows that this model gives a 99% probability that this is negative" or "the reviewer wonders [whether our model is significantly better fitting than a model containing only A] how our model compared to one containing only A. We address this question by comparing it to ... by using DIC / computing a Bayes Factor / showing our inferences about A are robust to the inclusion of B" etc. In each case there is a close translation of the original request and an answer. Caveats: this strategy seems to work best when the reviewer is a subject matter expert with a relatively weak understanding of statistics. It does not work with the self-identified statistically sophisticated reviewer who actually does want an X because they like Xs or read about them somewhere recently. I have no suggestions for the latter. Finally, I would strongly recommend not saying anything even faintly religious about Bayes being a different paradigm and the reviewers questions making no sense within it. Even if this is true, it makes everybody grumpy for no real gain.
How to respond to reviewers asking for p-values in bayesian multilevel model?
First, a quick clarification: Although the likelihood is indeed not the posterior, p-values are not so much inconsistent with Bayesian inference as usually just a different thing, for all the reasons
How to respond to reviewers asking for p-values in bayesian multilevel model? First, a quick clarification: Although the likelihood is indeed not the posterior, p-values are not so much inconsistent with Bayesian inference as usually just a different thing, for all the reasons that confidence intervals may or may not line up with credible intervals. (Although not necessarily an entirely different thing, as shown by posterior predictive checking, which really does involve p-values.) However I'm guessing that this level of sophistication is not what the reviewer has in mind. I'd guess they just 'know' that statistical models are meant to have p-values, so they've asked for them. So the question remains: how to respond? When 'reviewer wants an X' I have found it useful to ask myself two related questions: Motivation: What do they want X to do for them? Rational reconstruction: What would be most similar-sounding sensible thing they could have asked for instead of X if they wanted to do that? Then give them that instead. The advantage of an ignorant reviewer (who may nevertheless be smart and right about the paper) is that they seldom have a clear idea of what they mean when they ask for X. This means that if you reconstruct them asking a better question, they'll be content to see you answer it instead. In your case, it's quite possible that the reviewer wants a parallel frequentist analysis, though I doubt it. What I think you want to work with is the reviewer's hint that they want p-values to 'to better understand the model'. Your job, I think, is to parse this in a way that makes the reviewer sound wise. Presumably there were a few following sentences noting what was unclear from the paper. Perhaps there were some effects of interest to the reviewer that could not be reconstructed from your parameter marginals, or some quantities that would illuminate what the model would say about cases of interest to them, or a lack single number summaries... If you can identify these concerns then you can wrap up your response in the following forms (original request in square brackets): "the reviewer [demands a p-value for an interaction term] was concerned that it was unclear from our presentation how A varied with B, so in Figure 2 we show..." or "the reviewer wondered [whether we could reject the hypothesis that the effect of A is zero] about the direction of the effect of A. Table 3 shows that this model gives a 99% probability that this is negative" or "the reviewer wonders [whether our model is significantly better fitting than a model containing only A] how our model compared to one containing only A. We address this question by comparing it to ... by using DIC / computing a Bayes Factor / showing our inferences about A are robust to the inclusion of B" etc. In each case there is a close translation of the original request and an answer. Caveats: this strategy seems to work best when the reviewer is a subject matter expert with a relatively weak understanding of statistics. It does not work with the self-identified statistically sophisticated reviewer who actually does want an X because they like Xs or read about them somewhere recently. I have no suggestions for the latter. Finally, I would strongly recommend not saying anything even faintly religious about Bayes being a different paradigm and the reviewers questions making no sense within it. Even if this is true, it makes everybody grumpy for no real gain.
How to respond to reviewers asking for p-values in bayesian multilevel model? First, a quick clarification: Although the likelihood is indeed not the posterior, p-values are not so much inconsistent with Bayesian inference as usually just a different thing, for all the reasons
15,774
How to explain hypothesis testing for teenagers in less than 10 minutes?
I think you should start with asking them what they think it really means to say about a person that he or she is able to tell the difference between coca-cola and pepsi. What can such a person do that others can not do? Most of them will not have any such definition, and will not be able to produce one if asked. However, a meaning of that phrase is what statistics gives us, and that is what you can bring with your "a taste for statistics" class. One of the points of statistics is to give an exact answer to the question: "what does it mean to say of someone that he or she is able to tell the difference between coca-cola and pepsi" The answer is: he or she is better than a guessing-machine to classify cups in a blind test. The guessing machine can not tell the difference, it simply guesses all the time. The guessing machine is a useful invention for us because we know that it does not have the ability. The results of the guessing machine are useful because they show what we should expect from someone who lacks the ability that we test for. To test whether a person is able to tell the difference between coca-cola and pepsi, one must compare his or hers classifications of cups in a blind test to the classification that a guessing machine would do. Only if s/he is better than the guessing machine, s/he is able to tell the difference. How, then, do you determine whether one result is better than another result? What if they are almost the same? If two persons classify a small number of cups, it's not really fair to say that one is better than the other if the results are almost the same. Perhaps the winner just happened to be lucky today, and the results would have been reversed if the competition was repeated tomorrow? If we are to have a trustworthy result, it can not be based on a tiny number of classifications, because then chance can decide the result. Remember, you don't have to be perfect to have the ability, you just have to be better than the guessing machine. In fact, if the number of classifications is too small, not even a person that always identifies coca-cola correctly will be able to show that s/he is better than the guessing machine. For example, if there is only one cup to classify, even the guessing machine will have 50 per cent chance to classify completely correct. That's not good, because that means that in 50 per cent of the trials, we would falsely conclude that a good coca-cola identifier is no better than the guessing machine. Very unfair. The more cups there are to classify, the more opportunities for the guessing machine's inability to be revealed and the more opportunities for the good coca-cola identifier to show off. 10 cups might be a good place to start. How many right answers must a human then have to show that he or she is better than the machine? Ask them what they would guess. Then let them use the machine and find out how good it is, i.e. let all pupils generate a series of ten guesses, eg. using a dice or a random generator on the smartphone. To be pedagogical, you should prepare a series of ten right answers, which the guesses are to be evaluated against. Record all the results on the board. Print the sorted results on the board. Explain that a human would have to be better than 95 per cent of those results before a statistician would acknowledge his or her ability to tell the difference between coca-cola and pepsi. Draw the line that separates the 95% worst results from the top 5% results. Then, let a few pupils try classifying 10 cups. By now the pupils should know how many right they need to have to prove that they can tell the difference. All this is not really doable in 10 minutes though.
How to explain hypothesis testing for teenagers in less than 10 minutes?
I think you should start with asking them what they think it really means to say about a person that he or she is able to tell the difference between coca-cola and pepsi. What can such a person do tha
How to explain hypothesis testing for teenagers in less than 10 minutes? I think you should start with asking them what they think it really means to say about a person that he or she is able to tell the difference between coca-cola and pepsi. What can such a person do that others can not do? Most of them will not have any such definition, and will not be able to produce one if asked. However, a meaning of that phrase is what statistics gives us, and that is what you can bring with your "a taste for statistics" class. One of the points of statistics is to give an exact answer to the question: "what does it mean to say of someone that he or she is able to tell the difference between coca-cola and pepsi" The answer is: he or she is better than a guessing-machine to classify cups in a blind test. The guessing machine can not tell the difference, it simply guesses all the time. The guessing machine is a useful invention for us because we know that it does not have the ability. The results of the guessing machine are useful because they show what we should expect from someone who lacks the ability that we test for. To test whether a person is able to tell the difference between coca-cola and pepsi, one must compare his or hers classifications of cups in a blind test to the classification that a guessing machine would do. Only if s/he is better than the guessing machine, s/he is able to tell the difference. How, then, do you determine whether one result is better than another result? What if they are almost the same? If two persons classify a small number of cups, it's not really fair to say that one is better than the other if the results are almost the same. Perhaps the winner just happened to be lucky today, and the results would have been reversed if the competition was repeated tomorrow? If we are to have a trustworthy result, it can not be based on a tiny number of classifications, because then chance can decide the result. Remember, you don't have to be perfect to have the ability, you just have to be better than the guessing machine. In fact, if the number of classifications is too small, not even a person that always identifies coca-cola correctly will be able to show that s/he is better than the guessing machine. For example, if there is only one cup to classify, even the guessing machine will have 50 per cent chance to classify completely correct. That's not good, because that means that in 50 per cent of the trials, we would falsely conclude that a good coca-cola identifier is no better than the guessing machine. Very unfair. The more cups there are to classify, the more opportunities for the guessing machine's inability to be revealed and the more opportunities for the good coca-cola identifier to show off. 10 cups might be a good place to start. How many right answers must a human then have to show that he or she is better than the machine? Ask them what they would guess. Then let them use the machine and find out how good it is, i.e. let all pupils generate a series of ten guesses, eg. using a dice or a random generator on the smartphone. To be pedagogical, you should prepare a series of ten right answers, which the guesses are to be evaluated against. Record all the results on the board. Print the sorted results on the board. Explain that a human would have to be better than 95 per cent of those results before a statistician would acknowledge his or her ability to tell the difference between coca-cola and pepsi. Draw the line that separates the 95% worst results from the top 5% results. Then, let a few pupils try classifying 10 cups. By now the pupils should know how many right they need to have to prove that they can tell the difference. All this is not really doable in 10 minutes though.
How to explain hypothesis testing for teenagers in less than 10 minutes? I think you should start with asking them what they think it really means to say about a person that he or she is able to tell the difference between coca-cola and pepsi. What can such a person do tha
15,775
How to explain hypothesis testing for teenagers in less than 10 minutes?
Working with soda sounds fun, and the test of whether teenagers can actually tell the difference between sodas makes sense once you have a reasonable knowledge of hypothesis testing. The problem might be that this question: "can you actually tell the difference between sodas?" is complicated by lots of other stuff in the minds of teens, like "who is good and who is bad at testing sodas?", "is there actually any difference between the sodas?" I've never taught teens stats, but I've always fantasized about using a loaded die, or biased coin. Die more interesting, but statistically more challenging. With the coin example, a coin either is or is not fair. There's no being good at flipping coins. There's no deciding whether it's heads or tails. If we flip a coin for who wins $100, and it comes up heads (you win!), I might say, "Hey. How do I know whether that coin is fair? I bet you rigged the competition!". You say "Oh yeah? Prove it." The fairly obvious solution is to flip the coin over and over to see whether it comes up more heads than tails. We flip it, and it comes up heads. "Ahha! I say. Seee! It's biased towards heads!" And so on. Good biased coins don't exist, but biased dice do -- you can buy one on Amazon. You could offer students a prize if they can win some number of rolls. But you know you'll win. They'll be angry. You say, OK, I'll give you the prize if you can prove this die is biased, with say, 95% confidence. Then move on to soda. The prize could even be a soda party! "Hey, I wonder whether you guys can tell the difference between coke and pepsi..."
How to explain hypothesis testing for teenagers in less than 10 minutes?
Working with soda sounds fun, and the test of whether teenagers can actually tell the difference between sodas makes sense once you have a reasonable knowledge of hypothesis testing. The problem might
How to explain hypothesis testing for teenagers in less than 10 minutes? Working with soda sounds fun, and the test of whether teenagers can actually tell the difference between sodas makes sense once you have a reasonable knowledge of hypothesis testing. The problem might be that this question: "can you actually tell the difference between sodas?" is complicated by lots of other stuff in the minds of teens, like "who is good and who is bad at testing sodas?", "is there actually any difference between the sodas?" I've never taught teens stats, but I've always fantasized about using a loaded die, or biased coin. Die more interesting, but statistically more challenging. With the coin example, a coin either is or is not fair. There's no being good at flipping coins. There's no deciding whether it's heads or tails. If we flip a coin for who wins $100, and it comes up heads (you win!), I might say, "Hey. How do I know whether that coin is fair? I bet you rigged the competition!". You say "Oh yeah? Prove it." The fairly obvious solution is to flip the coin over and over to see whether it comes up more heads than tails. We flip it, and it comes up heads. "Ahha! I say. Seee! It's biased towards heads!" And so on. Good biased coins don't exist, but biased dice do -- you can buy one on Amazon. You could offer students a prize if they can win some number of rolls. But you know you'll win. They'll be angry. You say, OK, I'll give you the prize if you can prove this die is biased, with say, 95% confidence. Then move on to soda. The prize could even be a soda party! "Hey, I wonder whether you guys can tell the difference between coke and pepsi..."
How to explain hypothesis testing for teenagers in less than 10 minutes? Working with soda sounds fun, and the test of whether teenagers can actually tell the difference between sodas makes sense once you have a reasonable knowledge of hypothesis testing. The problem might
15,776
How to explain hypothesis testing for teenagers in less than 10 minutes?
Consider someone doing target practice with a shotgun, which shoots bursts of pellets in the direction of the barrel. Null Hypothesis: I'm a good shooter, and my barrel is perfectly on target. Not left, not right, but straight at it. My error is 0. Alternate Hypothesis: I'm a bad shooter, and my barrel is off target. Just left or just right of the target. My error is e>0 or e<0. Since any measurement has a certain average error (i.e. standard error), a measurement that says "off target" is possible, even if I'm shooting straight. I'll need to not "hit" my target (at all, even with each shot being a burst/spread) a certain number of times, before you can call me a bad shooter and choose the Alternate Hypothesis.
How to explain hypothesis testing for teenagers in less than 10 minutes?
Consider someone doing target practice with a shotgun, which shoots bursts of pellets in the direction of the barrel. Null Hypothesis: I'm a good shooter, and my barrel is perfectly on target. Not lef
How to explain hypothesis testing for teenagers in less than 10 minutes? Consider someone doing target practice with a shotgun, which shoots bursts of pellets in the direction of the barrel. Null Hypothesis: I'm a good shooter, and my barrel is perfectly on target. Not left, not right, but straight at it. My error is 0. Alternate Hypothesis: I'm a bad shooter, and my barrel is off target. Just left or just right of the target. My error is e>0 or e<0. Since any measurement has a certain average error (i.e. standard error), a measurement that says "off target" is possible, even if I'm shooting straight. I'll need to not "hit" my target (at all, even with each shot being a burst/spread) a certain number of times, before you can call me a bad shooter and choose the Alternate Hypothesis.
How to explain hypothesis testing for teenagers in less than 10 minutes? Consider someone doing target practice with a shotgun, which shoots bursts of pellets in the direction of the barrel. Null Hypothesis: I'm a good shooter, and my barrel is perfectly on target. Not lef
15,777
How to explain hypothesis testing for teenagers in less than 10 minutes?
Assume the kids can't tell the difference and decide by chance. Then each kid has a 50% chance of guessing it right. So you expect (expected value) that in this case, 5 kids do it right and 5 kids err. Of course, as it is by chance, it is also possible that 6 kids err and 4 get it right, and so on. On the opposite side, even if the kids can tell the difference, it is possible, that by chance one of them errs. Intuitively, it is clear, that if the kids guess by chance, it is rather improbable that all kids give the correct answer. In this case one would rather believe that the kids actually could taste the difference between both drinks. In other words, we don't expect improbable events to be observed. So if we observed an event that is improbable under the 50-50 scanario, we rather believe that this scenario is false and the kids can distinguish between Coke and Pepsi. But what does "rather improbable" and "rather believe" mean? Let your pupils choose $\alpha$: "If we observe an event from the extreme end contradicting the 50-50 hypothesis, which probability may it at most have such that you don't believe this hypothesis any more?" Hope they don't answer $\alpha \leq 0.00098$ Write their $\alpha$ at the board. I assume $\alpha=0.05$. So you and your pupils agree: If we observe an event that belongs to the upper 5% of extreme events contradicting the 50-50 scenario, we don't belive in this scenario any more (reject the hypothesis). Now calculate the binomial distribution with them. $P(\textrm{all kids guess it right})=0.00098$, $P(\textrm{only one kid confuses Coke with Pepsi})=0.01074$ and $P(\textrm{only two kids confuse})=0.05468$. Obviously, you'll only conclude that there is a difference between both beverages, if at most one kid confuses them. This is the moment where you conduct the experiment. Do it thoroughly with all 10 pupils, even if you just calculated that you could stop after the second error. Then record the results and keep them. You'll need the results if you want to explain meta-analyses to them. (By the way, the historical example is about tasting if the milk or the tea has been poured first into the cup. The tea tasting lady.)
How to explain hypothesis testing for teenagers in less than 10 minutes?
Assume the kids can't tell the difference and decide by chance. Then each kid has a 50% chance of guessing it right. So you expect (expected value) that in this case, 5 kids do it right and 5 kids err
How to explain hypothesis testing for teenagers in less than 10 minutes? Assume the kids can't tell the difference and decide by chance. Then each kid has a 50% chance of guessing it right. So you expect (expected value) that in this case, 5 kids do it right and 5 kids err. Of course, as it is by chance, it is also possible that 6 kids err and 4 get it right, and so on. On the opposite side, even if the kids can tell the difference, it is possible, that by chance one of them errs. Intuitively, it is clear, that if the kids guess by chance, it is rather improbable that all kids give the correct answer. In this case one would rather believe that the kids actually could taste the difference between both drinks. In other words, we don't expect improbable events to be observed. So if we observed an event that is improbable under the 50-50 scanario, we rather believe that this scenario is false and the kids can distinguish between Coke and Pepsi. But what does "rather improbable" and "rather believe" mean? Let your pupils choose $\alpha$: "If we observe an event from the extreme end contradicting the 50-50 hypothesis, which probability may it at most have such that you don't believe this hypothesis any more?" Hope they don't answer $\alpha \leq 0.00098$ Write their $\alpha$ at the board. I assume $\alpha=0.05$. So you and your pupils agree: If we observe an event that belongs to the upper 5% of extreme events contradicting the 50-50 scenario, we don't belive in this scenario any more (reject the hypothesis). Now calculate the binomial distribution with them. $P(\textrm{all kids guess it right})=0.00098$, $P(\textrm{only one kid confuses Coke with Pepsi})=0.01074$ and $P(\textrm{only two kids confuse})=0.05468$. Obviously, you'll only conclude that there is a difference between both beverages, if at most one kid confuses them. This is the moment where you conduct the experiment. Do it thoroughly with all 10 pupils, even if you just calculated that you could stop after the second error. Then record the results and keep them. You'll need the results if you want to explain meta-analyses to them. (By the way, the historical example is about tasting if the milk or the tea has been poured first into the cup. The tea tasting lady.)
How to explain hypothesis testing for teenagers in less than 10 minutes? Assume the kids can't tell the difference and decide by chance. Then each kid has a 50% chance of guessing it right. So you expect (expected value) that in this case, 5 kids do it right and 5 kids err
15,778
How to explain hypothesis testing for teenagers in less than 10 minutes?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. Show this video which is the most intuitive explanation of hypothesis testing that I have ever seen - https://www.youtube.com/watch?v=UApFKiK4Hi8
How to explain hypothesis testing for teenagers in less than 10 minutes?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
How to explain hypothesis testing for teenagers in less than 10 minutes? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. Show this video which is the most intuitive explanation of hypothesis testing that I have ever seen - https://www.youtube.com/watch?v=UApFKiK4Hi8
How to explain hypothesis testing for teenagers in less than 10 minutes? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
15,779
How to explain hypothesis testing for teenagers in less than 10 minutes?
The children tasting coke experiment is a good example to introduce hypothesis testing, as its equivalent the lady tasting tea experiment showed. However, evaluating those experiments is not very intuitive because the null hypothesis involves the binomial distribution with p=0.5, and it is not straightforward. In my usual introduction to hypothesis testing, I try to overcome this drawback by using only the all-successes case in the binomial distribution, whose probability can be computed as p^n even by people who doesn't know about the binomial probability. In my favourite example, I like roasted chestnuts and I buy a handful of them from a street vendor. I get them at a discount price because they come from a big bag where 10% of chestnuts have a worm hole - here I try to make clear that the bag has been well mixed so that my handful of chestnuts is a random sample of the chestnuts in the bag and the vendor's statement means that every chestnut has an independent probability of 10% of having a worm hole. As I start enjoying my roasted chestnuts, I take them one by one and check them for worm holes before eating them. When I check the first chestnut, I see a worm hole, and I wonder if the vendor lied to me - I explain here that wondering that is setting my null hypothesis p=10% and my alternative hypothesis p>10%, and I put them in the blackboard. Do I have a reason to doubt that p=10% when I got one bad chestnut out of one? Well, 10% of people performing the same experiment would get the same result, so I can think I just had bad luck. Then, I take the second chestnut and it has a worm hole, too. Two out of two has a probability of just 1% if the vendor hasn't lied to me. I could have had a very bad luck, but I get very suspicious about the vendor. The third chestnut has a worm hole, too. Getting the three chestnuts with worms out of three wouldn't be impossible assuming that the vendor is fair and p=10%, but it would be very unlikely (probability=0.1%). Therefore now I have a strong reason to doubt on the vendor's work and I raise a complaint and ask to be refunded. Of course, this kind of successive test have some theoretical problems, but it doesn't matter much to show the idea of an hypothesis tests. In fact, the most important idea that is not covered in that example is that in hypothesis tests we compute the probability of the results we get or anything worse - in my example this was avoided by just getting the worst possible result. I have used this example several times with freshmen at university - which are still technically teenagers - but I think it could work well with younger teenagers, too.
How to explain hypothesis testing for teenagers in less than 10 minutes?
The children tasting coke experiment is a good example to introduce hypothesis testing, as its equivalent the lady tasting tea experiment showed. However, evaluating those experiments is not very intu
How to explain hypothesis testing for teenagers in less than 10 minutes? The children tasting coke experiment is a good example to introduce hypothesis testing, as its equivalent the lady tasting tea experiment showed. However, evaluating those experiments is not very intuitive because the null hypothesis involves the binomial distribution with p=0.5, and it is not straightforward. In my usual introduction to hypothesis testing, I try to overcome this drawback by using only the all-successes case in the binomial distribution, whose probability can be computed as p^n even by people who doesn't know about the binomial probability. In my favourite example, I like roasted chestnuts and I buy a handful of them from a street vendor. I get them at a discount price because they come from a big bag where 10% of chestnuts have a worm hole - here I try to make clear that the bag has been well mixed so that my handful of chestnuts is a random sample of the chestnuts in the bag and the vendor's statement means that every chestnut has an independent probability of 10% of having a worm hole. As I start enjoying my roasted chestnuts, I take them one by one and check them for worm holes before eating them. When I check the first chestnut, I see a worm hole, and I wonder if the vendor lied to me - I explain here that wondering that is setting my null hypothesis p=10% and my alternative hypothesis p>10%, and I put them in the blackboard. Do I have a reason to doubt that p=10% when I got one bad chestnut out of one? Well, 10% of people performing the same experiment would get the same result, so I can think I just had bad luck. Then, I take the second chestnut and it has a worm hole, too. Two out of two has a probability of just 1% if the vendor hasn't lied to me. I could have had a very bad luck, but I get very suspicious about the vendor. The third chestnut has a worm hole, too. Getting the three chestnuts with worms out of three wouldn't be impossible assuming that the vendor is fair and p=10%, but it would be very unlikely (probability=0.1%). Therefore now I have a strong reason to doubt on the vendor's work and I raise a complaint and ask to be refunded. Of course, this kind of successive test have some theoretical problems, but it doesn't matter much to show the idea of an hypothesis tests. In fact, the most important idea that is not covered in that example is that in hypothesis tests we compute the probability of the results we get or anything worse - in my example this was avoided by just getting the worst possible result. I have used this example several times with freshmen at university - which are still technically teenagers - but I think it could work well with younger teenagers, too.
How to explain hypothesis testing for teenagers in less than 10 minutes? The children tasting coke experiment is a good example to introduce hypothesis testing, as its equivalent the lady tasting tea experiment showed. However, evaluating those experiments is not very intu
15,780
Introductory texts on structural econometrics
I am not aware of anything like this. Paarsch and Hong's An Introduction to the Structural Econometrics of Auction Data and Ada and Cooper's Dynamic Economics come closest. The usual classroom approach is to read classic papers and perhaps replicate one along the way. Here's one example (Jean-Marc Robin). Here's are more labor oriented lecture notes (Chris Taber).
Introductory texts on structural econometrics
I am not aware of anything like this. Paarsch and Hong's An Introduction to the Structural Econometrics of Auction Data and Ada and Cooper's Dynamic Economics come closest. The usual classroom approa
Introductory texts on structural econometrics I am not aware of anything like this. Paarsch and Hong's An Introduction to the Structural Econometrics of Auction Data and Ada and Cooper's Dynamic Economics come closest. The usual classroom approach is to read classic papers and perhaps replicate one along the way. Here's one example (Jean-Marc Robin). Here's are more labor oriented lecture notes (Chris Taber).
Introductory texts on structural econometrics I am not aware of anything like this. Paarsch and Hong's An Introduction to the Structural Econometrics of Auction Data and Ada and Cooper's Dynamic Economics come closest. The usual classroom approa
15,781
Introductory texts on structural econometrics
If you also consider structural methods for macroeconomics then perhaps the book Structural Macroeconometrics by DeJong and Dave will be interesting. Mathias Andre has some structural econometrics problem sets on his website. The questions are similar to the example in chapter one of Wolpin's book you mentioned in the comment to the previous answer and there are also examples of estimating value functions. There are some corrections to Wolpin's book here. Victor Aguirregabiria makes data and code to several estimation procedures available on his website. So does Aviv Nevo. Abbring and Klein have published Matlab code for dynamic discrete choice model. Simon Quinn has lecture notes that start off at the basics and then go on telling you how to use maximum likelihood in estimating utility functions. Data and code should also be on his website. For this purpose the book Maximum Likelihood Estimation by William Gould and his co-authors is valuable because maximum likelihood and simulated maximum likelihood are often used tools in structural econometrics.
Introductory texts on structural econometrics
If you also consider structural methods for macroeconomics then perhaps the book Structural Macroeconometrics by DeJong and Dave will be interesting. Mathias Andre has some structural econometrics pro
Introductory texts on structural econometrics If you also consider structural methods for macroeconomics then perhaps the book Structural Macroeconometrics by DeJong and Dave will be interesting. Mathias Andre has some structural econometrics problem sets on his website. The questions are similar to the example in chapter one of Wolpin's book you mentioned in the comment to the previous answer and there are also examples of estimating value functions. There are some corrections to Wolpin's book here. Victor Aguirregabiria makes data and code to several estimation procedures available on his website. So does Aviv Nevo. Abbring and Klein have published Matlab code for dynamic discrete choice model. Simon Quinn has lecture notes that start off at the basics and then go on telling you how to use maximum likelihood in estimating utility functions. Data and code should also be on his website. For this purpose the book Maximum Likelihood Estimation by William Gould and his co-authors is valuable because maximum likelihood and simulated maximum likelihood are often used tools in structural econometrics.
Introductory texts on structural econometrics If you also consider structural methods for macroeconomics then perhaps the book Structural Macroeconometrics by DeJong and Dave will be interesting. Mathias Andre has some structural econometrics pro
15,782
Introductory texts on structural econometrics
One problem is that structural estimation varies a lot depending on what field you are in, as the models used vary a lot. To me, at least, structural estimation in labor and marketing looks wildly different from finance and macro. It might be helpful to separate estimation methods (method of simulated moments, simulated maximum likelihood, Bayesian filtering) from model computation (dynamic programming and value function iteration). For estimation methods Gourieroux and Monfort are a good in-depth survey. For model solution Miranda and Fackler are another good reference, though you can also check out any number of other books on dynamic economics. In combining model solution and estimation, for finance this survey is a very good place to start, for Macro you've already been pointed to DeJong and Dave, and I would add Rust (1994) to an already long list of IO/marketing surveys you're looking at, as well as Kenneth Train's textbook.
Introductory texts on structural econometrics
One problem is that structural estimation varies a lot depending on what field you are in, as the models used vary a lot. To me, at least, structural estimation in labor and marketing looks wildly dif
Introductory texts on structural econometrics One problem is that structural estimation varies a lot depending on what field you are in, as the models used vary a lot. To me, at least, structural estimation in labor and marketing looks wildly different from finance and macro. It might be helpful to separate estimation methods (method of simulated moments, simulated maximum likelihood, Bayesian filtering) from model computation (dynamic programming and value function iteration). For estimation methods Gourieroux and Monfort are a good in-depth survey. For model solution Miranda and Fackler are another good reference, though you can also check out any number of other books on dynamic economics. In combining model solution and estimation, for finance this survey is a very good place to start, for Macro you've already been pointed to DeJong and Dave, and I would add Rust (1994) to an already long list of IO/marketing surveys you're looking at, as well as Kenneth Train's textbook.
Introductory texts on structural econometrics One problem is that structural estimation varies a lot depending on what field you are in, as the models used vary a lot. To me, at least, structural estimation in labor and marketing looks wildly dif
15,783
Brant test in R [closed]
I implemented the brant test in R. The package and function is called brant and it's now available on CRAN. The brant test was defined by Rollin Brant to test the parallel regression assumption (Brant, R. (1990) Assessing proportionality in the proportional odds model for ordinal logistic regression. Biometrics, 46, 1171–1178). Here is a code example: data = MASS::survey data$Smoke = ordered(MASS::survey$Smoke, levels=c("Never","Occas","Regul","Heavy")) model1 = MASS::polr(Smoke ~ Sex + Height, data=data, Hess=TRUE) brant(model1) In the example, the parallel regression assumption holds, because all p-values are above 0.05. The Omnibus is for the whole model, the rest for the indvidual coefficents.
Brant test in R [closed]
I implemented the brant test in R. The package and function is called brant and it's now available on CRAN. The brant test was defined by Rollin Brant to test the parallel regression assumption (Bran
Brant test in R [closed] I implemented the brant test in R. The package and function is called brant and it's now available on CRAN. The brant test was defined by Rollin Brant to test the parallel regression assumption (Brant, R. (1990) Assessing proportionality in the proportional odds model for ordinal logistic regression. Biometrics, 46, 1171–1178). Here is a code example: data = MASS::survey data$Smoke = ordered(MASS::survey$Smoke, levels=c("Never","Occas","Regul","Heavy")) model1 = MASS::polr(Smoke ~ Sex + Height, data=data, Hess=TRUE) brant(model1) In the example, the parallel regression assumption holds, because all p-values are above 0.05. The Omnibus is for the whole model, the rest for the indvidual coefficents.
Brant test in R [closed] I implemented the brant test in R. The package and function is called brant and it's now available on CRAN. The brant test was defined by Rollin Brant to test the parallel regression assumption (Bran
15,784
Brant test in R [closed]
Yes -- in fact the ordinal package that you linked can do it (although they don't call it the Brant test). Take a look at pages 6 and 7 of your link, which demonstrate "a likelihood ratio test of the equal slopes or proportional odds assumption," which is exactly what you are looking for.
Brant test in R [closed]
Yes -- in fact the ordinal package that you linked can do it (although they don't call it the Brant test). Take a look at pages 6 and 7 of your link, which demonstrate "a likelihood ratio test of the
Brant test in R [closed] Yes -- in fact the ordinal package that you linked can do it (although they don't call it the Brant test). Take a look at pages 6 and 7 of your link, which demonstrate "a likelihood ratio test of the equal slopes or proportional odds assumption," which is exactly what you are looking for.
Brant test in R [closed] Yes -- in fact the ordinal package that you linked can do it (although they don't call it the Brant test). Take a look at pages 6 and 7 of your link, which demonstrate "a likelihood ratio test of the
15,785
Brant test in R [closed]
Some notes on the topic The R package VGAM in the cumulative command (Ordinal Regression with Cumulative Probabilities) allows to change the proportional odds assumptions, with the option parallel=FALSE. It is known to be a common problem (from the book: Regression Models for Categorical Dependent Variables Using Stata, Second Edition, By J. Scott Long, Jeremy Freese) "A Caveat regarding the parallel regression assumption: We find that the parallel regression assumption (PRA) is frequently violated. When this is rejected alternatives models that do not impose the constraint of parallel regressions should be considered. Violation of the PRA is not rationale for usig OLS regression since the assumptions implied by the application of the LRM to ordinal data are even stronger. Alternative models that can be considered include models for nominal outcomes [...] Stereotype Logistic model or Stereotype ordered model; the Generalized Ordered Logit model; the continuation Ratio model, are alternatives" (page 221) This paper goes in depth in this topic, being clear and well written, but it does not consider the VGAM package or the "cumulative" command: Ordinal logistic regression in epidemiological studies
Brant test in R [closed]
Some notes on the topic The R package VGAM in the cumulative command (Ordinal Regression with Cumulative Probabilities) allows to change the proportional odds assumptions, with the option parallel=FAL
Brant test in R [closed] Some notes on the topic The R package VGAM in the cumulative command (Ordinal Regression with Cumulative Probabilities) allows to change the proportional odds assumptions, with the option parallel=FALSE. It is known to be a common problem (from the book: Regression Models for Categorical Dependent Variables Using Stata, Second Edition, By J. Scott Long, Jeremy Freese) "A Caveat regarding the parallel regression assumption: We find that the parallel regression assumption (PRA) is frequently violated. When this is rejected alternatives models that do not impose the constraint of parallel regressions should be considered. Violation of the PRA is not rationale for usig OLS regression since the assumptions implied by the application of the LRM to ordinal data are even stronger. Alternative models that can be considered include models for nominal outcomes [...] Stereotype Logistic model or Stereotype ordered model; the Generalized Ordered Logit model; the continuation Ratio model, are alternatives" (page 221) This paper goes in depth in this topic, being clear and well written, but it does not consider the VGAM package or the "cumulative" command: Ordinal logistic regression in epidemiological studies
Brant test in R [closed] Some notes on the topic The R package VGAM in the cumulative command (Ordinal Regression with Cumulative Probabilities) allows to change the proportional odds assumptions, with the option parallel=FAL
15,786
Brant test in R [closed]
This tutorial about ordinal logistic regression in R covers testing the proportional odds assumption.
Brant test in R [closed]
This tutorial about ordinal logistic regression in R covers testing the proportional odds assumption.
Brant test in R [closed] This tutorial about ordinal logistic regression in R covers testing the proportional odds assumption.
Brant test in R [closed] This tutorial about ordinal logistic regression in R covers testing the proportional odds assumption.
15,787
Alternative to sieve / mosaic plots for contingency tables
The book you described sounds like, 'Visualizing Categorical Data,' Michael Friendly. The plot described in the 1st chapter that seems to match your request was described as a type of conceptual model for visualizing contingency table data (loosely described by the author as a dynamic pressure model with observational density), and can be seen in the google preview for Ch 1. The book is geared towards SAS users. A paper on the topic is referenced here: www.datavis.ca/papers/koln/kolnpapr.pdf 'Conceptual Models for Visualizing Contingency Table Data,' Michael Friendly . *incidentally, the author is also listed as one of the authors of the vcd package (as it was specifically inspired by his book mentioned above) -- maybe you could ask him directly if there's a simple modification to one of the built in functions that's not readily apparent. ** The coloring scheme seems to relate the color blue with positive deviations from independence, and red for negative deviations. Although the red scheme makes sense in that context, maybe it would have been more apt to have used green to represent positive deviations. http://www.datavis.ca/papers/asa92.html
Alternative to sieve / mosaic plots for contingency tables
The book you described sounds like, 'Visualizing Categorical Data,' Michael Friendly. The plot described in the 1st chapter that seems to match your request was described as a type of conceptual model
Alternative to sieve / mosaic plots for contingency tables The book you described sounds like, 'Visualizing Categorical Data,' Michael Friendly. The plot described in the 1st chapter that seems to match your request was described as a type of conceptual model for visualizing contingency table data (loosely described by the author as a dynamic pressure model with observational density), and can be seen in the google preview for Ch 1. The book is geared towards SAS users. A paper on the topic is referenced here: www.datavis.ca/papers/koln/kolnpapr.pdf 'Conceptual Models for Visualizing Contingency Table Data,' Michael Friendly . *incidentally, the author is also listed as one of the authors of the vcd package (as it was specifically inspired by his book mentioned above) -- maybe you could ask him directly if there's a simple modification to one of the built in functions that's not readily apparent. ** The coloring scheme seems to relate the color blue with positive deviations from independence, and red for negative deviations. Although the red scheme makes sense in that context, maybe it would have been more apt to have used green to represent positive deviations. http://www.datavis.ca/papers/asa92.html
Alternative to sieve / mosaic plots for contingency tables The book you described sounds like, 'Visualizing Categorical Data,' Michael Friendly. The plot described in the 1st chapter that seems to match your request was described as a type of conceptual model
15,788
Alternative to sieve / mosaic plots for contingency tables
Maybe not what you saw, but for visualization of departures expected under independence correspondence plots are well motivated. http://www.jstatsoft.org/v20/i03/ (An an aside, SAS and M Friendly's book were mistaken about the recommended adjustment and many of the plots had artifacts in them and this may have distracted from their perceived value.)
Alternative to sieve / mosaic plots for contingency tables
Maybe not what you saw, but for visualization of departures expected under independence correspondence plots are well motivated. http://www.jstatsoft.org/v20/i03/ (An an aside, SAS and M Friendly's
Alternative to sieve / mosaic plots for contingency tables Maybe not what you saw, but for visualization of departures expected under independence correspondence plots are well motivated. http://www.jstatsoft.org/v20/i03/ (An an aside, SAS and M Friendly's book were mistaken about the recommended adjustment and many of the plots had artifacts in them and this may have distracted from their perceived value.)
Alternative to sieve / mosaic plots for contingency tables Maybe not what you saw, but for visualization of departures expected under independence correspondence plots are well motivated. http://www.jstatsoft.org/v20/i03/ (An an aside, SAS and M Friendly's
15,789
How to do one-class text classification?
The Spy EM algorithm solves exactly this problem. S-EM is a text learning or classification system that learns from a set of positive and unlabeled examples (no negative examples). It is based on a "spy" technique, naive Bayes and EM algorithm. The basic idea is to combine your positive set with a whole bunch of randomly crawled documents. You initially treat all the crawled documents as the negative class, and learn a naive bayes classifier on that set. Now some of those crawled documents will actually be positive, and you can conservatively relabel any documents that are scored higher than the lowest scoring true positive document. Then you iterate this process until it stablizes.
How to do one-class text classification?
The Spy EM algorithm solves exactly this problem. S-EM is a text learning or classification system that learns from a set of positive and unlabeled examples (no negative examples). It is based on a "
How to do one-class text classification? The Spy EM algorithm solves exactly this problem. S-EM is a text learning or classification system that learns from a set of positive and unlabeled examples (no negative examples). It is based on a "spy" technique, naive Bayes and EM algorithm. The basic idea is to combine your positive set with a whole bunch of randomly crawled documents. You initially treat all the crawled documents as the negative class, and learn a naive bayes classifier on that set. Now some of those crawled documents will actually be positive, and you can conservatively relabel any documents that are scored higher than the lowest scoring true positive document. Then you iterate this process until it stablizes.
How to do one-class text classification? The Spy EM algorithm solves exactly this problem. S-EM is a text learning or classification system that learns from a set of positive and unlabeled examples (no negative examples). It is based on a "
15,790
How to do one-class text classification?
Here is a good thesis about one-class classification: Tax, D. M.: One-class classification - Concept-learning in the absence of counter-examples, PhD thesis, Technische Universiteit Delft, 2001. (pdf) This thesis introduces the method of Support Vector Data Description (SVDD), a one-class support vector machine that finds a minimal hypersphere around the data rather than a hyperplane that separates the data. The thesis also reviews other one-class classifiers.
How to do one-class text classification?
Here is a good thesis about one-class classification: Tax, D. M.: One-class classification - Concept-learning in the absence of counter-examples, PhD thesis, Technische Universiteit Delft, 2001. (p
How to do one-class text classification? Here is a good thesis about one-class classification: Tax, D. M.: One-class classification - Concept-learning in the absence of counter-examples, PhD thesis, Technische Universiteit Delft, 2001. (pdf) This thesis introduces the method of Support Vector Data Description (SVDD), a one-class support vector machine that finds a minimal hypersphere around the data rather than a hyperplane that separates the data. The thesis also reviews other one-class classifiers.
How to do one-class text classification? Here is a good thesis about one-class classification: Tax, D. M.: One-class classification - Concept-learning in the absence of counter-examples, PhD thesis, Technische Universiteit Delft, 2001. (p
15,791
How to do one-class text classification?
Good training requires data that provides good estimates of the individual class probabilities. Every classification problem involves at least two classes. In your case the second class is anyone that is not in the positive class. To form a good decision boundary using Bayes or any other good method is best done with as much training data randomly selected from the class. If you do non random selection you might get a sample that doesn't truly represent the shape of the class conditional densities/distributions and could lead to a poor choice of the decision boundary.
How to do one-class text classification?
Good training requires data that provides good estimates of the individual class probabilities. Every classification problem involves at least two classes. In your case the second class is anyone th
How to do one-class text classification? Good training requires data that provides good estimates of the individual class probabilities. Every classification problem involves at least two classes. In your case the second class is anyone that is not in the positive class. To form a good decision boundary using Bayes or any other good method is best done with as much training data randomly selected from the class. If you do non random selection you might get a sample that doesn't truly represent the shape of the class conditional densities/distributions and could lead to a poor choice of the decision boundary.
How to do one-class text classification? Good training requires data that provides good estimates of the individual class probabilities. Every classification problem involves at least two classes. In your case the second class is anyone th
15,792
How to do one-class text classification?
I agree with Michael. Regarding your question about random selection; yes: you have to select randomly from the complementary set of your 'positives'. If there is any confusion that it is possible that your 'positives' are not fully defined as 'pure positive', if I may use that phrase, then you can also try at the least some kind of matched definition for positives so that you will control on those variables that are generating potentially some contamination on the definition of 'positive'. In this case you have to correspondingly match on the same variables on the 'non-positive' side also.
How to do one-class text classification?
I agree with Michael. Regarding your question about random selection; yes: you have to select randomly from the complementary set of your 'positives'. If there is any confusion that it is possible
How to do one-class text classification? I agree with Michael. Regarding your question about random selection; yes: you have to select randomly from the complementary set of your 'positives'. If there is any confusion that it is possible that your 'positives' are not fully defined as 'pure positive', if I may use that phrase, then you can also try at the least some kind of matched definition for positives so that you will control on those variables that are generating potentially some contamination on the definition of 'positive'. In this case you have to correspondingly match on the same variables on the 'non-positive' side also.
How to do one-class text classification? I agree with Michael. Regarding your question about random selection; yes: you have to select randomly from the complementary set of your 'positives'. If there is any confusion that it is possible
15,793
How to do one-class text classification?
An article that may be of interest is: "Extended nearest shrunken centroid classification: A new method for open-set authorship attribution of texts of varying sizes", Schaalje, Fields, Roper, and Snow. Literary and Linguistic Computing, vol. 26, No. 1, 2011. Which takes a method for attributing a text to a set of authors and extends it to use the possibility that the true author is not in the candidate set. Even if you don't use the NSC method, the ideas in the paper may be useful in thinking about how to proceed.
How to do one-class text classification?
An article that may be of interest is: "Extended nearest shrunken centroid classification: A new method for open-set authorship attribution of texts of varying sizes", Schaalje, Fields, Roper, an
How to do one-class text classification? An article that may be of interest is: "Extended nearest shrunken centroid classification: A new method for open-set authorship attribution of texts of varying sizes", Schaalje, Fields, Roper, and Snow. Literary and Linguistic Computing, vol. 26, No. 1, 2011. Which takes a method for attributing a text to a set of authors and extends it to use the possibility that the true author is not in the candidate set. Even if you don't use the NSC method, the ideas in the paper may be useful in thinking about how to proceed.
How to do one-class text classification? An article that may be of interest is: "Extended nearest shrunken centroid classification: A new method for open-set authorship attribution of texts of varying sizes", Schaalje, Fields, Roper, an
15,794
Logistic Regression and Dataset Structure
Do a logistic regression with covariates "play time" and "goals(home team) - goals(away team)". You will need an interaction effect of these terms since a 2 goal lead at half-time will have a much smaller effect than a 2 goal lead with only 1 minute left. Your response is "victory (home team)". Don't just assume linearity for this, fit a smoothly varying coefficient model for the effect of "goals(home team) - goals(away team)", e.g. in R you could use mgcv's gam function with a model formula like win_home ~ s(time_remaining, by=lead_home). Make lead_home into a factor, so that you get a different effect of time_remaining for every value of lead_home. I would create multiple observations per game, one for every slice of time you are interested in.
Logistic Regression and Dataset Structure
Do a logistic regression with covariates "play time" and "goals(home team) - goals(away team)". You will need an interaction effect of these terms since a 2 goal lead at half-time will have a much sma
Logistic Regression and Dataset Structure Do a logistic regression with covariates "play time" and "goals(home team) - goals(away team)". You will need an interaction effect of these terms since a 2 goal lead at half-time will have a much smaller effect than a 2 goal lead with only 1 minute left. Your response is "victory (home team)". Don't just assume linearity for this, fit a smoothly varying coefficient model for the effect of "goals(home team) - goals(away team)", e.g. in R you could use mgcv's gam function with a model formula like win_home ~ s(time_remaining, by=lead_home). Make lead_home into a factor, so that you get a different effect of time_remaining for every value of lead_home. I would create multiple observations per game, one for every slice of time you are interested in.
Logistic Regression and Dataset Structure Do a logistic regression with covariates "play time" and "goals(home team) - goals(away team)". You will need an interaction effect of these terms since a 2 goal lead at half-time will have a much sma
15,795
Logistic Regression and Dataset Structure
I would start simulating the data from a toy model. Something like: n.games <- 1000 n.slices <- 90 score.away <- score.home <- matrix(0, ncol=n.slices, nrow=n.games) for (j in 2:n.slices) { score.home[ ,j] <- score.home[ , j-1] + (runif(n.games)>.97) score.away[ ,j] <- score.away[ , j-1] + (runif(n.games)>.98) } Now we have something to play with. You could also use the raw data, but I find simulating the data very helpful to think things through. Next I would just plot the data, that is, plot time of the game versus lead home, with the color scale corresponding to the observed probability of winning. score.dif <- score.home-score.away windf <- data.frame(game=1:n.games, win=score.home[ , n.slices] > score.away[, n.slices]) library(reshape) library(ggplot2) dnow <- melt(score.dif) names(dnow) <- c('game', 'time', 'dif') dnow <- merge(dnow, windf) res <- ddply(dnow, c('time', 'dif'), function(x) c(pwin=sum(x$win)/nrow(x))) qplot(time, dif, fill=pwin, data=res, geom='tile') + scale_color_gradient2() This will help you find the support of your data, and give you a raw idea of what the probabilities look like.
Logistic Regression and Dataset Structure
I would start simulating the data from a toy model. Something like: n.games <- 1000 n.slices <- 90 score.away <- score.home <- matrix(0, ncol=n.slices, nrow=n.games) for (j in 2:n.slices) { score
Logistic Regression and Dataset Structure I would start simulating the data from a toy model. Something like: n.games <- 1000 n.slices <- 90 score.away <- score.home <- matrix(0, ncol=n.slices, nrow=n.games) for (j in 2:n.slices) { score.home[ ,j] <- score.home[ , j-1] + (runif(n.games)>.97) score.away[ ,j] <- score.away[ , j-1] + (runif(n.games)>.98) } Now we have something to play with. You could also use the raw data, but I find simulating the data very helpful to think things through. Next I would just plot the data, that is, plot time of the game versus lead home, with the color scale corresponding to the observed probability of winning. score.dif <- score.home-score.away windf <- data.frame(game=1:n.games, win=score.home[ , n.slices] > score.away[, n.slices]) library(reshape) library(ggplot2) dnow <- melt(score.dif) names(dnow) <- c('game', 'time', 'dif') dnow <- merge(dnow, windf) res <- ddply(dnow, c('time', 'dif'), function(x) c(pwin=sum(x$win)/nrow(x))) qplot(time, dif, fill=pwin, data=res, geom='tile') + scale_color_gradient2() This will help you find the support of your data, and give you a raw idea of what the probabilities look like.
Logistic Regression and Dataset Structure I would start simulating the data from a toy model. Something like: n.games <- 1000 n.slices <- 90 score.away <- score.home <- matrix(0, ncol=n.slices, nrow=n.games) for (j in 2:n.slices) { score
15,796
Logistic Regression and Dataset Structure
Check out the stats nerds at Football Outsiders as well as the book Mathletics for some inspiration. The Football Outsiders guys make game predictions based on every play in a football game. Winston in Mathletics uses some techniques such as dynamic programming as well. You can also consider other algorithms such as SVM.
Logistic Regression and Dataset Structure
Check out the stats nerds at Football Outsiders as well as the book Mathletics for some inspiration. The Football Outsiders guys make game predictions based on every play in a football game. Winston
Logistic Regression and Dataset Structure Check out the stats nerds at Football Outsiders as well as the book Mathletics for some inspiration. The Football Outsiders guys make game predictions based on every play in a football game. Winston in Mathletics uses some techniques such as dynamic programming as well. You can also consider other algorithms such as SVM.
Logistic Regression and Dataset Structure Check out the stats nerds at Football Outsiders as well as the book Mathletics for some inspiration. The Football Outsiders guys make game predictions based on every play in a football game. Winston
15,797
LASSO assumptions
I am not an expert on LASSO, but here is my take. First note that OLS is pretty robust to violations of indepence and normality. Then judging from the Theorem 7 and the discussion above it in the article Robust Regression and Lasso (by X. Huan, C. Caramanis and S. Mannor) I guess, that in LASSO regression we are more concerned not with the distribution of $\varepsilon_i$, but in the joint distribution of $(y_i,x_i)$. The theorem relies on the assumption that $(y_i,x_i)$ is a sample, so this is comparable to usual OLS assumptions. But LASSO is less restrictive, it does not constrain $y_i$ to be generated from the linear model. To sum up, the answer to your first question is no. There are no distributional assumptions on $\varepsilon$, all distributional assumptions are on $(y,X)$. Furthermore they are weaker, since in LASSO nothing is postulate on conditional distribution $(y|X)$. Having said that, the answer to the second question is then also no. Since the $\varepsilon$ does not play any role it does not make any sense to analyse them the way you analyse them in OLS (normality tests, heteroscedasticity, Durbin-Watson, etc). You should however analyse them in context how good the model fit was.
LASSO assumptions
I am not an expert on LASSO, but here is my take. First note that OLS is pretty robust to violations of indepence and normality. Then judging from the Theorem 7 and the discussion above it in the ar
LASSO assumptions I am not an expert on LASSO, but here is my take. First note that OLS is pretty robust to violations of indepence and normality. Then judging from the Theorem 7 and the discussion above it in the article Robust Regression and Lasso (by X. Huan, C. Caramanis and S. Mannor) I guess, that in LASSO regression we are more concerned not with the distribution of $\varepsilon_i$, but in the joint distribution of $(y_i,x_i)$. The theorem relies on the assumption that $(y_i,x_i)$ is a sample, so this is comparable to usual OLS assumptions. But LASSO is less restrictive, it does not constrain $y_i$ to be generated from the linear model. To sum up, the answer to your first question is no. There are no distributional assumptions on $\varepsilon$, all distributional assumptions are on $(y,X)$. Furthermore they are weaker, since in LASSO nothing is postulate on conditional distribution $(y|X)$. Having said that, the answer to the second question is then also no. Since the $\varepsilon$ does not play any role it does not make any sense to analyse them the way you analyse them in OLS (normality tests, heteroscedasticity, Durbin-Watson, etc). You should however analyse them in context how good the model fit was.
LASSO assumptions I am not an expert on LASSO, but here is my take. First note that OLS is pretty robust to violations of indepence and normality. Then judging from the Theorem 7 and the discussion above it in the ar
15,798
Why do we call the equations of least square estimation in linear regression the *normal equations*?
I'll give what is perhaps the most common understanding, then some additional details. Normal is a term in geometry (Wikipedia): In geometry, a normal is an object such as a line or vector that is perpendicular to a given object. which in turn appears to come from a term for a carpenter's or mason's square [1] NORM and NORMAL. According to the OED, in Latin norma could mean a square used by carpenters, masons, etc., for obtaining right angles, a right angle or a standard or pattern of practice or behaviour. These meanings are reflected in the mathematical terms based on norm and normal. and from geometry the term moves into vector spaces. The direct answer for "normal equations" is given here: http://mathworld.wolfram.com/NormalEquation.html It is called a normal equation because $b-Ax$ is normal to the range of $A$. (In the usual regression notation that's '$y-Xb$ is normal to the range of $X$') Literally, the least squares residual is perpendicular (at right angles) to the nearest point in the space spanned by $X$. The $y$-vector lies in $n$ dimensions. The X-matrix spans $p$ of those (or $p+1$ depending on how your notation is set up; if $X$ is of full rank, it's the number of columns of X). The least squares solution $X\hat{\beta}$ is the nearest point in that space spanned by $X$ to that $y$-vector (indeed, literally the projection of $y$ onto the space spanned by $X$). It is necessarily the case that by minimizing the sum of squares, the difference $y-X\hat{\beta}$ is orthogonal to the space spanned by $X$. (If it were not, there would be a still smaller solution.) However, as whuber suggests in comments, it's not quite so clear cut. Looking at [1] again: The term NORMAL EQUATION in least squares was introduced by Gauss in 1822 [James A. Landau]. Kruskal & Stigler‘s "Normative Terminology" (in Stigler (1999)) consider various hypotheses about where the term came from but do not find any very satisfactory. However, the method of normal equations is often credited to Legendre, 1805. [1] Miller, J. (ed) "Earliest known uses of some of the words of mathematics, N" in Earliest known uses of some of the words of mathematics
Why do we call the equations of least square estimation in linear regression the *normal equations*?
I'll give what is perhaps the most common understanding, then some additional details. Normal is a term in geometry (Wikipedia): In geometry, a normal is an object such as a line or vector that is pe
Why do we call the equations of least square estimation in linear regression the *normal equations*? I'll give what is perhaps the most common understanding, then some additional details. Normal is a term in geometry (Wikipedia): In geometry, a normal is an object such as a line or vector that is perpendicular to a given object. which in turn appears to come from a term for a carpenter's or mason's square [1] NORM and NORMAL. According to the OED, in Latin norma could mean a square used by carpenters, masons, etc., for obtaining right angles, a right angle or a standard or pattern of practice or behaviour. These meanings are reflected in the mathematical terms based on norm and normal. and from geometry the term moves into vector spaces. The direct answer for "normal equations" is given here: http://mathworld.wolfram.com/NormalEquation.html It is called a normal equation because $b-Ax$ is normal to the range of $A$. (In the usual regression notation that's '$y-Xb$ is normal to the range of $X$') Literally, the least squares residual is perpendicular (at right angles) to the nearest point in the space spanned by $X$. The $y$-vector lies in $n$ dimensions. The X-matrix spans $p$ of those (or $p+1$ depending on how your notation is set up; if $X$ is of full rank, it's the number of columns of X). The least squares solution $X\hat{\beta}$ is the nearest point in that space spanned by $X$ to that $y$-vector (indeed, literally the projection of $y$ onto the space spanned by $X$). It is necessarily the case that by minimizing the sum of squares, the difference $y-X\hat{\beta}$ is orthogonal to the space spanned by $X$. (If it were not, there would be a still smaller solution.) However, as whuber suggests in comments, it's not quite so clear cut. Looking at [1] again: The term NORMAL EQUATION in least squares was introduced by Gauss in 1822 [James A. Landau]. Kruskal & Stigler‘s "Normative Terminology" (in Stigler (1999)) consider various hypotheses about where the term came from but do not find any very satisfactory. However, the method of normal equations is often credited to Legendre, 1805. [1] Miller, J. (ed) "Earliest known uses of some of the words of mathematics, N" in Earliest known uses of some of the words of mathematics
Why do we call the equations of least square estimation in linear regression the *normal equations*? I'll give what is perhaps the most common understanding, then some additional details. Normal is a term in geometry (Wikipedia): In geometry, a normal is an object such as a line or vector that is pe
15,799
2SLS but second stage Probit
Your case is less problematic than the other way round. The expectations and linear projections operators go through a linear first stage (e.g. OLS) but not not through non-linear ones like probit or logit. Therefore it's not a problem if you first regress your continous endogenous variable $X$ on your instrument(s) $Z$, $$X_i = a + Z'_i\pi + \eta_i$$ and then use the fitted values in a probit second stage to estimate $$\text{Pr}(Y_i=1|\widehat{X}_i) = \text{Pr}(\beta\widehat{X}_i + \epsilon_i > 0)$$ The standard errors won't be right because $\widehat{X}_i$ is not a random variable but an estimated quantity. You can correct this by bootstrapping both first and second stage together. In Stata this would be something like // use a toy data set as example webuse nlswork // set up the program including 1st and 2nd stage program my2sls reg grade age race tenure predict grade_hat, xb probit union grade_hat age race drop grade_hat end // obtain bootstrapped standard errors bootstrap, reps(100): my2sls In this example we want to estimate the effect of years of education on the probability of being in a labor union. Given that years of education are likely to be endogenous, we instrument it with years of tenure in the first stage. Of course, this doesn't make any sense from the point of interpretation but it illustrates the code. Just make sure that you use the same exogenous control variables in both first and second stage. In the above example those are age, race whereas the (non-sensical) instrument tenure is only there in the first stage.
2SLS but second stage Probit
Your case is less problematic than the other way round. The expectations and linear projections operators go through a linear first stage (e.g. OLS) but not not through non-linear ones like probit or
2SLS but second stage Probit Your case is less problematic than the other way round. The expectations and linear projections operators go through a linear first stage (e.g. OLS) but not not through non-linear ones like probit or logit. Therefore it's not a problem if you first regress your continous endogenous variable $X$ on your instrument(s) $Z$, $$X_i = a + Z'_i\pi + \eta_i$$ and then use the fitted values in a probit second stage to estimate $$\text{Pr}(Y_i=1|\widehat{X}_i) = \text{Pr}(\beta\widehat{X}_i + \epsilon_i > 0)$$ The standard errors won't be right because $\widehat{X}_i$ is not a random variable but an estimated quantity. You can correct this by bootstrapping both first and second stage together. In Stata this would be something like // use a toy data set as example webuse nlswork // set up the program including 1st and 2nd stage program my2sls reg grade age race tenure predict grade_hat, xb probit union grade_hat age race drop grade_hat end // obtain bootstrapped standard errors bootstrap, reps(100): my2sls In this example we want to estimate the effect of years of education on the probability of being in a labor union. Given that years of education are likely to be endogenous, we instrument it with years of tenure in the first stage. Of course, this doesn't make any sense from the point of interpretation but it illustrates the code. Just make sure that you use the same exogenous control variables in both first and second stage. In the above example those are age, race whereas the (non-sensical) instrument tenure is only there in the first stage.
2SLS but second stage Probit Your case is less problematic than the other way round. The expectations and linear projections operators go through a linear first stage (e.g. OLS) but not not through non-linear ones like probit or
15,800
How to perform residual analysis for binary/dichotomous independent predictors in linear regression?
@NickCox has done a good job talking about displays of residuals when you have two groups. Let me address some of the explicit questions and implicit assumptions that lie behind this thread. The question asks, "how do you test assumptions of linear regression such as homoscedasticity when an independent variable is binary?" You have a multiple regression model. A (multiple) regression model assumes there is only one error term, which is constant everywhere. It isn't terribly meaningful (and you don't have) to check for heteroscedasticity for each predictor individually. This is why, when we have a multiple regression model, we diagnose heteroscedasticity from plots of the residuals vs. the predicted values. Probably the most helpful plot for this purpose is a scale-location plot (also called 'spread-level'), which is a plot of the square root of the absolute value of the residuals vs. the predicted values. To see examples, look at the bottom row of my answer here: What does having "constant variance" in a linear regression model mean? Likewise, you don't have to check the residuals for each predictor for normality. (I honestly don't even know how that would work.) What you can do with plots of residuals against individual predictors is check to see if the functional form is properly specified. For example, if the residuals form a parabola, there is some curvature in the data that you have missed. To see an example, look at the second plot in @Glen_b's answer here: Checking model quality in linear regression. However, these issues don't apply with a binary predictor. For what it's worth, if you only have categorical predictors, you can test for heteroscedasticity. You just use Levene's test. I discuss it here: Why Levene's test of equality of variances rather than F ratio? In R you use ?leveneTest from the car package. Edit: To better illustrate the point that looking at a plot of the residuals vs. an individual predictor variable does not help when you have a multiple regression model, consider this example: set.seed(8603) # this makes the example exactly reproducible x1 = sort(runif(48, min=0, max=50)) # here is the (continuous) x1 variable x2 = rep(c(1,0,0,1), each=12) # here is the (dichotomous) x2 variable y = 5 + 1*x1 + 2*x2 + rnorm(48) # the true data generating process, there is # no heteroscedasticity mod = lm(y~x1+x2) # this fits the model You can see from the data generating process that there is no heteroscedasticity. Let's examine the relevant plots of the model to see if they imply problematic heteroscedasticity: Nope, nothing to worry about. However, let's look at the plot of the residuals vs. the individual binary predictor variable to see if it looks like there is heteroscedasticity there: Uh oh, it does look like there may be a problem. We know from the data generating process that there isn't any heteroscedasticity, and the primary plots for exploring this didn't show any either, so what is happening here? Maybe these plots will help: x1 and x2 are not independent of each other. Moreover, the observations where x2 = 1 are at the extremes. They have more leverage, so their residuals are naturally smaller. Nonetheless, there is no heteroscedasticity. The take home message: Your best bet is to only diagnose heteroscedasticity from the appropriate plots (the residuals vs. fitted plot, and the spread-level plot).
How to perform residual analysis for binary/dichotomous independent predictors in linear regression?
@NickCox has done a good job talking about displays of residuals when you have two groups. Let me address some of the explicit questions and implicit assumptions that lie behind this thread. The qu
How to perform residual analysis for binary/dichotomous independent predictors in linear regression? @NickCox has done a good job talking about displays of residuals when you have two groups. Let me address some of the explicit questions and implicit assumptions that lie behind this thread. The question asks, "how do you test assumptions of linear regression such as homoscedasticity when an independent variable is binary?" You have a multiple regression model. A (multiple) regression model assumes there is only one error term, which is constant everywhere. It isn't terribly meaningful (and you don't have) to check for heteroscedasticity for each predictor individually. This is why, when we have a multiple regression model, we diagnose heteroscedasticity from plots of the residuals vs. the predicted values. Probably the most helpful plot for this purpose is a scale-location plot (also called 'spread-level'), which is a plot of the square root of the absolute value of the residuals vs. the predicted values. To see examples, look at the bottom row of my answer here: What does having "constant variance" in a linear regression model mean? Likewise, you don't have to check the residuals for each predictor for normality. (I honestly don't even know how that would work.) What you can do with plots of residuals against individual predictors is check to see if the functional form is properly specified. For example, if the residuals form a parabola, there is some curvature in the data that you have missed. To see an example, look at the second plot in @Glen_b's answer here: Checking model quality in linear regression. However, these issues don't apply with a binary predictor. For what it's worth, if you only have categorical predictors, you can test for heteroscedasticity. You just use Levene's test. I discuss it here: Why Levene's test of equality of variances rather than F ratio? In R you use ?leveneTest from the car package. Edit: To better illustrate the point that looking at a plot of the residuals vs. an individual predictor variable does not help when you have a multiple regression model, consider this example: set.seed(8603) # this makes the example exactly reproducible x1 = sort(runif(48, min=0, max=50)) # here is the (continuous) x1 variable x2 = rep(c(1,0,0,1), each=12) # here is the (dichotomous) x2 variable y = 5 + 1*x1 + 2*x2 + rnorm(48) # the true data generating process, there is # no heteroscedasticity mod = lm(y~x1+x2) # this fits the model You can see from the data generating process that there is no heteroscedasticity. Let's examine the relevant plots of the model to see if they imply problematic heteroscedasticity: Nope, nothing to worry about. However, let's look at the plot of the residuals vs. the individual binary predictor variable to see if it looks like there is heteroscedasticity there: Uh oh, it does look like there may be a problem. We know from the data generating process that there isn't any heteroscedasticity, and the primary plots for exploring this didn't show any either, so what is happening here? Maybe these plots will help: x1 and x2 are not independent of each other. Moreover, the observations where x2 = 1 are at the extremes. They have more leverage, so their residuals are naturally smaller. Nonetheless, there is no heteroscedasticity. The take home message: Your best bet is to only diagnose heteroscedasticity from the appropriate plots (the residuals vs. fitted plot, and the spread-level plot).
How to perform residual analysis for binary/dichotomous independent predictors in linear regression? @NickCox has done a good job talking about displays of residuals when you have two groups. Let me address some of the explicit questions and implicit assumptions that lie behind this thread. The qu