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
14,901
What is meant by proximity in random forests?
Note that the authors of Elements of Statistical Learning state that "Proximity plots for random forests often look very similar, irrespective of the data, which casts doubt on their utility. They tend to have a star shape, one arm per class, which is more pronounced the better the classification performance." (p 595) However, I think these authors don't mention the ways that random forests deal with missing data so much (even though they mention missing data with trees earlier in the book); perhaps the authors just did not highlight this aspect of RFs as much, which makes sense considering the book is enormous and has a lot of information on a lot of machine learning topics/techniques. However, I don't think that having the plots give similar shapes for any RF and data set means anything negative about RFs in general. For instance, linear regression basically always looks the same, but it's worthwhile to know what points lie close to the line and which seems to be outliers from the perspective of linear regression. So...their comment about the utility of proximity plots doesn't make sense to me.
What is meant by proximity in random forests?
Note that the authors of Elements of Statistical Learning state that "Proximity plots for random forests often look very similar, irrespective of the data, which casts doubt on their utility. They ten
What is meant by proximity in random forests? Note that the authors of Elements of Statistical Learning state that "Proximity plots for random forests often look very similar, irrespective of the data, which casts doubt on their utility. They tend to have a star shape, one arm per class, which is more pronounced the better the classification performance." (p 595) However, I think these authors don't mention the ways that random forests deal with missing data so much (even though they mention missing data with trees earlier in the book); perhaps the authors just did not highlight this aspect of RFs as much, which makes sense considering the book is enormous and has a lot of information on a lot of machine learning topics/techniques. However, I don't think that having the plots give similar shapes for any RF and data set means anything negative about RFs in general. For instance, linear regression basically always looks the same, but it's worthwhile to know what points lie close to the line and which seems to be outliers from the perspective of linear regression. So...their comment about the utility of proximity plots doesn't make sense to me.
What is meant by proximity in random forests? Note that the authors of Elements of Statistical Learning state that "Proximity plots for random forests often look very similar, irrespective of the data, which casts doubt on their utility. They ten
14,902
How to do exploratory data analysis to choose appropriate machine learning algorithm
This is a broad question without a simple answer. At CMU I taught a 3-month course on this topic. It covered issues such as: Using projections to understand correlation between variables and overall distributional structure. How to build up a regression model by successively modelling residuals. Determining when to add nonlinear interaction terms to a linear model. How to decide between knn vs. a decision tree vs. a logistic classifier. I went through a number of UCI datasets and showed how you could tell which classifier would win before running them. Sadly, there is no video or textbook for the course, but I gave a talk that summarizes the main points from the class. I'm not aware of any textbook that covers the same ground.
How to do exploratory data analysis to choose appropriate machine learning algorithm
This is a broad question without a simple answer. At CMU I taught a 3-month course on this topic. It covered issues such as: Using projections to understand correlation between variables and overal
How to do exploratory data analysis to choose appropriate machine learning algorithm This is a broad question without a simple answer. At CMU I taught a 3-month course on this topic. It covered issues such as: Using projections to understand correlation between variables and overall distributional structure. How to build up a regression model by successively modelling residuals. Determining when to add nonlinear interaction terms to a linear model. How to decide between knn vs. a decision tree vs. a logistic classifier. I went through a number of UCI datasets and showed how you could tell which classifier would win before running them. Sadly, there is no video or textbook for the course, but I gave a talk that summarizes the main points from the class. I'm not aware of any textbook that covers the same ground.
How to do exploratory data analysis to choose appropriate machine learning algorithm This is a broad question without a simple answer. At CMU I taught a 3-month course on this topic. It covered issues such as: Using projections to understand correlation between variables and overal
14,903
How to do exploratory data analysis to choose appropriate machine learning algorithm
There are some things that you can check in your data. 1 - correlation between variables 2 - categorical variables or continuous variables? 3 - relation between number of samples and number of variables 4 - are the samples independent or is it a time series? According to these points and to the kind of information you want to extract from your data you can decide what algorithm to use.
How to do exploratory data analysis to choose appropriate machine learning algorithm
There are some things that you can check in your data. 1 - correlation between variables 2 - categorical variables or continuous variables? 3 - relation between number of samples and number of variab
How to do exploratory data analysis to choose appropriate machine learning algorithm There are some things that you can check in your data. 1 - correlation between variables 2 - categorical variables or continuous variables? 3 - relation between number of samples and number of variables 4 - are the samples independent or is it a time series? According to these points and to the kind of information you want to extract from your data you can decide what algorithm to use.
How to do exploratory data analysis to choose appropriate machine learning algorithm There are some things that you can check in your data. 1 - correlation between variables 2 - categorical variables or continuous variables? 3 - relation between number of samples and number of variab
14,904
What is the relationship between profile likelihood and confidence intervals?
I will not give a complete answer (I have a hard time trying to understand what you are doing exactly), but I will try to clarify how profile likelihood is built. I may complete my answer later. The full likelihood for a normal sample of size $n$ is $$L(\mu, \sigma^2) = \left( \sigma^2 \right)^{-n/2} \exp\left( - \sum_i (x_i-\mu)^2/2\sigma^2 \right).$$ If $\mu$ is your parameter of interest, and $\sigma^2$ is a nuisance parameter, a solution to make inference only on $\mu$ is to define the profile likelihood $$L_P(\mu) = L\left(\mu, \widehat{\sigma^2}(\mu) \right)$$ where $\widehat{\sigma^2}(\mu)$ is the MLE for $\mu$ fixed: $$\widehat{\sigma^2}(\mu) = \text{argmax}_{\sigma^2} L(\mu, \sigma^2).$$ One checks that $$\widehat{\sigma^2}(\mu) = {1\over n} \sum_k (x_k - \mu)^2.$$ Hence the profile likelihood is $$L_P(\mu) = \left( {1\over n} \sum_k (x_k - \mu)^2 \right)^{-n/2} \exp( -n/2 ).$$ Here is some R code to compute and plot the profile likelihood (I removed the constant term $\exp(-n/2)$): > data(sleep) > difference <- sleep$extra[11:20]-sleep$extra[1:10] > Lp <- function(mu, x) {n <- length(x); mean( (x-mu)**2 )**(-n/2) } > mu <- seq(0,3, length=501) > plot(mu, sapply(mu, Lp, x = difference), type="l") Link with the likelihood I’ll try to highlight the link with the likelihood with the following graph. First define the likelihood: L <- function(mu,s2,x) {n <- length(x); s2**(-n/2)*exp( -sum((x-mu)**2)/2/s2 )} Then do a contour plot: sigma <- seq(0.5,4, length=501) mu <- seq(0,3, length=501) z <- matrix( nrow=length(mu), ncol=length(sigma)) for(i in 1:length(mu)) for(j in 1:length(sigma)) z[i,j] <- L(mu[i], sigma[j], difference) # shorter version # z <- outer(mu, sigma, Vectorize(function(a,b) L(a,b,difference))) contour(mu, sigma, z, levels=c(1e-10,1e-6,2e-5,1e-4,2e-4,4e-4,6e-4,8e-4,1e-3,1.2e-3,1.4e-3)) And then superpose the graph of $\widehat{\sigma^2}(\mu)$: hats2mu <- sapply(mu, function(mu0) mean( (difference-mu0)**2 )) lines(mu, hats2mu, col="red", lwd=2) The values of the profile likelihood are the values taken by the likelihood along the red parabola. You can use the profile likelihood just as a univariate classical likelihood (cf @Prokofiev’s answer). For example, the MLE $\hat\mu$ is the same. For your confidence interval, the results will differ a little because of the curvature of the function $\widehat{\sigma^2}(\mu)$, but as long that you deal only with a short segment of it, it’s almost linear, and the difference will be very small. You can also use the profile likelihood to build score tests, for example.
What is the relationship between profile likelihood and confidence intervals?
I will not give a complete answer (I have a hard time trying to understand what you are doing exactly), but I will try to clarify how profile likelihood is built. I may complete my answer later. The f
What is the relationship between profile likelihood and confidence intervals? I will not give a complete answer (I have a hard time trying to understand what you are doing exactly), but I will try to clarify how profile likelihood is built. I may complete my answer later. The full likelihood for a normal sample of size $n$ is $$L(\mu, \sigma^2) = \left( \sigma^2 \right)^{-n/2} \exp\left( - \sum_i (x_i-\mu)^2/2\sigma^2 \right).$$ If $\mu$ is your parameter of interest, and $\sigma^2$ is a nuisance parameter, a solution to make inference only on $\mu$ is to define the profile likelihood $$L_P(\mu) = L\left(\mu, \widehat{\sigma^2}(\mu) \right)$$ where $\widehat{\sigma^2}(\mu)$ is the MLE for $\mu$ fixed: $$\widehat{\sigma^2}(\mu) = \text{argmax}_{\sigma^2} L(\mu, \sigma^2).$$ One checks that $$\widehat{\sigma^2}(\mu) = {1\over n} \sum_k (x_k - \mu)^2.$$ Hence the profile likelihood is $$L_P(\mu) = \left( {1\over n} \sum_k (x_k - \mu)^2 \right)^{-n/2} \exp( -n/2 ).$$ Here is some R code to compute and plot the profile likelihood (I removed the constant term $\exp(-n/2)$): > data(sleep) > difference <- sleep$extra[11:20]-sleep$extra[1:10] > Lp <- function(mu, x) {n <- length(x); mean( (x-mu)**2 )**(-n/2) } > mu <- seq(0,3, length=501) > plot(mu, sapply(mu, Lp, x = difference), type="l") Link with the likelihood I’ll try to highlight the link with the likelihood with the following graph. First define the likelihood: L <- function(mu,s2,x) {n <- length(x); s2**(-n/2)*exp( -sum((x-mu)**2)/2/s2 )} Then do a contour plot: sigma <- seq(0.5,4, length=501) mu <- seq(0,3, length=501) z <- matrix( nrow=length(mu), ncol=length(sigma)) for(i in 1:length(mu)) for(j in 1:length(sigma)) z[i,j] <- L(mu[i], sigma[j], difference) # shorter version # z <- outer(mu, sigma, Vectorize(function(a,b) L(a,b,difference))) contour(mu, sigma, z, levels=c(1e-10,1e-6,2e-5,1e-4,2e-4,4e-4,6e-4,8e-4,1e-3,1.2e-3,1.4e-3)) And then superpose the graph of $\widehat{\sigma^2}(\mu)$: hats2mu <- sapply(mu, function(mu0) mean( (difference-mu0)**2 )) lines(mu, hats2mu, col="red", lwd=2) The values of the profile likelihood are the values taken by the likelihood along the red parabola. You can use the profile likelihood just as a univariate classical likelihood (cf @Prokofiev’s answer). For example, the MLE $\hat\mu$ is the same. For your confidence interval, the results will differ a little because of the curvature of the function $\widehat{\sigma^2}(\mu)$, but as long that you deal only with a short segment of it, it’s almost linear, and the difference will be very small. You can also use the profile likelihood to build score tests, for example.
What is the relationship between profile likelihood and confidence intervals? I will not give a complete answer (I have a hard time trying to understand what you are doing exactly), but I will try to clarify how profile likelihood is built. I may complete my answer later. The f
14,905
What is the relationship between profile likelihood and confidence intervals?
In a general framework, profile likelihood intervals are approximate confidence intervals. The proof of this result is essentially the same as proving that the likelihood ratio statistic is (asymptotically) approximately distributed as a $\chi^2_k$ distribution. The idea consists of inverting the hypothesis test obtained from a likelihood ratio statistic. For example, a $0.147$-level profile likelihood interval has an approximate confidence of $95\%$. These are classical results and therefore I will simply provide some references on this: http://www.jstor.org/stable/2347496 http://www.stata-journal.com/sjpdf.html?articlenum=st0132 http://www.unc.edu/courses/2010fall/ecol/563/001/docs/lectures/lecture11.htm http://en.wikipedia.org/wiki/Likelihood-ratio_test http://en.wikipedia.org/wiki/Likelihood_function#Profile_likelihood The following R code shows that, even for small samples, the intervals obtained with both approaches are similar (I am re-using Elvis example): Note that you have to use the normalised profile likelihood. data(sleep) x <- sleep$extra[11:20]-sleep$extra[1:10] n <- length(x) Rp <- function(mu) {mean( (x-mean(x))^2 )^(n/2)/mean( (x-mu)^2 )^(n/2) } Rp(mean(x)) mu <- seq(0,3, length=501) plot(mu, sapply(mu, Rp), type="l") Rpt<- function(mu) Rp(mu)-0.147 # Just an instrumental function # Likelihood-confidence interval of 95% level c(uniroot(Rpt,c(0.5,1.5))$root,uniroot(Rpt,c(1.51,3))$root) # t confidence interval t.test(x,conf.level=0.95)$conf.int If we use a larger sample size, the confidence intervals are even closer: set.seed(123) x <- rnorm(100) n <- length(x) Rp <- function(mu) {mean( (x-mean(x))^2 )^(n/2)/mean( (x-mu)^2 )^(n/2) } Rp(mean(x)) mu <- seq(-0.5,0.5, length=501) plot(mu, sapply(mu, Rp), type="l") Rpt<- function(mu) Rp(mu)-0.147 # Just an instrumental function # Likelihood-confidence interval of 95% level c(uniroot(Rpt,c(-0.4,0))$root,uniroot(Rpt,c(0,0.4))$root) # t confidence interval t.test(x,conf.level=0.95)$conf.int AN IMPORTANT POINT: Note that for specific samples different kinds of confidence intervals may differ in terms of their length or location, what really matters is their coverage. In the long run, all of them should provide the same coverage, independently on how much they differ for specific samples.
What is the relationship between profile likelihood and confidence intervals?
In a general framework, profile likelihood intervals are approximate confidence intervals. The proof of this result is essentially the same as proving that the likelihood ratio statistic is (asymptoti
What is the relationship between profile likelihood and confidence intervals? In a general framework, profile likelihood intervals are approximate confidence intervals. The proof of this result is essentially the same as proving that the likelihood ratio statistic is (asymptotically) approximately distributed as a $\chi^2_k$ distribution. The idea consists of inverting the hypothesis test obtained from a likelihood ratio statistic. For example, a $0.147$-level profile likelihood interval has an approximate confidence of $95\%$. These are classical results and therefore I will simply provide some references on this: http://www.jstor.org/stable/2347496 http://www.stata-journal.com/sjpdf.html?articlenum=st0132 http://www.unc.edu/courses/2010fall/ecol/563/001/docs/lectures/lecture11.htm http://en.wikipedia.org/wiki/Likelihood-ratio_test http://en.wikipedia.org/wiki/Likelihood_function#Profile_likelihood The following R code shows that, even for small samples, the intervals obtained with both approaches are similar (I am re-using Elvis example): Note that you have to use the normalised profile likelihood. data(sleep) x <- sleep$extra[11:20]-sleep$extra[1:10] n <- length(x) Rp <- function(mu) {mean( (x-mean(x))^2 )^(n/2)/mean( (x-mu)^2 )^(n/2) } Rp(mean(x)) mu <- seq(0,3, length=501) plot(mu, sapply(mu, Rp), type="l") Rpt<- function(mu) Rp(mu)-0.147 # Just an instrumental function # Likelihood-confidence interval of 95% level c(uniroot(Rpt,c(0.5,1.5))$root,uniroot(Rpt,c(1.51,3))$root) # t confidence interval t.test(x,conf.level=0.95)$conf.int If we use a larger sample size, the confidence intervals are even closer: set.seed(123) x <- rnorm(100) n <- length(x) Rp <- function(mu) {mean( (x-mean(x))^2 )^(n/2)/mean( (x-mu)^2 )^(n/2) } Rp(mean(x)) mu <- seq(-0.5,0.5, length=501) plot(mu, sapply(mu, Rp), type="l") Rpt<- function(mu) Rp(mu)-0.147 # Just an instrumental function # Likelihood-confidence interval of 95% level c(uniroot(Rpt,c(-0.4,0))$root,uniroot(Rpt,c(0,0.4))$root) # t confidence interval t.test(x,conf.level=0.95)$conf.int AN IMPORTANT POINT: Note that for specific samples different kinds of confidence intervals may differ in terms of their length or location, what really matters is their coverage. In the long run, all of them should provide the same coverage, independently on how much they differ for specific samples.
What is the relationship between profile likelihood and confidence intervals? In a general framework, profile likelihood intervals are approximate confidence intervals. The proof of this result is essentially the same as proving that the likelihood ratio statistic is (asymptoti
14,906
What is the relationship between profile likelihood and confidence intervals?
I will not give an overly mathematical answer, but I would like to address your central question about the relationship between CI's and profile likelihood intervals. As the other respondents have pointed out, CI's can be constructed from a profile likelihood by using the $\chi^2$ approximation to the $normalized$ likelihood ratio. The accuracty of this approach depends on one of two things being approximately true: The profile log-likelihood is approximatley quadratic There exists a parameter transform that makes the profile log-likelihood approximately quadratic. The quadratic is important because it defines a normal distribution in log-scale. The more quadratic it is, the better the approximation and the resulting CIs'. Your choice of 1/20th cutoff for the likelihood intervals is equivalent to more than a 95% CI in the asymptotic limit, whcih is why the blue intervals are generally longer than the red ones. Now, there is another issue with profile likelihood that needs some attention. If you have a lot of variables that you are profiling over, then if the number of data points per dimension is low, the profile likelihood can be very biased and optimistic. Marginal, conditional, and modified profile likelihoods are then used to reduce this bias. So, the answer to your question is YES...the connection is the asymptotic normality of most maximum likelihood estimators, as manifested in the chi-squared distribution of the likelihood ratio.
What is the relationship between profile likelihood and confidence intervals?
I will not give an overly mathematical answer, but I would like to address your central question about the relationship between CI's and profile likelihood intervals. As the other respondents have poi
What is the relationship between profile likelihood and confidence intervals? I will not give an overly mathematical answer, but I would like to address your central question about the relationship between CI's and profile likelihood intervals. As the other respondents have pointed out, CI's can be constructed from a profile likelihood by using the $\chi^2$ approximation to the $normalized$ likelihood ratio. The accuracty of this approach depends on one of two things being approximately true: The profile log-likelihood is approximatley quadratic There exists a parameter transform that makes the profile log-likelihood approximately quadratic. The quadratic is important because it defines a normal distribution in log-scale. The more quadratic it is, the better the approximation and the resulting CIs'. Your choice of 1/20th cutoff for the likelihood intervals is equivalent to more than a 95% CI in the asymptotic limit, whcih is why the blue intervals are generally longer than the red ones. Now, there is another issue with profile likelihood that needs some attention. If you have a lot of variables that you are profiling over, then if the number of data points per dimension is low, the profile likelihood can be very biased and optimistic. Marginal, conditional, and modified profile likelihoods are then used to reduce this bias. So, the answer to your question is YES...the connection is the asymptotic normality of most maximum likelihood estimators, as manifested in the chi-squared distribution of the likelihood ratio.
What is the relationship between profile likelihood and confidence intervals? I will not give an overly mathematical answer, but I would like to address your central question about the relationship between CI's and profile likelihood intervals. As the other respondents have poi
14,907
Feature selection with Random Forests
For feature selection, we need a scoring function as well as a search method to optimize the scoring function. You may use RF as a feature ranking method if you define some relevant importance score. RF will select features based on random with replacement method and group every subset in a separate subspace (called random subspace). One scoring function of importance could be based on assigning the accuracy of every tree for every feature in that random subspace. Then, you do this for every separate tree. Since, the source of generating the subspaces is random, you may put a threshold for computing the importance score. Summary: Step1: If feature X2 appears in 25% of the trees, then, score it. Otherwise, do not consider ranking the feature because we do not have sufficient information about its performance Step2: Now, assign the performance score of every tree in which X2 appears to X2 and average the score. For example: perf(Tree1) = 0.85 perf(Tree2) = 0.70 perf(Tree3) = 0.30 Then, the importance of feature X2 = (0.85+0.70+0.30)/3 = 0.6167 You may consider a more advanced setting by including the split depth of the feature or the information gain value in the decision tree. There can be many ways to design a scoring function based on decision trees and RF. Regarding the search method, your recursive method seems reasonable as a way to select the top ranked ones. Finally, you may use RF either as a classifier or a regression model in selecting your features since both of them would supply you with a performance score. The score is indicative as it is based on the out-of-bag OOB samples and you may not consider cross-validation in a simpler setting.
Feature selection with Random Forests
For feature selection, we need a scoring function as well as a search method to optimize the scoring function. You may use RF as a feature ranking method if you define some relevant importance score.
Feature selection with Random Forests For feature selection, we need a scoring function as well as a search method to optimize the scoring function. You may use RF as a feature ranking method if you define some relevant importance score. RF will select features based on random with replacement method and group every subset in a separate subspace (called random subspace). One scoring function of importance could be based on assigning the accuracy of every tree for every feature in that random subspace. Then, you do this for every separate tree. Since, the source of generating the subspaces is random, you may put a threshold for computing the importance score. Summary: Step1: If feature X2 appears in 25% of the trees, then, score it. Otherwise, do not consider ranking the feature because we do not have sufficient information about its performance Step2: Now, assign the performance score of every tree in which X2 appears to X2 and average the score. For example: perf(Tree1) = 0.85 perf(Tree2) = 0.70 perf(Tree3) = 0.30 Then, the importance of feature X2 = (0.85+0.70+0.30)/3 = 0.6167 You may consider a more advanced setting by including the split depth of the feature or the information gain value in the decision tree. There can be many ways to design a scoring function based on decision trees and RF. Regarding the search method, your recursive method seems reasonable as a way to select the top ranked ones. Finally, you may use RF either as a classifier or a regression model in selecting your features since both of them would supply you with a performance score. The score is indicative as it is based on the out-of-bag OOB samples and you may not consider cross-validation in a simpler setting.
Feature selection with Random Forests For feature selection, we need a scoring function as well as a search method to optimize the scoring function. You may use RF as a feature ranking method if you define some relevant importance score.
14,908
Feature selection with Random Forests
I have a dataset with mostly financial variables (120 features, 4k examples) which are mostly highly correlated and very noisy (technical indicators, for example) so I would like to select about max 20-30 for later use with model training (binary classification - increase / decrease). 4k examples is really not enough to estimate anything very sophisticated - you need to use the simplest possible models ( linear /logistic regression, linear svm) and small number of variables Given that your data is noisy and correlated, PCA is probably your best bet [ it is effectively identifying the common signals averaging over the individual indicators] L2 regularisation (for a linear model) will also help averaging out the noise [eg if you have n noisy copies of the same signal, l2 regularisation will encourage weights to be same - averaging those n variables]
Feature selection with Random Forests
I have a dataset with mostly financial variables (120 features, 4k examples) which are mostly highly correlated and very noisy (technical indicators, for example) so I would like to select about m
Feature selection with Random Forests I have a dataset with mostly financial variables (120 features, 4k examples) which are mostly highly correlated and very noisy (technical indicators, for example) so I would like to select about max 20-30 for later use with model training (binary classification - increase / decrease). 4k examples is really not enough to estimate anything very sophisticated - you need to use the simplest possible models ( linear /logistic regression, linear svm) and small number of variables Given that your data is noisy and correlated, PCA is probably your best bet [ it is effectively identifying the common signals averaging over the individual indicators] L2 regularisation (for a linear model) will also help averaging out the noise [eg if you have n noisy copies of the same signal, l2 regularisation will encourage weights to be same - averaging those n variables]
Feature selection with Random Forests I have a dataset with mostly financial variables (120 features, 4k examples) which are mostly highly correlated and very noisy (technical indicators, for example) so I would like to select about m
14,909
How do you write up Tukey post-hoc findings?
General strategy of article deconstruction A general strategy for learning how to write up results involves finding and deconstructing an example publication. I like to call this article deconstruction. A simple way of doing this involves searching Google Scholar to find a few examples. You may want to limit your search to good journals in your area (e.g., "tukey post hoc social psychology"). Then extract a few writing principles. Example write up of post-hoc test Here's one example of a write-up of a post-hoc test from a social psychology context: The article includes a table of means and standard deviations for each condition for a set of dependent variables. In the text it has the following: An analysis of variance (ANOVA) on these scores again yielded significant variation among conditions, F(2, 37) = 4.29, p < .03. A post hoc Tukey test showed that the future alone and future belonging groups differed significantly at p < .05; the misfortune control group was not significantly different from the other two groups, lying somewhere in the middle. --- Baumeister RF, Twenge JM, Nuss CK. (2002). Effects of social exclusion on cognitive processes: anticipated aloneness reduces intelligent thought. Journal of Personality and Social Psychology, 83, 817-27. Extract writing principles Present a table of means and standard deviations First report overall ANOVA Then report which pairs were significantly different at a given alpha level Then report which pairs were not significantly different. Of course, a post-hoc test could be written up in other ways; for example, you could use a graph of means rather than a table; or you could incorporate post-hoc test results into a table using the $a \le b<c$ style notation ($a,b,c,...$ correspond to groups); but at least by taking a good example, you have a starting point.
How do you write up Tukey post-hoc findings?
General strategy of article deconstruction A general strategy for learning how to write up results involves finding and deconstructing an example publication. I like to call this article deconstructio
How do you write up Tukey post-hoc findings? General strategy of article deconstruction A general strategy for learning how to write up results involves finding and deconstructing an example publication. I like to call this article deconstruction. A simple way of doing this involves searching Google Scholar to find a few examples. You may want to limit your search to good journals in your area (e.g., "tukey post hoc social psychology"). Then extract a few writing principles. Example write up of post-hoc test Here's one example of a write-up of a post-hoc test from a social psychology context: The article includes a table of means and standard deviations for each condition for a set of dependent variables. In the text it has the following: An analysis of variance (ANOVA) on these scores again yielded significant variation among conditions, F(2, 37) = 4.29, p < .03. A post hoc Tukey test showed that the future alone and future belonging groups differed significantly at p < .05; the misfortune control group was not significantly different from the other two groups, lying somewhere in the middle. --- Baumeister RF, Twenge JM, Nuss CK. (2002). Effects of social exclusion on cognitive processes: anticipated aloneness reduces intelligent thought. Journal of Personality and Social Psychology, 83, 817-27. Extract writing principles Present a table of means and standard deviations First report overall ANOVA Then report which pairs were significantly different at a given alpha level Then report which pairs were not significantly different. Of course, a post-hoc test could be written up in other ways; for example, you could use a graph of means rather than a table; or you could incorporate post-hoc test results into a table using the $a \le b<c$ style notation ($a,b,c,...$ correspond to groups); but at least by taking a good example, you have a starting point.
How do you write up Tukey post-hoc findings? General strategy of article deconstruction A general strategy for learning how to write up results involves finding and deconstructing an example publication. I like to call this article deconstructio
14,910
How do you write up Tukey post-hoc findings?
It's a tough one to visualize, especially considering the potential audience. But you should also show the homogenous subsets so it's easy to identify those elements that are truly differentiated from each other. Depending on the audience, I don't even bother showing SE or L/U B nor p-values. I had to cut the row labels from the left hand because it's real data, but you can see the presentation below: Plotting the subsets helps the user "see" which means are truely different from each other. Depending on your audience, adding a p-value could also be useful.
How do you write up Tukey post-hoc findings?
It's a tough one to visualize, especially considering the potential audience. But you should also show the homogenous subsets so it's easy to identify those elements that are truly differentiated from
How do you write up Tukey post-hoc findings? It's a tough one to visualize, especially considering the potential audience. But you should also show the homogenous subsets so it's easy to identify those elements that are truly differentiated from each other. Depending on the audience, I don't even bother showing SE or L/U B nor p-values. I had to cut the row labels from the left hand because it's real data, but you can see the presentation below: Plotting the subsets helps the user "see" which means are truely different from each other. Depending on your audience, adding a p-value could also be useful.
How do you write up Tukey post-hoc findings? It's a tough one to visualize, especially considering the potential audience. But you should also show the homogenous subsets so it's easy to identify those elements that are truly differentiated from
14,911
Notation: What does the tilde below of the expectation mean? [duplicate]
$z\sim q$ means that RV $Z$ is distributed with respect to $q$ function, i.e. $q(z)$, where $q(z)$ is a valid PDF/PMF. So, the expectation can be unfold as (assuming $z$ being continuous) $$\mathbb{E}_{z\sim q}[\log_{\phi}(x_i|z)]=\int_{-\infty}^\infty \log_\phi (x_i|z) q(z) dz$$
Notation: What does the tilde below of the expectation mean? [duplicate]
$z\sim q$ means that RV $Z$ is distributed with respect to $q$ function, i.e. $q(z)$, where $q(z)$ is a valid PDF/PMF. So, the expectation can be unfold as (assuming $z$ being continuous) $$\mathbb{E}
Notation: What does the tilde below of the expectation mean? [duplicate] $z\sim q$ means that RV $Z$ is distributed with respect to $q$ function, i.e. $q(z)$, where $q(z)$ is a valid PDF/PMF. So, the expectation can be unfold as (assuming $z$ being continuous) $$\mathbb{E}_{z\sim q}[\log_{\phi}(x_i|z)]=\int_{-\infty}^\infty \log_\phi (x_i|z) q(z) dz$$
Notation: What does the tilde below of the expectation mean? [duplicate] $z\sim q$ means that RV $Z$ is distributed with respect to $q$ function, i.e. $q(z)$, where $q(z)$ is a valid PDF/PMF. So, the expectation can be unfold as (assuming $z$ being continuous) $$\mathbb{E}
14,912
Using a Random Forest for Time Series Data
It works well but only if the features are properly prepared so that the order of the lines is not important anymore. E.g. for a univariate time series $y_i$, you would use $y_i$ as response and e.g. the following features: Lagged versions $y_{i-1}$, $y_{i-2}$, $y_{i-3}$ etc. Differences of appropriate order, e.g. $y_{i-1} - y_{i-2}$, $y_{i-1} - y_{i-8}$ (if there is weekly seasonality expected and the observations occur daily) etc. Integer or dummy coded periodic time info such as month in year, week day, hour of day, minute in hour etc. The same approach works for different modelling techniques, including linear regression, neural nets, boosted trees etc. An example is the following (using a binary target "temperature increase" (y/n)): library(tidyverse) library(lubridate) library(ranger) library(MetricsWeighted) # AUC # Import raw <- read.csv("https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv") # Explore str(raw) head(raw) summary(raw) hist(raw$Temp, breaks = "FD") # Prepare and add binary response prep <- raw %>% mutate(Date = ymd(Date), y = year(Date), m = month(Date), d = day(Date), increase = 0 + (Temp > lag(Temp))) with(prep, table(y)) summary(prep) # Plot full data -> year as seasonality ggplot(data = prep, aes(x = Date, y = Temp))+ geom_line(color = "#00AFBB", size = 2) + scale_x_date() # No visible within year seasonality prep %>% filter(y == 1987) %>% ggplot(aes(x = Date, y = Temp))+ geom_line(color = "#00AFBB", size = 2) + scale_x_date() # Add some lags and diffs & remove incomplete rows prep <- prep %>% mutate(lag1 = lag(Temp), lag2 = lag(Temp, 2L), lag3 = lag(Temp, 3L), dif1 = lag1 - lag2, dif2 = lag2 - lag3) %>% filter(complete.cases(.)) # Train/valid split in blocks valid <- prep %>% filter(y == 1990) train <- prep %>% filter(y < 1990) # Models y <- "increase" # response x <- c("lag1", "lag2", "lag3", "dif1", "dif2", "y", "m", "d") # covariables form <- reformulate(x, y) # Logistic model: Linear dependence between difs and lags fit_glm <- glm(form, data = train, family = binomial()) summary(fit_glm) # Random forest fit_rf <- ranger(form, data = train, seed = 345345, importance = "impurity", probability = TRUE) fit_rf barplot(-sort(-importance(fit_rf))) # Variable importance # Evaluate on 1990 for glm by looking at ROC AUC pred_glm <- predict(fit_glm, valid, type = "response") AUC(valid[[y]], pred_glm) # 0.684 ROC AUC # Then for rf pred_rf <- predict(fit_rf, valid)$predictions[, 2] AUC(valid[[y]], pred_rf) # 0.702 ROC AUC # view OOB residuals of rf within one month to see if structure is left over random_month <- train %>% mutate(residuals = increase - fit_rf$predictions[, 2]) %>% filter(y == 1987, m == 3) ggplot(random_month, aes(x = Date, y = residuals))+ geom_line(color = "#00AFBB", size = 2) + scale_x_date() Replacing variables "y" and "m" by factors would probably improve the logistic regression. But since the question was about random forests, I leave this to the reader.
Using a Random Forest for Time Series Data
It works well but only if the features are properly prepared so that the order of the lines is not important anymore. E.g. for a univariate time series $y_i$, you would use $y_i$ as response and e.g.
Using a Random Forest for Time Series Data It works well but only if the features are properly prepared so that the order of the lines is not important anymore. E.g. for a univariate time series $y_i$, you would use $y_i$ as response and e.g. the following features: Lagged versions $y_{i-1}$, $y_{i-2}$, $y_{i-3}$ etc. Differences of appropriate order, e.g. $y_{i-1} - y_{i-2}$, $y_{i-1} - y_{i-8}$ (if there is weekly seasonality expected and the observations occur daily) etc. Integer or dummy coded periodic time info such as month in year, week day, hour of day, minute in hour etc. The same approach works for different modelling techniques, including linear regression, neural nets, boosted trees etc. An example is the following (using a binary target "temperature increase" (y/n)): library(tidyverse) library(lubridate) library(ranger) library(MetricsWeighted) # AUC # Import raw <- read.csv("https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv") # Explore str(raw) head(raw) summary(raw) hist(raw$Temp, breaks = "FD") # Prepare and add binary response prep <- raw %>% mutate(Date = ymd(Date), y = year(Date), m = month(Date), d = day(Date), increase = 0 + (Temp > lag(Temp))) with(prep, table(y)) summary(prep) # Plot full data -> year as seasonality ggplot(data = prep, aes(x = Date, y = Temp))+ geom_line(color = "#00AFBB", size = 2) + scale_x_date() # No visible within year seasonality prep %>% filter(y == 1987) %>% ggplot(aes(x = Date, y = Temp))+ geom_line(color = "#00AFBB", size = 2) + scale_x_date() # Add some lags and diffs & remove incomplete rows prep <- prep %>% mutate(lag1 = lag(Temp), lag2 = lag(Temp, 2L), lag3 = lag(Temp, 3L), dif1 = lag1 - lag2, dif2 = lag2 - lag3) %>% filter(complete.cases(.)) # Train/valid split in blocks valid <- prep %>% filter(y == 1990) train <- prep %>% filter(y < 1990) # Models y <- "increase" # response x <- c("lag1", "lag2", "lag3", "dif1", "dif2", "y", "m", "d") # covariables form <- reformulate(x, y) # Logistic model: Linear dependence between difs and lags fit_glm <- glm(form, data = train, family = binomial()) summary(fit_glm) # Random forest fit_rf <- ranger(form, data = train, seed = 345345, importance = "impurity", probability = TRUE) fit_rf barplot(-sort(-importance(fit_rf))) # Variable importance # Evaluate on 1990 for glm by looking at ROC AUC pred_glm <- predict(fit_glm, valid, type = "response") AUC(valid[[y]], pred_glm) # 0.684 ROC AUC # Then for rf pred_rf <- predict(fit_rf, valid)$predictions[, 2] AUC(valid[[y]], pred_rf) # 0.702 ROC AUC # view OOB residuals of rf within one month to see if structure is left over random_month <- train %>% mutate(residuals = increase - fit_rf$predictions[, 2]) %>% filter(y == 1987, m == 3) ggplot(random_month, aes(x = Date, y = residuals))+ geom_line(color = "#00AFBB", size = 2) + scale_x_date() Replacing variables "y" and "m" by factors would probably improve the logistic regression. But since the question was about random forests, I leave this to the reader.
Using a Random Forest for Time Series Data It works well but only if the features are properly prepared so that the order of the lines is not important anymore. E.g. for a univariate time series $y_i$, you would use $y_i$ as response and e.g.
14,913
Using a Random Forest for Time Series Data
A random forest would not be expected to perform well on time series data for a variety of reasons. In my view the greatest pitfalls are unrelated to the bootstrapping, however, and are not unique to random forests: Time series have an interdependence between observations, which the model will ignore. The underlying learner is typically a tree based algorithm, which does not extrapolate trends. If there are genuine time trends in the data these will not be projected forward.
Using a Random Forest for Time Series Data
A random forest would not be expected to perform well on time series data for a variety of reasons. In my view the greatest pitfalls are unrelated to the bootstrapping, however, and are not unique to
Using a Random Forest for Time Series Data A random forest would not be expected to perform well on time series data for a variety of reasons. In my view the greatest pitfalls are unrelated to the bootstrapping, however, and are not unique to random forests: Time series have an interdependence between observations, which the model will ignore. The underlying learner is typically a tree based algorithm, which does not extrapolate trends. If there are genuine time trends in the data these will not be projected forward.
Using a Random Forest for Time Series Data A random forest would not be expected to perform well on time series data for a variety of reasons. In my view the greatest pitfalls are unrelated to the bootstrapping, however, and are not unique to
14,914
Is it wrong to choose features based on p-value?
The t-statistic can have next to nothing to say about the predictive ability of a feature, and they should not be used to screen predictor out of, or allow predictors into a predictive model. P-values say spurious features are important Consider the following scenario setup in R. Let's create two vectors, the first is simply $5000$ random coin flips: set.seed(154) N <- 5000 y <- rnorm(N) The second vector is $5000$ observations, each randomly assigned to one of $500$ equally sized random classes: N.classes <- 500 rand.class <- factor(cut(1:N, N.classes)) Now we fit a linear model to predict y given rand.classes. M <- lm(y ~ rand.class - 1) #(*) The correct value for all of the coefficients is zero, none of them have any predictive power. None-the-less, many of them are significant at the 5% level ps <- coef(summary(M))[, "Pr(>|t|)"] hist(ps, breaks=30) In fact, we should expect about 5% of them to be significant, even though they have no predictive power! P-values fail to detect important features Here's an example in the other direction. set.seed(154) N <- 100 x1 <- runif(N) x2 <- x1 + rnorm(N, sd = 0.05) y <- x1 + x2 + rnorm(N) M <- lm(y ~ x1 + x2) summary(M) I've created two correlated predictors, each with predictive power. M <- lm(y ~ x1 + x2) summary(M) Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.1271 0.2092 0.608 0.545 x1 0.8369 2.0954 0.399 0.690 x2 0.9216 2.0097 0.459 0.648 The p-values fail to detect the predictive power of both variables because the correlation affects how precisely the model can estimate the two individual coefficients from the data. Inferential statistics are not there to tell about the predictive power or importance of a variable. It is an abuse of these measurements to use them that way. There are much better options available for variable selection in predictive linear models, consider using glmnet. (*) Note that I am leaving off an intercept here, so all the comparisons are to the baseline of zero, not to the group mean of the first class. This was @whuber's suggestion. Since it led to a very interesting discussion in the comments, the original code was rand.class <- factor(sample(1:N.classes, N, replace=TRUE)) and M <- lm(y ~ rand.class) which led to the following histogram
Is it wrong to choose features based on p-value?
The t-statistic can have next to nothing to say about the predictive ability of a feature, and they should not be used to screen predictor out of, or allow predictors into a predictive model. P-valu
Is it wrong to choose features based on p-value? The t-statistic can have next to nothing to say about the predictive ability of a feature, and they should not be used to screen predictor out of, or allow predictors into a predictive model. P-values say spurious features are important Consider the following scenario setup in R. Let's create two vectors, the first is simply $5000$ random coin flips: set.seed(154) N <- 5000 y <- rnorm(N) The second vector is $5000$ observations, each randomly assigned to one of $500$ equally sized random classes: N.classes <- 500 rand.class <- factor(cut(1:N, N.classes)) Now we fit a linear model to predict y given rand.classes. M <- lm(y ~ rand.class - 1) #(*) The correct value for all of the coefficients is zero, none of them have any predictive power. None-the-less, many of them are significant at the 5% level ps <- coef(summary(M))[, "Pr(>|t|)"] hist(ps, breaks=30) In fact, we should expect about 5% of them to be significant, even though they have no predictive power! P-values fail to detect important features Here's an example in the other direction. set.seed(154) N <- 100 x1 <- runif(N) x2 <- x1 + rnorm(N, sd = 0.05) y <- x1 + x2 + rnorm(N) M <- lm(y ~ x1 + x2) summary(M) I've created two correlated predictors, each with predictive power. M <- lm(y ~ x1 + x2) summary(M) Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.1271 0.2092 0.608 0.545 x1 0.8369 2.0954 0.399 0.690 x2 0.9216 2.0097 0.459 0.648 The p-values fail to detect the predictive power of both variables because the correlation affects how precisely the model can estimate the two individual coefficients from the data. Inferential statistics are not there to tell about the predictive power or importance of a variable. It is an abuse of these measurements to use them that way. There are much better options available for variable selection in predictive linear models, consider using glmnet. (*) Note that I am leaving off an intercept here, so all the comparisons are to the baseline of zero, not to the group mean of the first class. This was @whuber's suggestion. Since it led to a very interesting discussion in the comments, the original code was rand.class <- factor(sample(1:N.classes, N, replace=TRUE)) and M <- lm(y ~ rand.class) which led to the following histogram
Is it wrong to choose features based on p-value? The t-statistic can have next to nothing to say about the predictive ability of a feature, and they should not be used to screen predictor out of, or allow predictors into a predictive model. P-valu
14,915
Is it wrong to choose features based on p-value?
The t-statistic is influenced by the effect size and the sample size. It might be the case that the effect size is non-zero but the sample size is not big enough to make it significant. In a simple T-test for zero mean (which is analogous to testing if a feature's influence is zero) the T statistic is $t=\left(\frac{\overline{x}}{s}\right) \sqrt{n} $ $\frac{\overline{x}}{s}$ is the sample estimate of the effect size, if it is small then the p-value won't show its significant until the $\sqrt{n}$ term becomes large. In your case any feature with non-zero effect will improve performance but you may not have enough data to make that feature's p-value significant.
Is it wrong to choose features based on p-value?
The t-statistic is influenced by the effect size and the sample size. It might be the case that the effect size is non-zero but the sample size is not big enough to make it significant. In a simple T-
Is it wrong to choose features based on p-value? The t-statistic is influenced by the effect size and the sample size. It might be the case that the effect size is non-zero but the sample size is not big enough to make it significant. In a simple T-test for zero mean (which is analogous to testing if a feature's influence is zero) the T statistic is $t=\left(\frac{\overline{x}}{s}\right) \sqrt{n} $ $\frac{\overline{x}}{s}$ is the sample estimate of the effect size, if it is small then the p-value won't show its significant until the $\sqrt{n}$ term becomes large. In your case any feature with non-zero effect will improve performance but you may not have enough data to make that feature's p-value significant.
Is it wrong to choose features based on p-value? The t-statistic is influenced by the effect size and the sample size. It might be the case that the effect size is non-zero but the sample size is not big enough to make it significant. In a simple T-
14,916
Fitting multivariate, natural cubic spline
This paper presented at UseR! 2009 seems to address a similar problem http://www.r-project.org/conferences/useR-2009/slides/Roustant+Ginsbourger+Deville.pdf It suggests the DiceKriging package http://cran.r-project.org/web/packages/DiceKriging/index.html In particular, check the functions km and predict. Here is a an example of three dimensional interpolation. It looks to be straightforward to generalise. x <- c(0, 0.4, 0.6, 0.8, 1) y <- c(0, 0.2, 0.3, 0.4, 0.5) z <- c(0, 0.3, 0.4, 0.6, 0.8) model <- function(param){ 2*param[1] + 3*param[2] +4*param[3] } model.in <- expand.grid(x,y,z) names(model.in) <- c('x','y','z') model.out <- apply(model.in, 1, model) # fit a kriging model m.1 <- km(design=model.in, response=model.out, covtype="matern5_2") # estimate a response interp <- predict(m.1, newdata=data.frame(x=0.5, y=0.5, z=0.5), type="UK", se.compute=FALSE) # check against model output interp$mean # [1] 4.498902 model(c(0.5,0.5,0.5)) # [1] 4.5 # check we get back what we put in interp <- predict(m.1, newdata=model.in, type="UK", se.compute=FALSE) all.equal(model.out, interp$mean) # TRUE
Fitting multivariate, natural cubic spline
This paper presented at UseR! 2009 seems to address a similar problem http://www.r-project.org/conferences/useR-2009/slides/Roustant+Ginsbourger+Deville.pdf It suggests the DiceKriging package http://
Fitting multivariate, natural cubic spline This paper presented at UseR! 2009 seems to address a similar problem http://www.r-project.org/conferences/useR-2009/slides/Roustant+Ginsbourger+Deville.pdf It suggests the DiceKriging package http://cran.r-project.org/web/packages/DiceKriging/index.html In particular, check the functions km and predict. Here is a an example of three dimensional interpolation. It looks to be straightforward to generalise. x <- c(0, 0.4, 0.6, 0.8, 1) y <- c(0, 0.2, 0.3, 0.4, 0.5) z <- c(0, 0.3, 0.4, 0.6, 0.8) model <- function(param){ 2*param[1] + 3*param[2] +4*param[3] } model.in <- expand.grid(x,y,z) names(model.in) <- c('x','y','z') model.out <- apply(model.in, 1, model) # fit a kriging model m.1 <- km(design=model.in, response=model.out, covtype="matern5_2") # estimate a response interp <- predict(m.1, newdata=data.frame(x=0.5, y=0.5, z=0.5), type="UK", se.compute=FALSE) # check against model output interp$mean # [1] 4.498902 model(c(0.5,0.5,0.5)) # [1] 4.5 # check we get back what we put in interp <- predict(m.1, newdata=model.in, type="UK", se.compute=FALSE) all.equal(model.out, interp$mean) # TRUE
Fitting multivariate, natural cubic spline This paper presented at UseR! 2009 seems to address a similar problem http://www.r-project.org/conferences/useR-2009/slides/Roustant+Ginsbourger+Deville.pdf It suggests the DiceKriging package http://
14,917
Fitting multivariate, natural cubic spline
You need more data for a spline fit. mgcv indeed is a good choice. For your specific request you need to set the cubic spline as the basis function bs='cr' and also not have it penalized with fx=TRUE. Both options are set for a smooth term that is set with s(). Predict works as expected. library(mgcv) x <- data.frame(a = 1:100, b = 1:100/2, c = 1:100*2) y <- runif(100) foo <- gam(y~a+b+s(c,bs="cr",fx=TRUE),data=x) plot(foo) predict(foo,x)
Fitting multivariate, natural cubic spline
You need more data for a spline fit. mgcv indeed is a good choice. For your specific request you need to set the cubic spline as the basis function bs='cr' and also not have it penalized with fx=TRUE.
Fitting multivariate, natural cubic spline You need more data for a spline fit. mgcv indeed is a good choice. For your specific request you need to set the cubic spline as the basis function bs='cr' and also not have it penalized with fx=TRUE. Both options are set for a smooth term that is set with s(). Predict works as expected. library(mgcv) x <- data.frame(a = 1:100, b = 1:100/2, c = 1:100*2) y <- runif(100) foo <- gam(y~a+b+s(c,bs="cr",fx=TRUE),data=x) plot(foo) predict(foo,x)
Fitting multivariate, natural cubic spline You need more data for a spline fit. mgcv indeed is a good choice. For your specific request you need to set the cubic spline as the basis function bs='cr' and also not have it penalized with fx=TRUE.
14,918
Fitting multivariate, natural cubic spline
You give no details as to the form of the function $f(X)$; it might be that a piecewise constant function is a sufficiently good approximation, in which case you might want to fit a regression tree (with package rpart for instance). Otherwise, you might want to look at package earth, in addition to what has been suggested already.
Fitting multivariate, natural cubic spline
You give no details as to the form of the function $f(X)$; it might be that a piecewise constant function is a sufficiently good approximation, in which case you might want to fit a regression tree (w
Fitting multivariate, natural cubic spline You give no details as to the form of the function $f(X)$; it might be that a piecewise constant function is a sufficiently good approximation, in which case you might want to fit a regression tree (with package rpart for instance). Otherwise, you might want to look at package earth, in addition to what has been suggested already.
Fitting multivariate, natural cubic spline You give no details as to the form of the function $f(X)$; it might be that a piecewise constant function is a sufficiently good approximation, in which case you might want to fit a regression tree (w
14,919
Persistence in time series
Roughly speaking, the term persistence in time series context is often related to the notion of memory properties of time series. To put it another way, you have a persistent time series process if the effect of infinitesimally (very) small shock will be influencing the future predictions of your time series for a very long time. Thus the longer the time of influence the longer is the memory and the extremely persistence. You may consider an integrated process I(1) as an example of highly persistent process (information that comes from the shocks never dies out). Though fractionally integrated (ARFIMA) processes would be more interesting examples of persistent processes. Probably it would be useful to read about Measuring Conditional Persistence in Time Series in G.Kapetanios article.
Persistence in time series
Roughly speaking, the term persistence in time series context is often related to the notion of memory properties of time series. To put it another way, you have a persistent time series process if th
Persistence in time series Roughly speaking, the term persistence in time series context is often related to the notion of memory properties of time series. To put it another way, you have a persistent time series process if the effect of infinitesimally (very) small shock will be influencing the future predictions of your time series for a very long time. Thus the longer the time of influence the longer is the memory and the extremely persistence. You may consider an integrated process I(1) as an example of highly persistent process (information that comes from the shocks never dies out). Though fractionally integrated (ARFIMA) processes would be more interesting examples of persistent processes. Probably it would be useful to read about Measuring Conditional Persistence in Time Series in G.Kapetanios article.
Persistence in time series Roughly speaking, the term persistence in time series context is often related to the notion of memory properties of time series. To put it another way, you have a persistent time series process if th
14,920
Persistence in time series
A persistent series is one where the value of the variable at a certain date is closely related to the previous value. The two basic measures of persistence are the autocovariance and the autocorrelation coefficient.
Persistence in time series
A persistent series is one where the value of the variable at a certain date is closely related to the previous value. The two basic measures of persistence are the autocovariance and the autocorrelat
Persistence in time series A persistent series is one where the value of the variable at a certain date is closely related to the previous value. The two basic measures of persistence are the autocovariance and the autocorrelation coefficient.
Persistence in time series A persistent series is one where the value of the variable at a certain date is closely related to the previous value. The two basic measures of persistence are the autocovariance and the autocorrelat
14,921
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation)
Your 2-sided test implicitly allots exactly half of your 5% significance level to "masks are harmful" ($M_-$) and the other half to "masks are beneficial" ($M_+$). To a Bayesian like Taleb that might suggest that you aren't properly thinking about your prior, because it implies that the amount of evidence it would take you to accept $M_-$ is exactly equal to the amount it would take you to accept $M_+$, even though $M_+$ is intuitively more likely (to me, at least - if you had asked me a year ago whether wearing a mask would be more likely to increase or decrease the risk of catching a respiratory virus, I would have said decrease). And it seems to me that since the single independent variable was binary, using Firth's logistic regression over Fisher's exact test doesn't add much value. But your core point was that most of the doubt that mask wearing reduced PCR infections in the trial comes from the presence of uncertainty in the estimate $p=\frac{5}{2470}$. This seems unarguable. Taleb says: "You don’t get it. BTW I added a double column table joint distribution a la Fisher." Maybe that's his way of saving face while admitting that you raised a valid criticism.
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation)
Your 2-sided test implicitly allots exactly half of your 5% significance level to "masks are harmful" ($M_-$) and the other half to "masks are beneficial" ($M_+$). To a Bayesian like Taleb that might
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation) Your 2-sided test implicitly allots exactly half of your 5% significance level to "masks are harmful" ($M_-$) and the other half to "masks are beneficial" ($M_+$). To a Bayesian like Taleb that might suggest that you aren't properly thinking about your prior, because it implies that the amount of evidence it would take you to accept $M_-$ is exactly equal to the amount it would take you to accept $M_+$, even though $M_+$ is intuitively more likely (to me, at least - if you had asked me a year ago whether wearing a mask would be more likely to increase or decrease the risk of catching a respiratory virus, I would have said decrease). And it seems to me that since the single independent variable was binary, using Firth's logistic regression over Fisher's exact test doesn't add much value. But your core point was that most of the doubt that mask wearing reduced PCR infections in the trial comes from the presence of uncertainty in the estimate $p=\frac{5}{2470}$. This seems unarguable. Taleb says: "You don’t get it. BTW I added a double column table joint distribution a la Fisher." Maybe that's his way of saving face while admitting that you raised a valid criticism.
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation) Your 2-sided test implicitly allots exactly half of your 5% significance level to "masks are harmful" ($M_-$) and the other half to "masks are beneficial" ($M_+$). To a Bayesian like Taleb that might
14,922
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation)
This simulation is an attempt to estimate the result of an exact test in which the chance of observing such an extreme disparity is $$\begin{aligned} \Pr(\text{all positive results in one group}) &= \frac{\binom{2470}{5} + \binom{2392}{5}}{\binom{2470+2392}{5}} \\&= 0.03377 + 0.02876 = 0.06253. \end{aligned}$$ This calculation is justified by the presumption that all $2470+2392$ subjects were independently randomized into the test and control groups. The terms in the numerator count the ways in which all five positive results could have ended up randomly in the first group or the second group. The denominator counts all possible five-element subsets of the group of all subjects, all of which are equally likely under this randomization assumption. For those who maintain (incorrectly, IMHO) that a one-sided test is appropriate here, I have shown the values of each of the two separate fractions. I believe this simple result is equivalent to both Fisher's Test and Boschloo's test. It might also be worth noting that the standard error in Taleb's Monte Carlo calculation is $$\operatorname{se} = \sqrt{0.03377(1-0.03377)/10^5} = 0.0005712,$$ bearing in mind he appears to have approximated $2392$ by $2400$ (which makes little difference). This places his result of $0.03483$ approximately $1.9$ standard errors below the true value, well within what one would expect of such a simulation.
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation)
This simulation is an attempt to estimate the result of an exact test in which the chance of observing such an extreme disparity is $$\begin{aligned} \Pr(\text{all positive results in one group}) &= \
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation) This simulation is an attempt to estimate the result of an exact test in which the chance of observing such an extreme disparity is $$\begin{aligned} \Pr(\text{all positive results in one group}) &= \frac{\binom{2470}{5} + \binom{2392}{5}}{\binom{2470+2392}{5}} \\&= 0.03377 + 0.02876 = 0.06253. \end{aligned}$$ This calculation is justified by the presumption that all $2470+2392$ subjects were independently randomized into the test and control groups. The terms in the numerator count the ways in which all five positive results could have ended up randomly in the first group or the second group. The denominator counts all possible five-element subsets of the group of all subjects, all of which are equally likely under this randomization assumption. For those who maintain (incorrectly, IMHO) that a one-sided test is appropriate here, I have shown the values of each of the two separate fractions. I believe this simple result is equivalent to both Fisher's Test and Boschloo's test. It might also be worth noting that the standard error in Taleb's Monte Carlo calculation is $$\operatorname{se} = \sqrt{0.03377(1-0.03377)/10^5} = 0.0005712,$$ bearing in mind he appears to have approximated $2392$ by $2400$ (which makes little difference). This places his result of $0.03483$ approximately $1.9$ standard errors below the true value, well within what one would expect of such a simulation.
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation) This simulation is an attempt to estimate the result of an exact test in which the chance of observing such an extreme disparity is $$\begin{aligned} \Pr(\text{all positive results in one group}) &= \
14,923
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation)
If you want to acquiesce to (i) avoiding methods that do p-values (ii) producing a more "bespoke" test for this problem (objectives mentioned by Taleb, not necessarilly something you agree with) One solution would be to simulate and find parameters by rejection sampling (actually approximate Bayesian computation). So let's say there are two key parameter: (a) the infection rate when maskless $r$ and (b) the % change in infection rate wearing a mask $m$. Let's put two uniform priors $r \sim U [.0001,.005]$ and $m \sim U[.5,1.5]$: a priori you think mask can cut risk by 50% or increase it by 50% (two-tailed as you suggested). We can run a simulation where we draw those two parameters, use them to sample 2392 observations with mask and 2470 without it. However we accept the simulation only where we it outputs precisely 5 positives when wearing no masks and 0 positives when wearing it. We keep doing this until we collect, say, 5000 simulations. When we look at the posteriors, the multiplier distribution has clearly shifted left and away from the original center at 1. However it is still true that the probability that the multiplier is above 1 is about 17% (far above the threshold of 5% we set ourselves). Everybody wins! library(tidyverse) library(progress) ### hard data from the paper WITH_MASK_OBSERVATIONS<-2392 WITHOUT_MASK_OBSERVATIONS<-2470 WITH_MASK_POSITIVES<-0 WITHOUT_MASK_POSITIVES<-5 ### here assume uniform priors on ### chances of getting sick PRIOR_INFECTION_RISK_MASKLESS<-function(){ runif(n=1,min=.0001,max=.005) } ### let's assume we have a uniform prior that masks can do anything ### between cutting risks by 50% and increasing it by 50% PRIOR_CHANGE_RISK_MASK<- function(){ runif(n=1,min=.5,max=1.5) } ### run simple ABC where we look for parameters ### where we get exactly the observations above accepted_runs<-list() TARGET_ACCEPTED_RUNS<-5000 pb <- progress_bar$new(total = TARGET_ACCEPTED_RUNS) ## to watch the time go by while(length(accepted_runs)<TARGET_ACCEPTED_RUNS) { ## draw a "real" infection rate from your priors infection_maskless<-PRIOR_INFECTION_RISK_MASKLESS() mask_multiplier<-PRIOR_CHANGE_RISK_MASK() infection_masked<- mask_multiplier * infection_maskless ## observe the infection rate! observed_infections_maskless<- sum( rbinom(n=WITHOUT_MASK_OBSERVATIONS, size=1, prob=infection_maskless)) observed_infections_mask<-sum( rbinom(n=WITH_MASK_OBSERVATIONS, size=1, prob=infection_masked)) ## if this is EXACTLY what we observe, store the drawn infection rates ## they will be part of our posterior if(observed_infections_maskless==WITHOUT_MASK_POSITIVES && observed_infections_mask==WITH_MASK_POSITIVES ){ pb$tick() accepted_runs<- append(accepted_runs, list(data.frame(maskless = infection_maskless, masked = infection_masked, multiplier = mask_multiplier))) } }
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation)
If you want to acquiesce to (i) avoiding methods that do p-values (ii) producing a more "bespoke" test for this problem (objectives mentioned by Taleb, not necessarilly something you agree with) One s
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation) If you want to acquiesce to (i) avoiding methods that do p-values (ii) producing a more "bespoke" test for this problem (objectives mentioned by Taleb, not necessarilly something you agree with) One solution would be to simulate and find parameters by rejection sampling (actually approximate Bayesian computation). So let's say there are two key parameter: (a) the infection rate when maskless $r$ and (b) the % change in infection rate wearing a mask $m$. Let's put two uniform priors $r \sim U [.0001,.005]$ and $m \sim U[.5,1.5]$: a priori you think mask can cut risk by 50% or increase it by 50% (two-tailed as you suggested). We can run a simulation where we draw those two parameters, use them to sample 2392 observations with mask and 2470 without it. However we accept the simulation only where we it outputs precisely 5 positives when wearing no masks and 0 positives when wearing it. We keep doing this until we collect, say, 5000 simulations. When we look at the posteriors, the multiplier distribution has clearly shifted left and away from the original center at 1. However it is still true that the probability that the multiplier is above 1 is about 17% (far above the threshold of 5% we set ourselves). Everybody wins! library(tidyverse) library(progress) ### hard data from the paper WITH_MASK_OBSERVATIONS<-2392 WITHOUT_MASK_OBSERVATIONS<-2470 WITH_MASK_POSITIVES<-0 WITHOUT_MASK_POSITIVES<-5 ### here assume uniform priors on ### chances of getting sick PRIOR_INFECTION_RISK_MASKLESS<-function(){ runif(n=1,min=.0001,max=.005) } ### let's assume we have a uniform prior that masks can do anything ### between cutting risks by 50% and increasing it by 50% PRIOR_CHANGE_RISK_MASK<- function(){ runif(n=1,min=.5,max=1.5) } ### run simple ABC where we look for parameters ### where we get exactly the observations above accepted_runs<-list() TARGET_ACCEPTED_RUNS<-5000 pb <- progress_bar$new(total = TARGET_ACCEPTED_RUNS) ## to watch the time go by while(length(accepted_runs)<TARGET_ACCEPTED_RUNS) { ## draw a "real" infection rate from your priors infection_maskless<-PRIOR_INFECTION_RISK_MASKLESS() mask_multiplier<-PRIOR_CHANGE_RISK_MASK() infection_masked<- mask_multiplier * infection_maskless ## observe the infection rate! observed_infections_maskless<- sum( rbinom(n=WITHOUT_MASK_OBSERVATIONS, size=1, prob=infection_maskless)) observed_infections_mask<-sum( rbinom(n=WITH_MASK_OBSERVATIONS, size=1, prob=infection_masked)) ## if this is EXACTLY what we observe, store the drawn infection rates ## they will be part of our posterior if(observed_infections_maskless==WITHOUT_MASK_POSITIVES && observed_infections_mask==WITH_MASK_POSITIVES ){ pb$tick() accepted_runs<- append(accepted_runs, list(data.frame(maskless = infection_maskless, masked = infection_masked, multiplier = mask_multiplier))) } }
Analysis of Danish mask study data by Nassim Nicholas Taleb (binomial GLM with complete separation) If you want to acquiesce to (i) avoiding methods that do p-values (ii) producing a more "bespoke" test for this problem (objectives mentioned by Taleb, not necessarilly something you agree with) One s
14,924
What is the difference between 'regular' linear regression and deep learning linear regression?
Assuming that by deep learning you meant more precisely neural networks: a vanilla fully connected feedforward neural network with only linear activation functions will perform linear regression, regardless of how many layers it has. One difference is that with a neural network one typically uses gradient descent, whereas with "normal" linear regression one uses the normal equation if possible (when the number of features isn't too huge). Example of a fully connected feedforward neural network with no hidden layer and using a linear activation function (namely the identity activation function): If you replace the activation function of the output layer with a sigmoid function, then the neural network performs logistic regression. If you replace the activation function of the output layer with a softmax function and add a few output units, then the neural network performs multiclass logistic regression: Difference between logistic regression and neural networks. If you replace the cost function with the hinge loss, then the neural network is an SVM optimized in its primal form: http://cs231n.github.io/linear-classify/. Here is the example shown in the picture above programmed in TensorFlow: """ Linear Regression Example """ # https://github.com/tflearn/tflearn/blob/master/examples/basics/linear_regression.py from __future__ import absolute_import, division, print_function import tflearn # Regression data X = [3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1] Y = [1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3] # Linear Regression graph input_ = tflearn.input_data(shape=[None]) linear = tflearn.single_unit(input_) regression = tflearn.regression(linear, optimizer='sgd', loss='mean_square', metric='R2', learning_rate=0.01) m = tflearn.DNN(regression) m.fit(X, Y, n_epoch=1000, show_metric=True, snapshot_epoch=False) print("\nRegression result:") print("Y = " + str(m.get_weights(linear.W)) + "*X + " + str(m.get_weights(linear.b))) print("\nTest prediction for x = 3.2, 3.3, 3.4:") print(m.predict([3.2, 3.3, 3.4])) # should output (close, not exact) y = [1.5315033197402954, 1.5585315227508545, 1.5855598449707031] Here is a code snippet that does not use any neural network libraries: # From http://briandolhansky.com/blog/artificial-neural-networks-linear-regression-part-1 import matplotlib.pyplot as plt import numpy as np # Load the data and create the data matrices X and Y # This creates a feature vector X with a column of ones (bias) # and a column of car weights. # The target vector Y is a column of MPG values for each car. X_file = np.genfromtxt('mpg.csv', delimiter=',', skip_header=1) N = np.shape(X_file)[0] X = np.hstack((np.ones(N).reshape(N, 1), X_file[:, 4].reshape(N, 1))) Y = X_file[:, 0] # Standardize the input X[:, 1] = (X[:, 1]-np.mean(X[:, 1]))/np.std(X[:, 1]) # There are two weights, the bias weight and the feature weight w = np.array([0, 0]) # Start batch gradient descent, it will run for max_iter epochs and have a step # size eta max_iter = 100 eta = 1E-3 for t in range(0, max_iter): # We need to iterate over each data point for one epoch grad_t = np.array([0., 0.]) for i in range(0, N): x_i = X[i, :] y_i = Y[i] # Dot product, computes h(x_i, w) h = np.dot(w, x_i)-y_i grad_t += 2*x_i*h # Update the weights w = w - eta*grad_t print "Weights found:",w # Plot the data and best fit line tt = np.linspace(np.min(X[:, 1]), np.max(X[:, 1]), 10) bf_line = w[0]+w[1]*tt plt.plot(X[:, 1], Y, 'kx', tt, bf_line, 'r-') plt.xlabel('Weight (Normalized)') plt.ylabel('MPG') plt.title('ANN Regression on 1D MPG Data') plt.savefig('mpg.png') plt.show() Data file mpg.csv (~50% abridged due to Stack Exchange answer size limitation): mpg (n),cylinders (n),displacement (n),horsepower (n),weight (n),acceleration (n),year (n),origin (n), name (s) 18.000000,8.000000,307.000000,130.000000,3504.000000,12.000000,70.000000,1.000000 15.000000,8.000000,350.000000,165.000000,3693.000000,11.500000,70.000000,1.000000 18.000000,8.000000,318.000000,150.000000,3436.000000,11.000000,70.000000,1.000000 16.000000,8.000000,304.000000,150.000000,3433.000000,12.000000,70.000000,1.000000 17.000000,8.000000,302.000000,140.000000,3449.000000,10.500000,70.000000,1.000000 15.000000,8.000000,429.000000,198.000000,4341.000000,10.000000,70.000000,1.000000 14.000000,8.000000,454.000000,220.000000,4354.000000,9.000000,70.000000,1.000000 14.000000,8.000000,440.000000,215.000000,4312.000000,8.500000,70.000000,1.000000 14.000000,8.000000,455.000000,225.000000,4425.000000,10.000000,70.000000,1.000000 15.000000,8.000000,390.000000,190.000000,3850.000000,8.500000,70.000000,1.000000 15.000000,8.000000,383.000000,170.000000,3563.000000,10.000000,70.000000,1.000000 14.000000,8.000000,340.000000,160.000000,3609.000000,8.000000,70.000000,1.000000 15.000000,8.000000,400.000000,150.000000,3761.000000,9.500000,70.000000,1.000000 14.000000,8.000000,455.000000,225.000000,3086.000000,10.000000,70.000000,1.000000 24.000000,4.000000,113.000000,95.000000,2372.000000,15.000000,70.000000,3.000000 22.000000,6.000000,198.000000,95.000000,2833.000000,15.500000,70.000000,1.000000 18.000000,6.000000,199.000000,97.000000,2774.000000,15.500000,70.000000,1.000000 21.000000,6.000000,200.000000,85.000000,2587.000000,16.000000,70.000000,1.000000 27.000000,4.000000,97.000000,88.000000,2130.000000,14.500000,70.000000,3.000000 26.000000,4.000000,97.000000,46.000000,1835.000000,20.500000,70.000000,2.000000 25.000000,4.000000,110.000000,87.000000,2672.000000,17.500000,70.000000,2.000000 24.000000,4.000000,107.000000,90.000000,2430.000000,14.500000,70.000000,2.000000 25.000000,4.000000,104.000000,95.000000,2375.000000,17.500000,70.000000,2.000000 26.000000,4.000000,121.000000,113.000000,2234.000000,12.500000,70.000000,2.000000 21.000000,6.000000,199.000000,90.000000,2648.000000,15.000000,70.000000,1.000000 10.000000,8.000000,360.000000,215.000000,4615.000000,14.000000,70.000000,1.000000 10.000000,8.000000,307.000000,200.000000,4376.000000,15.000000,70.000000,1.000000 11.000000,8.000000,318.000000,210.000000,4382.000000,13.500000,70.000000,1.000000 9.000000,8.000000,304.000000,193.000000,4732.000000,18.500000,70.000000,1.000000 27.000000,4.000000,97.000000,88.000000,2130.000000,14.500000,71.000000,3.000000 28.000000,4.000000,140.000000,90.000000,2264.000000,15.500000,71.000000,1.000000 25.000000,4.000000,113.000000,95.000000,2228.000000,14.000000,71.000000,3.000000 19.000000,6.000000,232.000000,100.000000,2634.000000,13.000000,71.000000,1.000000 16.000000,6.000000,225.000000,105.000000,3439.000000,15.500000,71.000000,1.000000 17.000000,6.000000,250.000000,100.000000,3329.000000,15.500000,71.000000,1.000000 19.000000,6.000000,250.000000,88.000000,3302.000000,15.500000,71.000000,1.000000 18.000000,6.000000,232.000000,100.000000,3288.000000,15.500000,71.000000,1.000000 14.000000,8.000000,350.000000,165.000000,4209.000000,12.000000,71.000000,1.000000 14.000000,8.000000,400.000000,175.000000,4464.000000,11.500000,71.000000,1.000000 14.000000,8.000000,351.000000,153.000000,4154.000000,13.500000,71.000000,1.000000 14.000000,8.000000,318.000000,150.000000,4096.000000,13.000000,71.000000,1.000000 12.000000,8.000000,383.000000,180.000000,4955.000000,11.500000,71.000000,1.000000 13.000000,8.000000,400.000000,170.000000,4746.000000,12.000000,71.000000,1.000000 13.000000,8.000000,400.000000,175.000000,5140.000000,12.000000,71.000000,1.000000 18.000000,6.000000,258.000000,110.000000,2962.000000,13.500000,71.000000,1.000000 22.000000,4.000000,140.000000,72.000000,2408.000000,19.000000,71.000000,1.000000 19.000000,6.000000,250.000000,100.000000,3282.000000,15.000000,71.000000,1.000000 18.000000,6.000000,250.000000,88.000000,3139.000000,14.500000,71.000000,1.000000 23.000000,4.000000,122.000000,86.000000,2220.000000,14.000000,71.000000,1.000000 28.000000,4.000000,116.000000,90.000000,2123.000000,14.000000,71.000000,2.000000 30.000000,4.000000,79.000000,70.000000,2074.000000,19.500000,71.000000,2.000000 30.000000,4.000000,88.000000,76.000000,2065.000000,14.500000,71.000000,2.000000 31.000000,4.000000,71.000000,65.000000,1773.000000,19.000000,71.000000,3.000000 35.000000,4.000000,72.000000,69.000000,1613.000000,18.000000,71.000000,3.000000 27.000000,4.000000,97.000000,60.000000,1834.000000,19.000000,71.000000,2.000000 26.000000,4.000000,91.000000,70.000000,1955.000000,20.500000,71.000000,1.000000 24.000000,4.000000,113.000000,95.000000,2278.000000,15.500000,72.000000,3.000000 25.000000,4.000000,97.500000,80.000000,2126.000000,17.000000,72.000000,1.000000 23.000000,4.000000,97.000000,54.000000,2254.000000,23.500000,72.000000,2.000000 20.000000,4.000000,140.000000,90.000000,2408.000000,19.500000,72.000000,1.000000 21.000000,4.000000,122.000000,86.000000,2226.000000,16.500000,72.000000,1.000000 13.000000,8.000000,350.000000,165.000000,4274.000000,12.000000,72.000000,1.000000 14.000000,8.000000,400.000000,175.000000,4385.000000,12.000000,72.000000,1.000000 15.000000,8.000000,318.000000,150.000000,4135.000000,13.500000,72.000000,1.000000 14.000000,8.000000,351.000000,153.000000,4129.000000,13.000000,72.000000,1.000000 17.000000,8.000000,304.000000,150.000000,3672.000000,11.500000,72.000000,1.000000 11.000000,8.000000,429.000000,208.000000,4633.000000,11.000000,72.000000,1.000000 13.000000,8.000000,350.000000,155.000000,4502.000000,13.500000,72.000000,1.000000 12.000000,8.000000,350.000000,160.000000,4456.000000,13.500000,72.000000,1.000000 13.000000,8.000000,400.000000,190.000000,4422.000000,12.500000,72.000000,1.000000 19.000000,3.000000,70.000000,97.000000,2330.000000,13.500000,72.000000,3.000000 15.000000,8.000000,304.000000,150.000000,3892.000000,12.500000,72.000000,1.000000 13.000000,8.000000,307.000000,130.000000,4098.000000,14.000000,72.000000,1.000000 13.000000,8.000000,302.000000,140.000000,4294.000000,16.000000,72.000000,1.000000 14.000000,8.000000,318.000000,150.000000,4077.000000,14.000000,72.000000,1.000000 18.000000,4.000000,121.000000,112.000000,2933.000000,14.500000,72.000000,2.000000 22.000000,4.000000,121.000000,76.000000,2511.000000,18.000000,72.000000,2.000000 21.000000,4.000000,120.000000,87.000000,2979.000000,19.500000,72.000000,2.000000 26.000000,4.000000,96.000000,69.000000,2189.000000,18.000000,72.000000,2.000000 22.000000,4.000000,122.000000,86.000000,2395.000000,16.000000,72.000000,1.000000 28.000000,4.000000,97.000000,92.000000,2288.000000,17.000000,72.000000,3.000000 23.000000,4.000000,120.000000,97.000000,2506.000000,14.500000,72.000000,3.000000 28.000000,4.000000,98.000000,80.000000,2164.000000,15.000000,72.000000,1.000000 27.000000,4.000000,97.000000,88.000000,2100.000000,16.500000,72.000000,3.000000 13.000000,8.000000,350.000000,175.000000,4100.000000,13.000000,73.000000,1.000000 14.000000,8.000000,304.000000,150.000000,3672.000000,11.500000,73.000000,1.000000 13.000000,8.000000,350.000000,145.000000,3988.000000,13.000000,73.000000,1.000000 14.000000,8.000000,302.000000,137.000000,4042.000000,14.500000,73.000000,1.000000 15.000000,8.000000,318.000000,150.000000,3777.000000,12.500000,73.000000,1.000000 12.000000,8.000000,429.000000,198.000000,4952.000000,11.500000,73.000000,1.000000 13.000000,8.000000,400.000000,150.000000,4464.000000,12.000000,73.000000,1.000000 13.000000,8.000000,351.000000,158.000000,4363.000000,13.000000,73.000000,1.000000 14.000000,8.000000,318.000000,150.000000,4237.000000,14.500000,73.000000,1.000000 13.000000,8.000000,440.000000,215.000000,4735.000000,11.000000,73.000000,1.000000 12.000000,8.000000,455.000000,225.000000,4951.000000,11.000000,73.000000,1.000000 13.000000,8.000000,360.000000,175.000000,3821.000000,11.000000,73.000000,1.000000 18.000000,6.000000,225.000000,105.000000,3121.000000,16.500000,73.000000,1.000000 16.000000,6.000000,250.000000,100.000000,3278.000000,18.000000,73.000000,1.000000 18.000000,6.000000,232.000000,100.000000,2945.000000,16.000000,73.000000,1.000000 18.000000,6.000000,250.000000,88.000000,3021.000000,16.500000,73.000000,1.000000 23.000000,6.000000,198.000000,95.000000,2904.000000,16.000000,73.000000,1.000000 26.000000,4.000000,97.000000,46.000000,1950.000000,21.000000,73.000000,2.000000 11.000000,8.000000,400.000000,150.000000,4997.000000,14.000000,73.000000,1.000000 12.000000,8.000000,400.000000,167.000000,4906.000000,12.500000,73.000000,1.000000 13.000000,8.000000,360.000000,170.000000,4654.000000,13.000000,73.000000,1.000000 12.000000,8.000000,350.000000,180.000000,4499.000000,12.500000,73.000000,1.000000 18.000000,6.000000,232.000000,100.000000,2789.000000,15.000000,73.000000,1.000000 20.000000,4.000000,97.000000,88.000000,2279.000000,19.000000,73.000000,3.000000 21.000000,4.000000,140.000000,72.000000,2401.000000,19.500000,73.000000,1.000000 22.000000,4.000000,108.000000,94.000000,2379.000000,16.500000,73.000000,3.000000 18.000000,3.000000,70.000000,90.000000,2124.000000,13.500000,73.000000,3.000000 19.000000,4.000000,122.000000,85.000000,2310.000000,18.500000,73.000000,1.000000 21.000000,6.000000,155.000000,107.000000,2472.000000,14.000000,73.000000,1.000000 26.000000,4.000000,98.000000,90.000000,2265.000000,15.500000,73.000000,2.000000 15.000000,8.000000,350.000000,145.000000,4082.000000,13.000000,73.000000,1.000000 16.000000,8.000000,400.000000,230.000000,4278.000000,9.500000,73.000000,1.000000 29.000000,4.000000,68.000000,49.000000,1867.000000,19.500000,73.000000,2.000000 24.000000,4.000000,116.000000,75.000000,2158.000000,15.500000,73.000000,2.000000 20.000000,4.000000,114.000000,91.000000,2582.000000,14.000000,73.000000,2.000000 19.000000,4.000000,121.000000,112.000000,2868.000000,15.500000,73.000000,2.000000 15.000000,8.000000,318.000000,150.000000,3399.000000,11.000000,73.000000,1.000000 24.000000,4.000000,121.000000,110.000000,2660.000000,14.000000,73.000000,2.000000 20.000000,6.000000,156.000000,122.000000,2807.000000,13.500000,73.000000,3.000000 11.000000,8.000000,350.000000,180.000000,3664.000000,11.000000,73.000000,1.000000 20.000000,6.000000,198.000000,95.000000,3102.000000,16.500000,74.000000,1.000000 19.000000,6.000000,232.000000,100.000000,2901.000000,16.000000,74.000000,1.000000 15.000000,6.000000,250.000000,100.000000,3336.000000,17.000000,74.000000,1.000000 31.000000,4.000000,79.000000,67.000000,1950.000000,19.000000,74.000000,3.000000 26.000000,4.000000,122.000000,80.000000,2451.000000,16.500000,74.000000,1.000000 32.000000,4.000000,71.000000,65.000000,1836.000000,21.000000,74.000000,3.000000 25.000000,4.000000,140.000000,75.000000,2542.000000,17.000000,74.000000,1.000000 16.000000,6.000000,250.000000,100.000000,3781.000000,17.000000,74.000000,1.000000 16.000000,6.000000,258.000000,110.000000,3632.000000,18.000000,74.000000,1.000000 18.000000,6.000000,225.000000,105.000000,3613.000000,16.500000,74.000000,1.000000 16.000000,8.000000,302.000000,140.000000,4141.000000,14.000000,74.000000,1.000000 13.000000,8.000000,350.000000,150.000000,4699.000000,14.500000,74.000000,1.000000 14.000000,8.000000,318.000000,150.000000,4457.000000,13.500000,74.000000,1.000000 14.000000,8.000000,302.000000,140.000000,4638.000000,16.000000,74.000000,1.000000 14.000000,8.000000,304.000000,150.000000,4257.000000,15.500000,74.000000,1.000000 29.000000,4.000000,98.000000,83.000000,2219.000000,16.500000,74.000000,2.000000 26.000000,4.000000,79.000000,67.000000,1963.000000,15.500000,74.000000,2.000000 26.000000,4.000000,97.000000,78.000000,2300.000000,14.500000,74.000000,2.000000 31.000000,4.000000,76.000000,52.000000,1649.000000,16.500000,74.000000,3.000000 32.000000,4.000000,83.000000,61.000000,2003.000000,19.000000,74.000000,3.000000 28.000000,4.000000,90.000000,75.000000,2125.000000,14.500000,74.000000,1.000000 24.000000,4.000000,90.000000,75.000000,2108.000000,15.500000,74.000000,2.000000 26.000000,4.000000,116.000000,75.000000,2246.000000,14.000000,74.000000,2.000000 24.000000,4.000000,120.000000,97.000000,2489.000000,15.000000,74.000000,3.000000 26.000000,4.000000,108.000000,93.000000,2391.000000,15.500000,74.000000,3.000000 31.000000,4.000000,79.000000,67.000000,2000.000000,16.000000,74.000000,2.000000 19.000000,6.000000,225.000000,95.000000,3264.000000,16.000000,75.000000,1.000000 18.000000,6.000000,250.000000,105.000000,3459.000000,16.000000,75.000000,1.000000 15.000000,6.000000,250.000000,72.000000,3432.000000,21.000000,75.000000,1.000000 15.000000,6.000000,250.000000,72.000000,3158.000000,19.500000,75.000000,1.000000 16.000000,8.000000,400.000000,170.000000,4668.000000,11.500000,75.000000,1.000000 15.000000,8.000000,350.000000,145.000000,4440.000000,14.000000,75.000000,1.000000 16.000000,8.000000,318.000000,150.000000,4498.000000,14.500000,75.000000,1.000000 14.000000,8.000000,351.000000,148.000000,4657.000000,13.500000,75.000000,1.000000 17.000000,6.000000,231.000000,110.000000,3907.000000,21.000000,75.000000,1.000000 16.000000,6.000000,250.000000,105.000000,3897.000000,18.500000,75.000000,1.000000 15.000000,6.000000,258.000000,110.000000,3730.000000,19.000000,75.000000,1.000000 18.000000,6.000000,225.000000,95.000000,3785.000000,19.000000,75.000000,1.000000 21.000000,6.000000,231.000000,110.000000,3039.000000,15.000000,75.000000,1.000000 20.000000,8.000000,262.000000,110.000000,3221.000000,13.500000,75.000000,1.000000 13.000000,8.000000,302.000000,129.000000,3169.000000,12.000000,75.000000,1.000000 29.000000,4.000000,97.000000,75.000000,2171.000000,16.000000,75.000000,3.000000 23.000000,4.000000,140.000000,83.000000,2639.000000,17.000000,75.000000,1.000000 20.000000,6.000000,232.000000,100.000000,2914.000000,16.000000,75.000000,1.000000 23.000000,4.000000,140.000000,78.000000,2592.000000,18.500000,75.000000,1.000000 24.000000,4.000000,134.000000,96.000000,2702.000000,13.500000,75.000000,3.000000 25.000000,4.000000,90.000000,71.000000,2223.000000,16.500000,75.000000,2.000000 24.000000,4.000000,119.000000,97.000000,2545.000000,17.000000,75.000000,3.000000 18.000000,6.000000,171.000000,97.000000,2984.000000,14.500000,75.000000,1.000000 29.000000,4.000000,90.000000,70.000000,1937.000000,14.000000,75.000000,2.000000 19.000000,6.000000,232.000000,90.000000,3211.000000,17.000000,75.000000,1.000000 23.000000,4.000000,115.000000,95.000000,2694.000000,15.000000,75.000000,2.000000 23.000000,4.000000,120.000000,88.000000,2957.000000,17.000000,75.000000,2.000000 22.000000,4.000000,121.000000,98.000000,2945.000000,14.500000,75.000000,2.000000 25.000000,4.000000,121.000000,115.000000,2671.000000,13.500000,75.000000,2.000000 33.000000,4.000000,91.000000,53.000000,1795.000000,17.500000,75.000000,3.000000 28.000000,4.000000,107.000000,86.000000,2464.000000,15.500000,76.000000,2.000000 25.000000,4.000000,116.000000,81.000000,2220.000000,16.900000,76.000000,2.000000 25.000000,4.000000,140.000000,92.000000,2572.000000,14.900000,76.000000,1.000000 26.000000,4.000000,98.000000,79.000000,2255.000000,17.700000,76.000000,1.000000 27.000000,4.000000,101.000000,83.000000,2202.000000,15.300000,76.000000,2.000000 17.500000,8.000000,305.000000,140.000000,4215.000000,13.000000,76.000000,1.000000 16.000000,8.000000,318.000000,150.000000,4190.000000,13.000000,76.000000,1.000000 15.500000,8.000000,304.000000,120.000000,3962.000000,13.900000,76.000000,1.000000 14.500000,8.000000,351.000000,152.000000,4215.000000,12.800000,76.000000,1.000000 22.000000,6.000000,225.000000,100.000000,3233.000000,15.400000,76.000000,1.000000 22.000000,6.000000,250.000000,105.000000,3353.000000,14.500000,76.000000,1.000000 24.000000,6.000000,200.000000,81.000000,3012.000000,17.600000,76.000000,1.000000 22.500000,6.000000,232.000000,90.000000,3085.000000,17.600000,76.000000,1.000000 29.000000,4.000000,85.000000,52.000000,2035.000000,22.200000,76.000000,1.000000 24.500000,4.000000,98.000000,60.000000,2164.000000,22.100000,76.000000,1.000000 29.000000,4.000000,90.000000,70.000000,1937.000000,14.200000,76.000000,2.000000 33.000000,4.000000,91.000000,53.000000,1795.000000,17.400000,76.000000,3.000000 20.000000,6.000000,225.000000,100.000000,3651.000000,17.700000,76.000000,1.000000 18.000000,6.000000,250.000000,78.000000,3574.000000,21.000000,76.000000,1.000000 18.500000,6.000000,250.000000,110.000000,3645.000000,16.200000,76.000000,1.000000 17.500000,6.000000,258.000000,95.000000,3193.000000,17.800000,76.000000,1.000000 29.500000,4.000000,97.000000,71.000000,1825.000000,12.200000,76.000000,2.000000 32.000000,4.000000,85.000000,70.000000,1990.000000,17.000000,76.000000,3.000000 28.000000,4.000000,97.000000,75.000000,2155.000000,16.400000,76.000000,3.000000 26.500000,4.000000,140.000000,72.000000,2565.000000,13.600000,76.000000,1.000000 20.000000,4.000000,130.000000,102.000000,3150.000000,15.700000,76.000000,2.000000 13.000000,8.000000,318.000000,150.000000,3940.000000,13.200000,76.000000,1.000000 19.000000,4.000000,120.000000,88.000000,3270.000000,21.900000,76.000000,2.000000 19.000000,6.000000,156.000000,108.000000,2930.000000,15.500000,76.000000,3.000000 16.500000,6.000000,168.000000,120.000000,3820.000000,16.700000,76.000000,2.000000 16.500000,8.000000,350.000000,180.000000,4380.000000,12.100000,76.000000,1.000000 13.000000,8.000000,350.000000,145.000000,4055.000000,12.000000,76.000000,1.000000 13.000000,8.000000,302.000000,130.000000,3870.000000,15.000000,76.000000,1.000000 13.000000,8.000000,318.000000,150.000000,3755.000000,14.000000,76.000000,1.000000 31.500000,4.000000,98.000000,68.000000,2045.000000,18.500000,77.000000,3.000000 30.000000,4.000000,111.000000,80.000000,2155.000000,14.800000,77.000000,1.000000 36.000000,4.000000,79.000000,58.000000,1825.000000,18.600000,77.000000,2.000000 25.500000,4.000000,122.000000,96.000000,2300.000000,15.500000,77.000000,1.000000 33.500000,4.000000,85.000000,70.000000,1945.000000,16.800000,77.000000,3.000000 17.500000,8.000000,305.000000,145.000000,3880.000000,12.500000,77.000000,1.000000 17.000000,8.000000,260.000000,110.000000,4060.000000,19.000000,77.000000,1.000000 15.500000,8.000000,318.000000,145.000000,4140.000000,13.700000,77.000000,1.000000 15.000000,8.000000,302.000000,130.000000,4295.000000,14.900000,77.000000,1.000000 17.500000,6.000000,250.000000,110.000000,3520.000000,16.400000,77.000000,1.000000 20.500000,6.000000,231.000000,105.000000,3425.000000,16.900000,77.000000,1.000000 19.000000,6.000000,225.000000,100.000000,3630.000000,17.700000,77.000000,1.000000 18.500000,6.000000,250.000000,98.000000,3525.000000,19.000000,77.000000,1.000000 16.000000,8.000000,400.000000,180.000000,4220.000000,11.100000,77.000000,1.000000 15.500000,8.000000,350.000000,170.000000,4165.000000,11.400000,77.000000,1.000000 15.500000,8.000000,400.000000,190.000000,4325.000000,12.200000,77.000000,1.000000 16.000000,8.000000,351.000000,149.000000,4335.000000,14.500000,77.000000,1.000000 29.000000,4.000000,97.000000,78.000000,1940.000000,14.500000,77.000000,2.000000 24.500000,4.000000,151.000000,88.000000,2740.000000,16.000000,77.000000,1.000000 26.000000,4.000000,97.000000,75.000000,2265.000000,18.200000,77.000000,3.000000 25.500000,4.000000,140.000000,89.000000,2755.000000,15.800000,77.000000,1.000000 30.500000,4.000000,98.000000,63.000000,2051.000000,17.000000,77.000000,1.000000 33.500000,4.000000,98.000000,83.000000,2075.000000,15.900000,77.000000,1.000000 30.000000,4.000000,97.000000,67.000000,1985.000000,16.400000,77.000000,3.000000 30.500000,4.000000,97.000000,78.000000,2190.000000,14.100000,77.000000,2.000000 22.000000,6.000000,146.000000,97.000000,2815.000000,14.500000,77.000000,3.000000 21.500000,4.000000,121.000000,110.000000,2600.000000,12.800000,77.000000,2.000000 21.500000,3.000000,80.000000,110.000000,2720.000000,13.500000,77.000000,3.000000 43.100000,4.000000,90.000000,48.000000,1985.000000,21.500000,78.000000,2.000000 36.100000,4.000000,98.000000,66.000000,1800.000000,14.400000,78.000000,1.000000 32.800000,4.000000,78.000000,52.000000,1985.000000,19.400000,78.000000,3.000000 39.400000,4.000000,85.000000,70.000000,2070.000000,18.600000,78.000000,3.000000 36.100000,4.000000,91.000000,60.000000,1800.000000,16.400000,78.000000,3.000000 19.900000,8.000000,260.000000,110.000000,3365.000000,15.500000,78.000000,1.000000
What is the difference between 'regular' linear regression and deep learning linear regression?
Assuming that by deep learning you meant more precisely neural networks: a vanilla fully connected feedforward neural network with only linear activation functions will perform linear regression, reg
What is the difference between 'regular' linear regression and deep learning linear regression? Assuming that by deep learning you meant more precisely neural networks: a vanilla fully connected feedforward neural network with only linear activation functions will perform linear regression, regardless of how many layers it has. One difference is that with a neural network one typically uses gradient descent, whereas with "normal" linear regression one uses the normal equation if possible (when the number of features isn't too huge). Example of a fully connected feedforward neural network with no hidden layer and using a linear activation function (namely the identity activation function): If you replace the activation function of the output layer with a sigmoid function, then the neural network performs logistic regression. If you replace the activation function of the output layer with a softmax function and add a few output units, then the neural network performs multiclass logistic regression: Difference between logistic regression and neural networks. If you replace the cost function with the hinge loss, then the neural network is an SVM optimized in its primal form: http://cs231n.github.io/linear-classify/. Here is the example shown in the picture above programmed in TensorFlow: """ Linear Regression Example """ # https://github.com/tflearn/tflearn/blob/master/examples/basics/linear_regression.py from __future__ import absolute_import, division, print_function import tflearn # Regression data X = [3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1] Y = [1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3] # Linear Regression graph input_ = tflearn.input_data(shape=[None]) linear = tflearn.single_unit(input_) regression = tflearn.regression(linear, optimizer='sgd', loss='mean_square', metric='R2', learning_rate=0.01) m = tflearn.DNN(regression) m.fit(X, Y, n_epoch=1000, show_metric=True, snapshot_epoch=False) print("\nRegression result:") print("Y = " + str(m.get_weights(linear.W)) + "*X + " + str(m.get_weights(linear.b))) print("\nTest prediction for x = 3.2, 3.3, 3.4:") print(m.predict([3.2, 3.3, 3.4])) # should output (close, not exact) y = [1.5315033197402954, 1.5585315227508545, 1.5855598449707031] Here is a code snippet that does not use any neural network libraries: # From http://briandolhansky.com/blog/artificial-neural-networks-linear-regression-part-1 import matplotlib.pyplot as plt import numpy as np # Load the data and create the data matrices X and Y # This creates a feature vector X with a column of ones (bias) # and a column of car weights. # The target vector Y is a column of MPG values for each car. X_file = np.genfromtxt('mpg.csv', delimiter=',', skip_header=1) N = np.shape(X_file)[0] X = np.hstack((np.ones(N).reshape(N, 1), X_file[:, 4].reshape(N, 1))) Y = X_file[:, 0] # Standardize the input X[:, 1] = (X[:, 1]-np.mean(X[:, 1]))/np.std(X[:, 1]) # There are two weights, the bias weight and the feature weight w = np.array([0, 0]) # Start batch gradient descent, it will run for max_iter epochs and have a step # size eta max_iter = 100 eta = 1E-3 for t in range(0, max_iter): # We need to iterate over each data point for one epoch grad_t = np.array([0., 0.]) for i in range(0, N): x_i = X[i, :] y_i = Y[i] # Dot product, computes h(x_i, w) h = np.dot(w, x_i)-y_i grad_t += 2*x_i*h # Update the weights w = w - eta*grad_t print "Weights found:",w # Plot the data and best fit line tt = np.linspace(np.min(X[:, 1]), np.max(X[:, 1]), 10) bf_line = w[0]+w[1]*tt plt.plot(X[:, 1], Y, 'kx', tt, bf_line, 'r-') plt.xlabel('Weight (Normalized)') plt.ylabel('MPG') plt.title('ANN Regression on 1D MPG Data') plt.savefig('mpg.png') plt.show() Data file mpg.csv (~50% abridged due to Stack Exchange answer size limitation): mpg (n),cylinders (n),displacement (n),horsepower (n),weight (n),acceleration (n),year (n),origin (n), name (s) 18.000000,8.000000,307.000000,130.000000,3504.000000,12.000000,70.000000,1.000000 15.000000,8.000000,350.000000,165.000000,3693.000000,11.500000,70.000000,1.000000 18.000000,8.000000,318.000000,150.000000,3436.000000,11.000000,70.000000,1.000000 16.000000,8.000000,304.000000,150.000000,3433.000000,12.000000,70.000000,1.000000 17.000000,8.000000,302.000000,140.000000,3449.000000,10.500000,70.000000,1.000000 15.000000,8.000000,429.000000,198.000000,4341.000000,10.000000,70.000000,1.000000 14.000000,8.000000,454.000000,220.000000,4354.000000,9.000000,70.000000,1.000000 14.000000,8.000000,440.000000,215.000000,4312.000000,8.500000,70.000000,1.000000 14.000000,8.000000,455.000000,225.000000,4425.000000,10.000000,70.000000,1.000000 15.000000,8.000000,390.000000,190.000000,3850.000000,8.500000,70.000000,1.000000 15.000000,8.000000,383.000000,170.000000,3563.000000,10.000000,70.000000,1.000000 14.000000,8.000000,340.000000,160.000000,3609.000000,8.000000,70.000000,1.000000 15.000000,8.000000,400.000000,150.000000,3761.000000,9.500000,70.000000,1.000000 14.000000,8.000000,455.000000,225.000000,3086.000000,10.000000,70.000000,1.000000 24.000000,4.000000,113.000000,95.000000,2372.000000,15.000000,70.000000,3.000000 22.000000,6.000000,198.000000,95.000000,2833.000000,15.500000,70.000000,1.000000 18.000000,6.000000,199.000000,97.000000,2774.000000,15.500000,70.000000,1.000000 21.000000,6.000000,200.000000,85.000000,2587.000000,16.000000,70.000000,1.000000 27.000000,4.000000,97.000000,88.000000,2130.000000,14.500000,70.000000,3.000000 26.000000,4.000000,97.000000,46.000000,1835.000000,20.500000,70.000000,2.000000 25.000000,4.000000,110.000000,87.000000,2672.000000,17.500000,70.000000,2.000000 24.000000,4.000000,107.000000,90.000000,2430.000000,14.500000,70.000000,2.000000 25.000000,4.000000,104.000000,95.000000,2375.000000,17.500000,70.000000,2.000000 26.000000,4.000000,121.000000,113.000000,2234.000000,12.500000,70.000000,2.000000 21.000000,6.000000,199.000000,90.000000,2648.000000,15.000000,70.000000,1.000000 10.000000,8.000000,360.000000,215.000000,4615.000000,14.000000,70.000000,1.000000 10.000000,8.000000,307.000000,200.000000,4376.000000,15.000000,70.000000,1.000000 11.000000,8.000000,318.000000,210.000000,4382.000000,13.500000,70.000000,1.000000 9.000000,8.000000,304.000000,193.000000,4732.000000,18.500000,70.000000,1.000000 27.000000,4.000000,97.000000,88.000000,2130.000000,14.500000,71.000000,3.000000 28.000000,4.000000,140.000000,90.000000,2264.000000,15.500000,71.000000,1.000000 25.000000,4.000000,113.000000,95.000000,2228.000000,14.000000,71.000000,3.000000 19.000000,6.000000,232.000000,100.000000,2634.000000,13.000000,71.000000,1.000000 16.000000,6.000000,225.000000,105.000000,3439.000000,15.500000,71.000000,1.000000 17.000000,6.000000,250.000000,100.000000,3329.000000,15.500000,71.000000,1.000000 19.000000,6.000000,250.000000,88.000000,3302.000000,15.500000,71.000000,1.000000 18.000000,6.000000,232.000000,100.000000,3288.000000,15.500000,71.000000,1.000000 14.000000,8.000000,350.000000,165.000000,4209.000000,12.000000,71.000000,1.000000 14.000000,8.000000,400.000000,175.000000,4464.000000,11.500000,71.000000,1.000000 14.000000,8.000000,351.000000,153.000000,4154.000000,13.500000,71.000000,1.000000 14.000000,8.000000,318.000000,150.000000,4096.000000,13.000000,71.000000,1.000000 12.000000,8.000000,383.000000,180.000000,4955.000000,11.500000,71.000000,1.000000 13.000000,8.000000,400.000000,170.000000,4746.000000,12.000000,71.000000,1.000000 13.000000,8.000000,400.000000,175.000000,5140.000000,12.000000,71.000000,1.000000 18.000000,6.000000,258.000000,110.000000,2962.000000,13.500000,71.000000,1.000000 22.000000,4.000000,140.000000,72.000000,2408.000000,19.000000,71.000000,1.000000 19.000000,6.000000,250.000000,100.000000,3282.000000,15.000000,71.000000,1.000000 18.000000,6.000000,250.000000,88.000000,3139.000000,14.500000,71.000000,1.000000 23.000000,4.000000,122.000000,86.000000,2220.000000,14.000000,71.000000,1.000000 28.000000,4.000000,116.000000,90.000000,2123.000000,14.000000,71.000000,2.000000 30.000000,4.000000,79.000000,70.000000,2074.000000,19.500000,71.000000,2.000000 30.000000,4.000000,88.000000,76.000000,2065.000000,14.500000,71.000000,2.000000 31.000000,4.000000,71.000000,65.000000,1773.000000,19.000000,71.000000,3.000000 35.000000,4.000000,72.000000,69.000000,1613.000000,18.000000,71.000000,3.000000 27.000000,4.000000,97.000000,60.000000,1834.000000,19.000000,71.000000,2.000000 26.000000,4.000000,91.000000,70.000000,1955.000000,20.500000,71.000000,1.000000 24.000000,4.000000,113.000000,95.000000,2278.000000,15.500000,72.000000,3.000000 25.000000,4.000000,97.500000,80.000000,2126.000000,17.000000,72.000000,1.000000 23.000000,4.000000,97.000000,54.000000,2254.000000,23.500000,72.000000,2.000000 20.000000,4.000000,140.000000,90.000000,2408.000000,19.500000,72.000000,1.000000 21.000000,4.000000,122.000000,86.000000,2226.000000,16.500000,72.000000,1.000000 13.000000,8.000000,350.000000,165.000000,4274.000000,12.000000,72.000000,1.000000 14.000000,8.000000,400.000000,175.000000,4385.000000,12.000000,72.000000,1.000000 15.000000,8.000000,318.000000,150.000000,4135.000000,13.500000,72.000000,1.000000 14.000000,8.000000,351.000000,153.000000,4129.000000,13.000000,72.000000,1.000000 17.000000,8.000000,304.000000,150.000000,3672.000000,11.500000,72.000000,1.000000 11.000000,8.000000,429.000000,208.000000,4633.000000,11.000000,72.000000,1.000000 13.000000,8.000000,350.000000,155.000000,4502.000000,13.500000,72.000000,1.000000 12.000000,8.000000,350.000000,160.000000,4456.000000,13.500000,72.000000,1.000000 13.000000,8.000000,400.000000,190.000000,4422.000000,12.500000,72.000000,1.000000 19.000000,3.000000,70.000000,97.000000,2330.000000,13.500000,72.000000,3.000000 15.000000,8.000000,304.000000,150.000000,3892.000000,12.500000,72.000000,1.000000 13.000000,8.000000,307.000000,130.000000,4098.000000,14.000000,72.000000,1.000000 13.000000,8.000000,302.000000,140.000000,4294.000000,16.000000,72.000000,1.000000 14.000000,8.000000,318.000000,150.000000,4077.000000,14.000000,72.000000,1.000000 18.000000,4.000000,121.000000,112.000000,2933.000000,14.500000,72.000000,2.000000 22.000000,4.000000,121.000000,76.000000,2511.000000,18.000000,72.000000,2.000000 21.000000,4.000000,120.000000,87.000000,2979.000000,19.500000,72.000000,2.000000 26.000000,4.000000,96.000000,69.000000,2189.000000,18.000000,72.000000,2.000000 22.000000,4.000000,122.000000,86.000000,2395.000000,16.000000,72.000000,1.000000 28.000000,4.000000,97.000000,92.000000,2288.000000,17.000000,72.000000,3.000000 23.000000,4.000000,120.000000,97.000000,2506.000000,14.500000,72.000000,3.000000 28.000000,4.000000,98.000000,80.000000,2164.000000,15.000000,72.000000,1.000000 27.000000,4.000000,97.000000,88.000000,2100.000000,16.500000,72.000000,3.000000 13.000000,8.000000,350.000000,175.000000,4100.000000,13.000000,73.000000,1.000000 14.000000,8.000000,304.000000,150.000000,3672.000000,11.500000,73.000000,1.000000 13.000000,8.000000,350.000000,145.000000,3988.000000,13.000000,73.000000,1.000000 14.000000,8.000000,302.000000,137.000000,4042.000000,14.500000,73.000000,1.000000 15.000000,8.000000,318.000000,150.000000,3777.000000,12.500000,73.000000,1.000000 12.000000,8.000000,429.000000,198.000000,4952.000000,11.500000,73.000000,1.000000 13.000000,8.000000,400.000000,150.000000,4464.000000,12.000000,73.000000,1.000000 13.000000,8.000000,351.000000,158.000000,4363.000000,13.000000,73.000000,1.000000 14.000000,8.000000,318.000000,150.000000,4237.000000,14.500000,73.000000,1.000000 13.000000,8.000000,440.000000,215.000000,4735.000000,11.000000,73.000000,1.000000 12.000000,8.000000,455.000000,225.000000,4951.000000,11.000000,73.000000,1.000000 13.000000,8.000000,360.000000,175.000000,3821.000000,11.000000,73.000000,1.000000 18.000000,6.000000,225.000000,105.000000,3121.000000,16.500000,73.000000,1.000000 16.000000,6.000000,250.000000,100.000000,3278.000000,18.000000,73.000000,1.000000 18.000000,6.000000,232.000000,100.000000,2945.000000,16.000000,73.000000,1.000000 18.000000,6.000000,250.000000,88.000000,3021.000000,16.500000,73.000000,1.000000 23.000000,6.000000,198.000000,95.000000,2904.000000,16.000000,73.000000,1.000000 26.000000,4.000000,97.000000,46.000000,1950.000000,21.000000,73.000000,2.000000 11.000000,8.000000,400.000000,150.000000,4997.000000,14.000000,73.000000,1.000000 12.000000,8.000000,400.000000,167.000000,4906.000000,12.500000,73.000000,1.000000 13.000000,8.000000,360.000000,170.000000,4654.000000,13.000000,73.000000,1.000000 12.000000,8.000000,350.000000,180.000000,4499.000000,12.500000,73.000000,1.000000 18.000000,6.000000,232.000000,100.000000,2789.000000,15.000000,73.000000,1.000000 20.000000,4.000000,97.000000,88.000000,2279.000000,19.000000,73.000000,3.000000 21.000000,4.000000,140.000000,72.000000,2401.000000,19.500000,73.000000,1.000000 22.000000,4.000000,108.000000,94.000000,2379.000000,16.500000,73.000000,3.000000 18.000000,3.000000,70.000000,90.000000,2124.000000,13.500000,73.000000,3.000000 19.000000,4.000000,122.000000,85.000000,2310.000000,18.500000,73.000000,1.000000 21.000000,6.000000,155.000000,107.000000,2472.000000,14.000000,73.000000,1.000000 26.000000,4.000000,98.000000,90.000000,2265.000000,15.500000,73.000000,2.000000 15.000000,8.000000,350.000000,145.000000,4082.000000,13.000000,73.000000,1.000000 16.000000,8.000000,400.000000,230.000000,4278.000000,9.500000,73.000000,1.000000 29.000000,4.000000,68.000000,49.000000,1867.000000,19.500000,73.000000,2.000000 24.000000,4.000000,116.000000,75.000000,2158.000000,15.500000,73.000000,2.000000 20.000000,4.000000,114.000000,91.000000,2582.000000,14.000000,73.000000,2.000000 19.000000,4.000000,121.000000,112.000000,2868.000000,15.500000,73.000000,2.000000 15.000000,8.000000,318.000000,150.000000,3399.000000,11.000000,73.000000,1.000000 24.000000,4.000000,121.000000,110.000000,2660.000000,14.000000,73.000000,2.000000 20.000000,6.000000,156.000000,122.000000,2807.000000,13.500000,73.000000,3.000000 11.000000,8.000000,350.000000,180.000000,3664.000000,11.000000,73.000000,1.000000 20.000000,6.000000,198.000000,95.000000,3102.000000,16.500000,74.000000,1.000000 19.000000,6.000000,232.000000,100.000000,2901.000000,16.000000,74.000000,1.000000 15.000000,6.000000,250.000000,100.000000,3336.000000,17.000000,74.000000,1.000000 31.000000,4.000000,79.000000,67.000000,1950.000000,19.000000,74.000000,3.000000 26.000000,4.000000,122.000000,80.000000,2451.000000,16.500000,74.000000,1.000000 32.000000,4.000000,71.000000,65.000000,1836.000000,21.000000,74.000000,3.000000 25.000000,4.000000,140.000000,75.000000,2542.000000,17.000000,74.000000,1.000000 16.000000,6.000000,250.000000,100.000000,3781.000000,17.000000,74.000000,1.000000 16.000000,6.000000,258.000000,110.000000,3632.000000,18.000000,74.000000,1.000000 18.000000,6.000000,225.000000,105.000000,3613.000000,16.500000,74.000000,1.000000 16.000000,8.000000,302.000000,140.000000,4141.000000,14.000000,74.000000,1.000000 13.000000,8.000000,350.000000,150.000000,4699.000000,14.500000,74.000000,1.000000 14.000000,8.000000,318.000000,150.000000,4457.000000,13.500000,74.000000,1.000000 14.000000,8.000000,302.000000,140.000000,4638.000000,16.000000,74.000000,1.000000 14.000000,8.000000,304.000000,150.000000,4257.000000,15.500000,74.000000,1.000000 29.000000,4.000000,98.000000,83.000000,2219.000000,16.500000,74.000000,2.000000 26.000000,4.000000,79.000000,67.000000,1963.000000,15.500000,74.000000,2.000000 26.000000,4.000000,97.000000,78.000000,2300.000000,14.500000,74.000000,2.000000 31.000000,4.000000,76.000000,52.000000,1649.000000,16.500000,74.000000,3.000000 32.000000,4.000000,83.000000,61.000000,2003.000000,19.000000,74.000000,3.000000 28.000000,4.000000,90.000000,75.000000,2125.000000,14.500000,74.000000,1.000000 24.000000,4.000000,90.000000,75.000000,2108.000000,15.500000,74.000000,2.000000 26.000000,4.000000,116.000000,75.000000,2246.000000,14.000000,74.000000,2.000000 24.000000,4.000000,120.000000,97.000000,2489.000000,15.000000,74.000000,3.000000 26.000000,4.000000,108.000000,93.000000,2391.000000,15.500000,74.000000,3.000000 31.000000,4.000000,79.000000,67.000000,2000.000000,16.000000,74.000000,2.000000 19.000000,6.000000,225.000000,95.000000,3264.000000,16.000000,75.000000,1.000000 18.000000,6.000000,250.000000,105.000000,3459.000000,16.000000,75.000000,1.000000 15.000000,6.000000,250.000000,72.000000,3432.000000,21.000000,75.000000,1.000000 15.000000,6.000000,250.000000,72.000000,3158.000000,19.500000,75.000000,1.000000 16.000000,8.000000,400.000000,170.000000,4668.000000,11.500000,75.000000,1.000000 15.000000,8.000000,350.000000,145.000000,4440.000000,14.000000,75.000000,1.000000 16.000000,8.000000,318.000000,150.000000,4498.000000,14.500000,75.000000,1.000000 14.000000,8.000000,351.000000,148.000000,4657.000000,13.500000,75.000000,1.000000 17.000000,6.000000,231.000000,110.000000,3907.000000,21.000000,75.000000,1.000000 16.000000,6.000000,250.000000,105.000000,3897.000000,18.500000,75.000000,1.000000 15.000000,6.000000,258.000000,110.000000,3730.000000,19.000000,75.000000,1.000000 18.000000,6.000000,225.000000,95.000000,3785.000000,19.000000,75.000000,1.000000 21.000000,6.000000,231.000000,110.000000,3039.000000,15.000000,75.000000,1.000000 20.000000,8.000000,262.000000,110.000000,3221.000000,13.500000,75.000000,1.000000 13.000000,8.000000,302.000000,129.000000,3169.000000,12.000000,75.000000,1.000000 29.000000,4.000000,97.000000,75.000000,2171.000000,16.000000,75.000000,3.000000 23.000000,4.000000,140.000000,83.000000,2639.000000,17.000000,75.000000,1.000000 20.000000,6.000000,232.000000,100.000000,2914.000000,16.000000,75.000000,1.000000 23.000000,4.000000,140.000000,78.000000,2592.000000,18.500000,75.000000,1.000000 24.000000,4.000000,134.000000,96.000000,2702.000000,13.500000,75.000000,3.000000 25.000000,4.000000,90.000000,71.000000,2223.000000,16.500000,75.000000,2.000000 24.000000,4.000000,119.000000,97.000000,2545.000000,17.000000,75.000000,3.000000 18.000000,6.000000,171.000000,97.000000,2984.000000,14.500000,75.000000,1.000000 29.000000,4.000000,90.000000,70.000000,1937.000000,14.000000,75.000000,2.000000 19.000000,6.000000,232.000000,90.000000,3211.000000,17.000000,75.000000,1.000000 23.000000,4.000000,115.000000,95.000000,2694.000000,15.000000,75.000000,2.000000 23.000000,4.000000,120.000000,88.000000,2957.000000,17.000000,75.000000,2.000000 22.000000,4.000000,121.000000,98.000000,2945.000000,14.500000,75.000000,2.000000 25.000000,4.000000,121.000000,115.000000,2671.000000,13.500000,75.000000,2.000000 33.000000,4.000000,91.000000,53.000000,1795.000000,17.500000,75.000000,3.000000 28.000000,4.000000,107.000000,86.000000,2464.000000,15.500000,76.000000,2.000000 25.000000,4.000000,116.000000,81.000000,2220.000000,16.900000,76.000000,2.000000 25.000000,4.000000,140.000000,92.000000,2572.000000,14.900000,76.000000,1.000000 26.000000,4.000000,98.000000,79.000000,2255.000000,17.700000,76.000000,1.000000 27.000000,4.000000,101.000000,83.000000,2202.000000,15.300000,76.000000,2.000000 17.500000,8.000000,305.000000,140.000000,4215.000000,13.000000,76.000000,1.000000 16.000000,8.000000,318.000000,150.000000,4190.000000,13.000000,76.000000,1.000000 15.500000,8.000000,304.000000,120.000000,3962.000000,13.900000,76.000000,1.000000 14.500000,8.000000,351.000000,152.000000,4215.000000,12.800000,76.000000,1.000000 22.000000,6.000000,225.000000,100.000000,3233.000000,15.400000,76.000000,1.000000 22.000000,6.000000,250.000000,105.000000,3353.000000,14.500000,76.000000,1.000000 24.000000,6.000000,200.000000,81.000000,3012.000000,17.600000,76.000000,1.000000 22.500000,6.000000,232.000000,90.000000,3085.000000,17.600000,76.000000,1.000000 29.000000,4.000000,85.000000,52.000000,2035.000000,22.200000,76.000000,1.000000 24.500000,4.000000,98.000000,60.000000,2164.000000,22.100000,76.000000,1.000000 29.000000,4.000000,90.000000,70.000000,1937.000000,14.200000,76.000000,2.000000 33.000000,4.000000,91.000000,53.000000,1795.000000,17.400000,76.000000,3.000000 20.000000,6.000000,225.000000,100.000000,3651.000000,17.700000,76.000000,1.000000 18.000000,6.000000,250.000000,78.000000,3574.000000,21.000000,76.000000,1.000000 18.500000,6.000000,250.000000,110.000000,3645.000000,16.200000,76.000000,1.000000 17.500000,6.000000,258.000000,95.000000,3193.000000,17.800000,76.000000,1.000000 29.500000,4.000000,97.000000,71.000000,1825.000000,12.200000,76.000000,2.000000 32.000000,4.000000,85.000000,70.000000,1990.000000,17.000000,76.000000,3.000000 28.000000,4.000000,97.000000,75.000000,2155.000000,16.400000,76.000000,3.000000 26.500000,4.000000,140.000000,72.000000,2565.000000,13.600000,76.000000,1.000000 20.000000,4.000000,130.000000,102.000000,3150.000000,15.700000,76.000000,2.000000 13.000000,8.000000,318.000000,150.000000,3940.000000,13.200000,76.000000,1.000000 19.000000,4.000000,120.000000,88.000000,3270.000000,21.900000,76.000000,2.000000 19.000000,6.000000,156.000000,108.000000,2930.000000,15.500000,76.000000,3.000000 16.500000,6.000000,168.000000,120.000000,3820.000000,16.700000,76.000000,2.000000 16.500000,8.000000,350.000000,180.000000,4380.000000,12.100000,76.000000,1.000000 13.000000,8.000000,350.000000,145.000000,4055.000000,12.000000,76.000000,1.000000 13.000000,8.000000,302.000000,130.000000,3870.000000,15.000000,76.000000,1.000000 13.000000,8.000000,318.000000,150.000000,3755.000000,14.000000,76.000000,1.000000 31.500000,4.000000,98.000000,68.000000,2045.000000,18.500000,77.000000,3.000000 30.000000,4.000000,111.000000,80.000000,2155.000000,14.800000,77.000000,1.000000 36.000000,4.000000,79.000000,58.000000,1825.000000,18.600000,77.000000,2.000000 25.500000,4.000000,122.000000,96.000000,2300.000000,15.500000,77.000000,1.000000 33.500000,4.000000,85.000000,70.000000,1945.000000,16.800000,77.000000,3.000000 17.500000,8.000000,305.000000,145.000000,3880.000000,12.500000,77.000000,1.000000 17.000000,8.000000,260.000000,110.000000,4060.000000,19.000000,77.000000,1.000000 15.500000,8.000000,318.000000,145.000000,4140.000000,13.700000,77.000000,1.000000 15.000000,8.000000,302.000000,130.000000,4295.000000,14.900000,77.000000,1.000000 17.500000,6.000000,250.000000,110.000000,3520.000000,16.400000,77.000000,1.000000 20.500000,6.000000,231.000000,105.000000,3425.000000,16.900000,77.000000,1.000000 19.000000,6.000000,225.000000,100.000000,3630.000000,17.700000,77.000000,1.000000 18.500000,6.000000,250.000000,98.000000,3525.000000,19.000000,77.000000,1.000000 16.000000,8.000000,400.000000,180.000000,4220.000000,11.100000,77.000000,1.000000 15.500000,8.000000,350.000000,170.000000,4165.000000,11.400000,77.000000,1.000000 15.500000,8.000000,400.000000,190.000000,4325.000000,12.200000,77.000000,1.000000 16.000000,8.000000,351.000000,149.000000,4335.000000,14.500000,77.000000,1.000000 29.000000,4.000000,97.000000,78.000000,1940.000000,14.500000,77.000000,2.000000 24.500000,4.000000,151.000000,88.000000,2740.000000,16.000000,77.000000,1.000000 26.000000,4.000000,97.000000,75.000000,2265.000000,18.200000,77.000000,3.000000 25.500000,4.000000,140.000000,89.000000,2755.000000,15.800000,77.000000,1.000000 30.500000,4.000000,98.000000,63.000000,2051.000000,17.000000,77.000000,1.000000 33.500000,4.000000,98.000000,83.000000,2075.000000,15.900000,77.000000,1.000000 30.000000,4.000000,97.000000,67.000000,1985.000000,16.400000,77.000000,3.000000 30.500000,4.000000,97.000000,78.000000,2190.000000,14.100000,77.000000,2.000000 22.000000,6.000000,146.000000,97.000000,2815.000000,14.500000,77.000000,3.000000 21.500000,4.000000,121.000000,110.000000,2600.000000,12.800000,77.000000,2.000000 21.500000,3.000000,80.000000,110.000000,2720.000000,13.500000,77.000000,3.000000 43.100000,4.000000,90.000000,48.000000,1985.000000,21.500000,78.000000,2.000000 36.100000,4.000000,98.000000,66.000000,1800.000000,14.400000,78.000000,1.000000 32.800000,4.000000,78.000000,52.000000,1985.000000,19.400000,78.000000,3.000000 39.400000,4.000000,85.000000,70.000000,2070.000000,18.600000,78.000000,3.000000 36.100000,4.000000,91.000000,60.000000,1800.000000,16.400000,78.000000,3.000000 19.900000,8.000000,260.000000,110.000000,3365.000000,15.500000,78.000000,1.000000
What is the difference between 'regular' linear regression and deep learning linear regression? Assuming that by deep learning you meant more precisely neural networks: a vanilla fully connected feedforward neural network with only linear activation functions will perform linear regression, reg
14,925
What is the difference between 'regular' linear regression and deep learning linear regression?
For regression, which for deep learning is nonlinear in most cases, final layer has 1 neuron with identity function and loss function we optimize is MSE, MAE instead of binary or categorical cross-entropy used for classification.
What is the difference between 'regular' linear regression and deep learning linear regression?
For regression, which for deep learning is nonlinear in most cases, final layer has 1 neuron with identity function and loss function we optimize is MSE, MAE instead of binary or categorical cross-ent
What is the difference between 'regular' linear regression and deep learning linear regression? For regression, which for deep learning is nonlinear in most cases, final layer has 1 neuron with identity function and loss function we optimize is MSE, MAE instead of binary or categorical cross-entropy used for classification.
What is the difference between 'regular' linear regression and deep learning linear regression? For regression, which for deep learning is nonlinear in most cases, final layer has 1 neuron with identity function and loss function we optimize is MSE, MAE instead of binary or categorical cross-ent
14,926
Why P>0.5 cutoff is not "optimal" for logistic regression?
You don't have to get predicted categories from a logistic regression model. It can be fine stay with predicted probabilities. If you do get predicted categories, you should not use that information to do anything other than say 'this observation is best classified into this category'. For example, you should not use 'accuracy' / percent correct to select a model. Having said those things, $.50$ is rarely going to be the optimal cutoff for classifying observations. To get an intuitive sense of how this could happen, imagine that you had $N=100$ with $99$ observations in the positive category. A simple, intercept-only model could easily have $49$ false negatives when you use $.50$ as your cutoff. On the other hand, if you just called everything positive, you would have $1$ false positive, but $99\%$ correct. More generally, logistic regression is trying to fit the true probability positive for observations as a function of explanatory variables. It is not trying to maximize accuracy by centering predicted probabilities around the $.50$ cutoff. If your sample isn't $50\%$ positive, there is just no reason $.50$ would maximize the percent correct.
Why P>0.5 cutoff is not "optimal" for logistic regression?
You don't have to get predicted categories from a logistic regression model. It can be fine stay with predicted probabilities. If you do get predicted categories, you should not use that information
Why P>0.5 cutoff is not "optimal" for logistic regression? You don't have to get predicted categories from a logistic regression model. It can be fine stay with predicted probabilities. If you do get predicted categories, you should not use that information to do anything other than say 'this observation is best classified into this category'. For example, you should not use 'accuracy' / percent correct to select a model. Having said those things, $.50$ is rarely going to be the optimal cutoff for classifying observations. To get an intuitive sense of how this could happen, imagine that you had $N=100$ with $99$ observations in the positive category. A simple, intercept-only model could easily have $49$ false negatives when you use $.50$ as your cutoff. On the other hand, if you just called everything positive, you would have $1$ false positive, but $99\%$ correct. More generally, logistic regression is trying to fit the true probability positive for observations as a function of explanatory variables. It is not trying to maximize accuracy by centering predicted probabilities around the $.50$ cutoff. If your sample isn't $50\%$ positive, there is just no reason $.50$ would maximize the percent correct.
Why P>0.5 cutoff is not "optimal" for logistic regression? You don't have to get predicted categories from a logistic regression model. It can be fine stay with predicted probabilities. If you do get predicted categories, you should not use that information
14,927
Why P>0.5 cutoff is not "optimal" for logistic regression?
I think, it could be because of multiple reasons: There might be non-linearity in your data, so linearly adding the weights, might not always result in correct probabilities Variables are a mix of good predictors and weak predictors, so scored population that is around .5 is because of weak predictors or less effect of strong predictors. As you go above, you get people, for whom the effect of predictors is strong So, you might have to sometime play around with cut-off value, to maximize your desired output like precision,accuracy etc. Because most of the time populations are not very homogeneous.
Why P>0.5 cutoff is not "optimal" for logistic regression?
I think, it could be because of multiple reasons: There might be non-linearity in your data, so linearly adding the weights, might not always result in correct probabilities Variables are a mix of go
Why P>0.5 cutoff is not "optimal" for logistic regression? I think, it could be because of multiple reasons: There might be non-linearity in your data, so linearly adding the weights, might not always result in correct probabilities Variables are a mix of good predictors and weak predictors, so scored population that is around .5 is because of weak predictors or less effect of strong predictors. As you go above, you get people, for whom the effect of predictors is strong So, you might have to sometime play around with cut-off value, to maximize your desired output like precision,accuracy etc. Because most of the time populations are not very homogeneous.
Why P>0.5 cutoff is not "optimal" for logistic regression? I think, it could be because of multiple reasons: There might be non-linearity in your data, so linearly adding the weights, might not always result in correct probabilities Variables are a mix of go
14,928
Difference between multilevel modelling and mixed effects models?
Section 2.2.2.1 from lme4 book Because each level of sample occurs with one and only one level of batch we say that sample is nested within batch. Some presentations of mixed-effects models, especially those related to multilevel modeling˜[Rasbash et˜al., 2000] or hierarchical linear models˜[Raudenbush and Bryk, 2002], leave the impression that one can only define random effects with respect to factors that are nested. This is the origin of the terms “multilevel”, referring to multiple, nested levels of variability, and “hierarchical”, also invoking the concept of a hierarchy of levels. To be fair, both those references do describe the use of models with random effects associated with non-nested factors, but such models tend to be treated as a special case. The blurring of mixed-effects models with the concept of multiple, hierarchical levels of variation results in an unwarranted emphasis on “levels” when defining a model and leads to considerable confusion. It is perfectly legitimate to define models having random effects associated with non-nested factors. The reasons for the emphasis on defining random effects with respect to nested factors only are that such cases do occur frequently in practice and that some of the computational methods for estimating the parameters in the models can only be easily applied to nested factors
Difference between multilevel modelling and mixed effects models?
Section 2.2.2.1 from lme4 book Because each level of sample occurs with one and only one level of batch we say that sample is nested within batch. Some presentations of mixed-effects models, espe
Difference between multilevel modelling and mixed effects models? Section 2.2.2.1 from lme4 book Because each level of sample occurs with one and only one level of batch we say that sample is nested within batch. Some presentations of mixed-effects models, especially those related to multilevel modeling˜[Rasbash et˜al., 2000] or hierarchical linear models˜[Raudenbush and Bryk, 2002], leave the impression that one can only define random effects with respect to factors that are nested. This is the origin of the terms “multilevel”, referring to multiple, nested levels of variability, and “hierarchical”, also invoking the concept of a hierarchy of levels. To be fair, both those references do describe the use of models with random effects associated with non-nested factors, but such models tend to be treated as a special case. The blurring of mixed-effects models with the concept of multiple, hierarchical levels of variation results in an unwarranted emphasis on “levels” when defining a model and leads to considerable confusion. It is perfectly legitimate to define models having random effects associated with non-nested factors. The reasons for the emphasis on defining random effects with respect to nested factors only are that such cases do occur frequently in practice and that some of the computational methods for estimating the parameters in the models can only be easily applied to nested factors
Difference between multilevel modelling and mixed effects models? Section 2.2.2.1 from lme4 book Because each level of sample occurs with one and only one level of batch we say that sample is nested within batch. Some presentations of mixed-effects models, espe
14,929
do logs modify the correlation between two variables?
There are multiple different types of correlation. The most common one is Pearson's correlation coefficient, which measures the amount of linear dependence between two vectors. That is, it essentially lays a straight line through the scatterplot and calculates its slope. This will of course change if you take logs! If you are interested in a measure of correlation that is invariant under monotone transformations like the logarithm, use Kendall's rank correlation or Spearman's rank correlation. These only work on ranks, which do not change under monotone transformations. Here is an example - note how the Pearson correlation changes after logging, while the Kendall and the Spearman ones don't: > set.seed(1) > foo <- exp(rnorm(100)) > bar <- exp(rnorm(100)) > > cor(foo,bar,method="pearson") [1] -0.08337386 > cor(log(foo),log(bar),method="pearson") [1] -0.0009943199 > > cor(foo,bar,method="kendall") [1] 0.02707071 > cor(log(foo),log(bar),method="kendall") [1] 0.02707071 > > cor(foo,bar,method="spearman") [1] 0.03871587 > cor(log(foo),log(bar),method="spearman") [1] 0.03871587 The following earlier question discusses Kendall's and Spearman's correlation: Kendall Tau or Spearman's rho?
do logs modify the correlation between two variables?
There are multiple different types of correlation. The most common one is Pearson's correlation coefficient, which measures the amount of linear dependence between two vectors. That is, it essentially
do logs modify the correlation between two variables? There are multiple different types of correlation. The most common one is Pearson's correlation coefficient, which measures the amount of linear dependence between two vectors. That is, it essentially lays a straight line through the scatterplot and calculates its slope. This will of course change if you take logs! If you are interested in a measure of correlation that is invariant under monotone transformations like the logarithm, use Kendall's rank correlation or Spearman's rank correlation. These only work on ranks, which do not change under monotone transformations. Here is an example - note how the Pearson correlation changes after logging, while the Kendall and the Spearman ones don't: > set.seed(1) > foo <- exp(rnorm(100)) > bar <- exp(rnorm(100)) > > cor(foo,bar,method="pearson") [1] -0.08337386 > cor(log(foo),log(bar),method="pearson") [1] -0.0009943199 > > cor(foo,bar,method="kendall") [1] 0.02707071 > cor(log(foo),log(bar),method="kendall") [1] 0.02707071 > > cor(foo,bar,method="spearman") [1] 0.03871587 > cor(log(foo),log(bar),method="spearman") [1] 0.03871587 The following earlier question discusses Kendall's and Spearman's correlation: Kendall Tau or Spearman's rho?
do logs modify the correlation between two variables? There are multiple different types of correlation. The most common one is Pearson's correlation coefficient, which measures the amount of linear dependence between two vectors. That is, it essentially
14,930
What does the convolution step in a Convolutional Neural Network do?
I'll first try to share some intuition behind CNN and then comment the particular topics you listed. The convolution and sub-sampling layers in a CNN are not different from the hidden layers in a common MLP, i. e. their function is to extract features from their input. These features are then given to the next hidden layer to extract still more complex features, or are directly given to a standard classifier to output the final prediction (usually a Softmax, but also SVM or any other can be used). In the context of image recognition, these features are images treats, like stroke patterns in the lower layers and object parts in the upper layers. In natural images these features tend to be the same at all locations. Recognizing a certain stroke pattern in the middle of the images will be as useful as recognizing it close to the borders. So why don't we replicate the hidden layers and connect multiple copies of it in all regions of the input image, so the same features can be detected anywhere? It's exactly what a CNN does, but in a efficient way. After the replication (the "convolution" step) we add a sub-sample step, which can be implemented in many ways, but is nothing more than a sub-sample. In theory this step could be even removed, but in practice it's essential in order to allow the problem remain tractable. Thus: Correct. As explained above, hidden layers of a CNN are feature extractors as in a regular MLP. The alternated convolution and sub-sampling steps are done during the training and classification, so they are not something done "before" the actual processing. I wouldn't call them "pre-processing", the same way the hidden layers of a MLP is not called so. Correct. A good image which helps to understand the convolution is CNN page in the ULFDL tutorial. Think of a hidden layer with a single neuron which is trained to extract features from $3 \times 3$ patches. If we convolve this single learned feature over a $5 \times 5$ image, this process can be represented by the following gif: In this example we were using a single neuron in our feature extraction layer, and we generated $9$ convolved features. If we had a larger number of units in the hidden layer, it would be clear why the sub-sampling step after this is required. The subsequent convolution and sub-sampling steps are based in the same principle, but computed over features extracted in the previous layer, instead of the raw pixels of the original image.
What does the convolution step in a Convolutional Neural Network do?
I'll first try to share some intuition behind CNN and then comment the particular topics you listed. The convolution and sub-sampling layers in a CNN are not different from the hidden layers in a comm
What does the convolution step in a Convolutional Neural Network do? I'll first try to share some intuition behind CNN and then comment the particular topics you listed. The convolution and sub-sampling layers in a CNN are not different from the hidden layers in a common MLP, i. e. their function is to extract features from their input. These features are then given to the next hidden layer to extract still more complex features, or are directly given to a standard classifier to output the final prediction (usually a Softmax, but also SVM or any other can be used). In the context of image recognition, these features are images treats, like stroke patterns in the lower layers and object parts in the upper layers. In natural images these features tend to be the same at all locations. Recognizing a certain stroke pattern in the middle of the images will be as useful as recognizing it close to the borders. So why don't we replicate the hidden layers and connect multiple copies of it in all regions of the input image, so the same features can be detected anywhere? It's exactly what a CNN does, but in a efficient way. After the replication (the "convolution" step) we add a sub-sample step, which can be implemented in many ways, but is nothing more than a sub-sample. In theory this step could be even removed, but in practice it's essential in order to allow the problem remain tractable. Thus: Correct. As explained above, hidden layers of a CNN are feature extractors as in a regular MLP. The alternated convolution and sub-sampling steps are done during the training and classification, so they are not something done "before" the actual processing. I wouldn't call them "pre-processing", the same way the hidden layers of a MLP is not called so. Correct. A good image which helps to understand the convolution is CNN page in the ULFDL tutorial. Think of a hidden layer with a single neuron which is trained to extract features from $3 \times 3$ patches. If we convolve this single learned feature over a $5 \times 5$ image, this process can be represented by the following gif: In this example we were using a single neuron in our feature extraction layer, and we generated $9$ convolved features. If we had a larger number of units in the hidden layer, it would be clear why the sub-sampling step after this is required. The subsequent convolution and sub-sampling steps are based in the same principle, but computed over features extracted in the previous layer, instead of the raw pixels of the original image.
What does the convolution step in a Convolutional Neural Network do? I'll first try to share some intuition behind CNN and then comment the particular topics you listed. The convolution and sub-sampling layers in a CNN are not different from the hidden layers in a comm
14,931
What does the convolution step in a Convolutional Neural Network do?
I have no idea what you mean by "why the first convolution step works." In order for a CNN to be successful it needs to have many layers. One of the fundamental ideas behind CNN and many other deep learning approaches is that larger signals can be identified by the spatial correlation of their smaller parts which can be sparsely represented. In other words, images might look complex but they are made from a combination of just a few basic parts. For computer vision, the baseline structure in images is usually composed of edges and corners. CNN try to exploit the sparseness of the structure in an image by looking for common localized structures. That is what the first layer of the CNN is trying to determine. Think of a convolution as a match filter that is looking for signals that match a specific template. How well it works depends on the data at hand. Fortunately the world is full of repetition on a small scale, so CNN works well for computer vision tasks.
What does the convolution step in a Convolutional Neural Network do?
I have no idea what you mean by "why the first convolution step works." In order for a CNN to be successful it needs to have many layers. One of the fundamental ideas behind CNN and many other deep
What does the convolution step in a Convolutional Neural Network do? I have no idea what you mean by "why the first convolution step works." In order for a CNN to be successful it needs to have many layers. One of the fundamental ideas behind CNN and many other deep learning approaches is that larger signals can be identified by the spatial correlation of their smaller parts which can be sparsely represented. In other words, images might look complex but they are made from a combination of just a few basic parts. For computer vision, the baseline structure in images is usually composed of edges and corners. CNN try to exploit the sparseness of the structure in an image by looking for common localized structures. That is what the first layer of the CNN is trying to determine. Think of a convolution as a match filter that is looking for signals that match a specific template. How well it works depends on the data at hand. Fortunately the world is full of repetition on a small scale, so CNN works well for computer vision tasks.
What does the convolution step in a Convolutional Neural Network do? I have no idea what you mean by "why the first convolution step works." In order for a CNN to be successful it needs to have many layers. One of the fundamental ideas behind CNN and many other deep
14,932
Why is controlling FDR less stringent than controlling FWER?
Indeed, @cardinal is quite right that the paper is as clear as it gets. So, for what it's worth, in case you do not have access to the paper, here's a slightly elaborated version of how Benjamini–Hochberg argue: The FDR $Q_e$ is the expected value of the proportion of false rejections $v$ to all rejections $r$. Now, $r$ is, obviously, the sum of false and correct rejections; call the latter $s$. In summary, (using capital letters for random variables and lowercase letters for realized values), $$Q_e=E\left(\frac{V}{R}\right)=E\left(\frac{V}{V+S}\right)=:E\left(Q\right).$$ One takes $Q=0$ if $R=0$. Now, there are two possibilities: either all $m$ nulls are true or just $m_0<m$ of them are true. In the first case, there cannot be correct rejections, so $r=v$. Thus, if there are any rejections ($r\geq 1$), $q=1$, otherwise $q=0$. Hence, $$\newcommand{\FDR}{\mathrm{FDR}}\newcommand{\FWER}{\mathrm{FWER}}\FDR=E(Q)=1\cdot P(Q=1)+0\cdot P(Q=0)=P(Q=1)=P(V \geq 1)=\FWER$$ So, $\FDR=\FWER$ in this case, such that any procedure that controls the $\FDR$ trivially also controls the $\FWER$ and vice versa. In the second case in which $m_0<m$, if $v>0$ (so if there is at least one false rejection), we obviously have (this being a fraction with also $v$ in the denominator) that $v/r\leq 1$. This implies that the indicator function that takes the value 1 if there is at least one false rejection, $\mathbf 1_{V\geq 1}$ will never be less than $Q$, $\mathbf 1_{V\geq 1}\geq Q$. Now, take expectation on either side of the inequality, which by monotonicity of $E$ leaves the inequality intact, $$E(\mathbf 1_{V\geq 1})\geq E(Q)=\FDR$$ The expected value of an indicator function being the probability of the event in the indicator, we have $E(\mathbf 1_{V\geq 1})=P(V\geq 1)$, which again is the $\FWER$. Thus, when we have a procedure that controls the $\FWER$ in the sense that $\FWER\leq \alpha$, we must have that $\FDR\leq\alpha$. Conversely, having $\FDR$ control at some $\alpha$ may come with a substantially larger $\FWER$. Intuitively, accepting a nonzero expected fraction of false rejections ($\FDR$) out of a potentially large total of hypotheses tested may imply a very high probability of at least one false rejection ($\FWER$). So, a procedure has to be less strict when only $\FDR$ control is desired, which is also good for power. This is the same idea as in any basic hypothesis test: when you test at the 5% level you reject more frequently (both correct and false nulls) than when testing at the 1% level simply because you have a smaller critical value.
Why is controlling FDR less stringent than controlling FWER?
Indeed, @cardinal is quite right that the paper is as clear as it gets. So, for what it's worth, in case you do not have access to the paper, here's a slightly elaborated version of how Benjamini–Hoch
Why is controlling FDR less stringent than controlling FWER? Indeed, @cardinal is quite right that the paper is as clear as it gets. So, for what it's worth, in case you do not have access to the paper, here's a slightly elaborated version of how Benjamini–Hochberg argue: The FDR $Q_e$ is the expected value of the proportion of false rejections $v$ to all rejections $r$. Now, $r$ is, obviously, the sum of false and correct rejections; call the latter $s$. In summary, (using capital letters for random variables and lowercase letters for realized values), $$Q_e=E\left(\frac{V}{R}\right)=E\left(\frac{V}{V+S}\right)=:E\left(Q\right).$$ One takes $Q=0$ if $R=0$. Now, there are two possibilities: either all $m$ nulls are true or just $m_0<m$ of them are true. In the first case, there cannot be correct rejections, so $r=v$. Thus, if there are any rejections ($r\geq 1$), $q=1$, otherwise $q=0$. Hence, $$\newcommand{\FDR}{\mathrm{FDR}}\newcommand{\FWER}{\mathrm{FWER}}\FDR=E(Q)=1\cdot P(Q=1)+0\cdot P(Q=0)=P(Q=1)=P(V \geq 1)=\FWER$$ So, $\FDR=\FWER$ in this case, such that any procedure that controls the $\FDR$ trivially also controls the $\FWER$ and vice versa. In the second case in which $m_0<m$, if $v>0$ (so if there is at least one false rejection), we obviously have (this being a fraction with also $v$ in the denominator) that $v/r\leq 1$. This implies that the indicator function that takes the value 1 if there is at least one false rejection, $\mathbf 1_{V\geq 1}$ will never be less than $Q$, $\mathbf 1_{V\geq 1}\geq Q$. Now, take expectation on either side of the inequality, which by monotonicity of $E$ leaves the inequality intact, $$E(\mathbf 1_{V\geq 1})\geq E(Q)=\FDR$$ The expected value of an indicator function being the probability of the event in the indicator, we have $E(\mathbf 1_{V\geq 1})=P(V\geq 1)$, which again is the $\FWER$. Thus, when we have a procedure that controls the $\FWER$ in the sense that $\FWER\leq \alpha$, we must have that $\FDR\leq\alpha$. Conversely, having $\FDR$ control at some $\alpha$ may come with a substantially larger $\FWER$. Intuitively, accepting a nonzero expected fraction of false rejections ($\FDR$) out of a potentially large total of hypotheses tested may imply a very high probability of at least one false rejection ($\FWER$). So, a procedure has to be less strict when only $\FDR$ control is desired, which is also good for power. This is the same idea as in any basic hypothesis test: when you test at the 5% level you reject more frequently (both correct and false nulls) than when testing at the 1% level simply because you have a smaller critical value.
Why is controlling FDR less stringent than controlling FWER? Indeed, @cardinal is quite right that the paper is as clear as it gets. So, for what it's worth, in case you do not have access to the paper, here's a slightly elaborated version of how Benjamini–Hoch
14,933
Why use Platt's scaling?
I suggest to check out the wikipedia page of logistic regression. It states that in case of a binary dependent variable logistic regression maps the predictors to the probability of occurrence of the dependent variable. Without any transformation, the probability used for training the model is either 1 (if y is positive in the training set) or 0 (if y is negative). So: Instead of using the absolute values 1 for positive class and 0 for negative class when fitting $p_i=\frac{1}{(1+exp(A*f_i+B))}$ (where $f_i$ is the uncalibrated output of the SVM), Platt suggests to use the mentioned transformation to allow the opposite label to appear with some probability. In this way some regularization is introduced. When the size of the dataset reaches infinity, $y_+$ will become 1 and $y_{-}$ will become zero. For details, see the original paper of Platt.
Why use Platt's scaling?
I suggest to check out the wikipedia page of logistic regression. It states that in case of a binary dependent variable logistic regression maps the predictors to the probability of occurrence of the
Why use Platt's scaling? I suggest to check out the wikipedia page of logistic regression. It states that in case of a binary dependent variable logistic regression maps the predictors to the probability of occurrence of the dependent variable. Without any transformation, the probability used for training the model is either 1 (if y is positive in the training set) or 0 (if y is negative). So: Instead of using the absolute values 1 for positive class and 0 for negative class when fitting $p_i=\frac{1}{(1+exp(A*f_i+B))}$ (where $f_i$ is the uncalibrated output of the SVM), Platt suggests to use the mentioned transformation to allow the opposite label to appear with some probability. In this way some regularization is introduced. When the size of the dataset reaches infinity, $y_+$ will become 1 and $y_{-}$ will become zero. For details, see the original paper of Platt.
Why use Platt's scaling? I suggest to check out the wikipedia page of logistic regression. It states that in case of a binary dependent variable logistic regression maps the predictors to the probability of occurrence of the
14,934
Why use Platt's scaling?
Another method of avoiding over-fitting that I have found useful is to fit the univariate logistic regression model to the leave-out-out cross-validation output of the SVM, which can be approximated efficiently using the Span bound. However, if you want a classifier that produces estimates of the probability of class membership, then you would be better off using kernel logistic regression, which aims to do that directly. The ouput of the SVM is designed for discrete classification and doesn't necessarily contain the information required for accurate estimation of probabilities away from the p=0.5 contour. Gaussian process classifiers are another good option if you want a kernel based probabilistic classifier.
Why use Platt's scaling?
Another method of avoiding over-fitting that I have found useful is to fit the univariate logistic regression model to the leave-out-out cross-validation output of the SVM, which can be approximated e
Why use Platt's scaling? Another method of avoiding over-fitting that I have found useful is to fit the univariate logistic regression model to the leave-out-out cross-validation output of the SVM, which can be approximated efficiently using the Span bound. However, if you want a classifier that produces estimates of the probability of class membership, then you would be better off using kernel logistic regression, which aims to do that directly. The ouput of the SVM is designed for discrete classification and doesn't necessarily contain the information required for accurate estimation of probabilities away from the p=0.5 contour. Gaussian process classifiers are another good option if you want a kernel based probabilistic classifier.
Why use Platt's scaling? Another method of avoiding over-fitting that I have found useful is to fit the univariate logistic regression model to the leave-out-out cross-validation output of the SVM, which can be approximated e
14,935
How is causation defined mathematically?
What is the mathematical definition of a causal relationship between two random variables? Mathematically, a causal model consists of functional relationships between variables. For instance, consider the system of structural equations below: $$ x = f_x(\epsilon_{x})\\ y = f_y(x, \epsilon_{y}) $$ This means that $x$ functionally determines the value of $y$ (if you intervene on $x$ this changes the values of $y$) but not the other way around. Graphically, this is usually represented by $x \rightarrow y$, which means that $x$ enters the structural equation of y. As an addendum, you can also express a causal model in terms of joint distributions of counterfactual variables, which is mathematically equivalent to functional models. Given a sample from the joint distribution of two random variables X and Y, when would we say X causes Y? Sometimes (or most of the times) you do not have knowledge about the shape of the structural equations $f_{x}$, $f_y$, nor even whether $x\rightarrow y$ or $y \rightarrow x$. The only information you have is the joint probability distribution $p(y,x)$ (or samples from this distribution). This leads to your question: when can I recover the direction of causality just from the data? Or, more precisely, when can I recover whether $x$ enters the structural equation of $y$ or vice-versa, just from the data? Of course, without any fundamentally untestable assumptions about the causal model, this is impossible. The problem is that several different causal models can entail the same joint probability distribution of observed variables. The most common example is a causal linear system with gaussian noise. But under some causal assumptions, this might be possible---and this is what the causal discovery literature works on. If you have no prior exposure to this topic, you might want to start from Elements of Causal Inference by Peters, Janzing and Scholkopf, as well as chapter 2 from Causality by Judea Pearl. We have a topic here on CV for references on causal discovery, but we don't have that many references listed there yet. Therefore, there isn't just one answer to your question, since it depends on the assumptions one makes. The paper you mention cites some examples, such as assuming a linear model with non-gaussian noise. This case is known as LINGAN (short for linear non-gaussian acyclic model), here is an example in R: library(pcalg) set.seed(1234) n <- 500 eps1 <- sign(rnorm(n)) * sqrt(abs(rnorm(n))) eps2 <- runif(n) - 0.5 x2 <- 3 + eps2 x1 <- 0.9*x2 + 7 + eps1 # runs lingam X <- cbind(x1, x2) res <- lingam(X) as(res, "amat") # Adjacency Matrix 'amat' (2 x 2) of type ‘pag’: # [,1] [,2] # [1,] . . # [2,] TRUE . Notice here we have a linear causal model with non-gaussian noise where $x_2$ causes $x_1$ and lingam correctly recovers the causal direction. However, notice this depends critically on the LINGAM assumptions. For the case of the paper you cite, they make this specific assumption (see their "postulate"): If $x\rightarrow y$ , the minimal description length of the mechanism mapping X to Y is independent of the value of X, whereas the minimal description length of the mechanism mapping Y to X is dependent on the value of Y. Note this is an assumption. This is what we would call their "identification condition". Essentially, the postulate imposes restrictions on the joint distribution $p(x,y)$. That is, the postulate says that if $x \rightarrow y$ certain restrictions holds in the data, and if $y \rightarrow x$ other restrictions hold. These types of restrictions that have testable implications (impose constraints on $p(y,x)$) is what allows one to recover directionally from observational data. As a final remark, causal discovery results are still very limited, and depend on strong assumptions, be careful when applying these on real world context.
How is causation defined mathematically?
What is the mathematical definition of a causal relationship between two random variables? Mathematically, a causal model consists of functional relationships between variables. For instance, consi
How is causation defined mathematically? What is the mathematical definition of a causal relationship between two random variables? Mathematically, a causal model consists of functional relationships between variables. For instance, consider the system of structural equations below: $$ x = f_x(\epsilon_{x})\\ y = f_y(x, \epsilon_{y}) $$ This means that $x$ functionally determines the value of $y$ (if you intervene on $x$ this changes the values of $y$) but not the other way around. Graphically, this is usually represented by $x \rightarrow y$, which means that $x$ enters the structural equation of y. As an addendum, you can also express a causal model in terms of joint distributions of counterfactual variables, which is mathematically equivalent to functional models. Given a sample from the joint distribution of two random variables X and Y, when would we say X causes Y? Sometimes (or most of the times) you do not have knowledge about the shape of the structural equations $f_{x}$, $f_y$, nor even whether $x\rightarrow y$ or $y \rightarrow x$. The only information you have is the joint probability distribution $p(y,x)$ (or samples from this distribution). This leads to your question: when can I recover the direction of causality just from the data? Or, more precisely, when can I recover whether $x$ enters the structural equation of $y$ or vice-versa, just from the data? Of course, without any fundamentally untestable assumptions about the causal model, this is impossible. The problem is that several different causal models can entail the same joint probability distribution of observed variables. The most common example is a causal linear system with gaussian noise. But under some causal assumptions, this might be possible---and this is what the causal discovery literature works on. If you have no prior exposure to this topic, you might want to start from Elements of Causal Inference by Peters, Janzing and Scholkopf, as well as chapter 2 from Causality by Judea Pearl. We have a topic here on CV for references on causal discovery, but we don't have that many references listed there yet. Therefore, there isn't just one answer to your question, since it depends on the assumptions one makes. The paper you mention cites some examples, such as assuming a linear model with non-gaussian noise. This case is known as LINGAN (short for linear non-gaussian acyclic model), here is an example in R: library(pcalg) set.seed(1234) n <- 500 eps1 <- sign(rnorm(n)) * sqrt(abs(rnorm(n))) eps2 <- runif(n) - 0.5 x2 <- 3 + eps2 x1 <- 0.9*x2 + 7 + eps1 # runs lingam X <- cbind(x1, x2) res <- lingam(X) as(res, "amat") # Adjacency Matrix 'amat' (2 x 2) of type ‘pag’: # [,1] [,2] # [1,] . . # [2,] TRUE . Notice here we have a linear causal model with non-gaussian noise where $x_2$ causes $x_1$ and lingam correctly recovers the causal direction. However, notice this depends critically on the LINGAM assumptions. For the case of the paper you cite, they make this specific assumption (see their "postulate"): If $x\rightarrow y$ , the minimal description length of the mechanism mapping X to Y is independent of the value of X, whereas the minimal description length of the mechanism mapping Y to X is dependent on the value of Y. Note this is an assumption. This is what we would call their "identification condition". Essentially, the postulate imposes restrictions on the joint distribution $p(x,y)$. That is, the postulate says that if $x \rightarrow y$ certain restrictions holds in the data, and if $y \rightarrow x$ other restrictions hold. These types of restrictions that have testable implications (impose constraints on $p(y,x)$) is what allows one to recover directionally from observational data. As a final remark, causal discovery results are still very limited, and depend on strong assumptions, be careful when applying these on real world context.
How is causation defined mathematically? What is the mathematical definition of a causal relationship between two random variables? Mathematically, a causal model consists of functional relationships between variables. For instance, consi
14,936
How is causation defined mathematically?
There are a variety of approaches to formalizing causality (which is in keeping with substantial philosophical disagreement about causality that has been around for centuries). A popular one is in terms of potential outcomes. The potential-outcomes approach, called the Rubin causal model, supposes that for each causal state of affairs, there's a different random variable. So, $Y_1$ might be the random variable of possible outcomes from a clinical trial if a subject takes the study drug, and $Y_2$ might be the random variable if he takes the placebo. The causal effect is the difference between $Y_1$ and $Y_2$. If in fact $Y_1 = Y_2$, we could say that the treatment has no effect. Otherwise, we could say that the treatment condition causes the outcome. Causal relationships between variables can also be represented with directional acylical graphs, which have a very different flavor but turn out to be mathematically equivalent to the Rubin model (Wasserman, 2004, section 17.8). Wasserman, L. (2004). All of statistics: A concise course in statistical inference. New York, NY: Springer. ISBN 978-0-387-40272-7.
How is causation defined mathematically?
There are a variety of approaches to formalizing causality (which is in keeping with substantial philosophical disagreement about causality that has been around for centuries). A popular one is in ter
How is causation defined mathematically? There are a variety of approaches to formalizing causality (which is in keeping with substantial philosophical disagreement about causality that has been around for centuries). A popular one is in terms of potential outcomes. The potential-outcomes approach, called the Rubin causal model, supposes that for each causal state of affairs, there's a different random variable. So, $Y_1$ might be the random variable of possible outcomes from a clinical trial if a subject takes the study drug, and $Y_2$ might be the random variable if he takes the placebo. The causal effect is the difference between $Y_1$ and $Y_2$. If in fact $Y_1 = Y_2$, we could say that the treatment has no effect. Otherwise, we could say that the treatment condition causes the outcome. Causal relationships between variables can also be represented with directional acylical graphs, which have a very different flavor but turn out to be mathematically equivalent to the Rubin model (Wasserman, 2004, section 17.8). Wasserman, L. (2004). All of statistics: A concise course in statistical inference. New York, NY: Springer. ISBN 978-0-387-40272-7.
How is causation defined mathematically? There are a variety of approaches to formalizing causality (which is in keeping with substantial philosophical disagreement about causality that has been around for centuries). A popular one is in ter
14,937
How is causation defined mathematically?
There are two ways to determine whether $X$ is the cause of $Y$. The first is standard while the second is my own claim. There exists an intervention on $X$ such that the value of $Y$ is changed An intervention is a surgical change to a variable that does not affect variables it depends on. Interventions have been formalized rigorously in structural equations and causal graphical models, but as far as I know, there is no definition which is independent of a particular model class. The simulation of $Y$ requires the simulation of $X$ To make this rigorous requires formalizing a model over $X$ and $Y$, and in particular the semantics which define how it is simulated. In modern approaches to causation, intervention is taken as the primitive object which defines causal relationships (definition 1). In my opinion, however, intervention is a reflection of, and necessarily consistent with simulation dynamics.
How is causation defined mathematically?
There are two ways to determine whether $X$ is the cause of $Y$. The first is standard while the second is my own claim. There exists an intervention on $X$ such that the value of $Y$ is changed An
How is causation defined mathematically? There are two ways to determine whether $X$ is the cause of $Y$. The first is standard while the second is my own claim. There exists an intervention on $X$ such that the value of $Y$ is changed An intervention is a surgical change to a variable that does not affect variables it depends on. Interventions have been formalized rigorously in structural equations and causal graphical models, but as far as I know, there is no definition which is independent of a particular model class. The simulation of $Y$ requires the simulation of $X$ To make this rigorous requires formalizing a model over $X$ and $Y$, and in particular the semantics which define how it is simulated. In modern approaches to causation, intervention is taken as the primitive object which defines causal relationships (definition 1). In my opinion, however, intervention is a reflection of, and necessarily consistent with simulation dynamics.
How is causation defined mathematically? There are two ways to determine whether $X$ is the cause of $Y$. The first is standard while the second is my own claim. There exists an intervention on $X$ such that the value of $Y$ is changed An
14,938
logloss vs gini/auc
Whereas the AUC is computed with regards to binary classification with a varying decision threshold, logloss actually takes "certainty" of classification into account. Therefore to my understanding, logloss conceptually goes beyond AUC and is especially relevant in cases with imbalanced data or in case of unequally distributed error cost (for example detection of a deadly disease). In addition to this very basic answer, you might want to have a look at optimizing auc vs logloss in binary classification problems A simple example of logloss computation and the underlying concept is discussed in this recent question Log Loss function in scikit-learn returns different values In addition, a very good point has been made in stackoverflow One must understand crucial difference between AUC ROC and "point-wise" metrics like accuracy/precision etc. ROC is a function of a threshold. Given a model (classifier) that outputs the probability of belonging to each class we usually classify element to the class with the highest support. However, sometimes we can get better scores by changing this rule and requiring one support to be 2 times bigger than the other to actually classify as a given class. This is often true for imbalanced datasets. This way you are actually modifing the learned prior of classes to better fit your data. ROC looks at "what would happen if I change this threshold to all possible values" and then AUC ROC computes the integral of such a curve.
logloss vs gini/auc
Whereas the AUC is computed with regards to binary classification with a varying decision threshold, logloss actually takes "certainty" of classification into account. Therefore to my understanding,
logloss vs gini/auc Whereas the AUC is computed with regards to binary classification with a varying decision threshold, logloss actually takes "certainty" of classification into account. Therefore to my understanding, logloss conceptually goes beyond AUC and is especially relevant in cases with imbalanced data or in case of unequally distributed error cost (for example detection of a deadly disease). In addition to this very basic answer, you might want to have a look at optimizing auc vs logloss in binary classification problems A simple example of logloss computation and the underlying concept is discussed in this recent question Log Loss function in scikit-learn returns different values In addition, a very good point has been made in stackoverflow One must understand crucial difference between AUC ROC and "point-wise" metrics like accuracy/precision etc. ROC is a function of a threshold. Given a model (classifier) that outputs the probability of belonging to each class we usually classify element to the class with the highest support. However, sometimes we can get better scores by changing this rule and requiring one support to be 2 times bigger than the other to actually classify as a given class. This is often true for imbalanced datasets. This way you are actually modifing the learned prior of classes to better fit your data. ROC looks at "what would happen if I change this threshold to all possible values" and then AUC ROC computes the integral of such a curve.
logloss vs gini/auc Whereas the AUC is computed with regards to binary classification with a varying decision threshold, logloss actually takes "certainty" of classification into account. Therefore to my understanding,
14,939
Is the sample correlation coefficient an unbiased estimator of the population correlation coefficient?
This is not an easy question but some expressions are available. If you are talking about the Normal distribution in particular, then the answer is NO! We have $$\mathbb{E} \widehat{\rho} = \rho \left[1 - \frac{\left(1-\rho^2 \right)}{2n} + O\left( \frac{1}{n^2} \right) \right]$$ as seen in Chapter 2 of Lehmann's Theory of Point Estimation. There are infinitely many terms in the expression above but we are essentially considering terms of equal or lower order than $n^{-2}$ negligible. This formula shows that the sample correlation coefficient is only unbiased for $\rho = 0$, i.e. independence, as one would expect. It is also unbiased for the degenerate cases with $|\rho| = 1$, but that is not very interesting. In general cases the bias will be of order $\frac{1}{n}$ but quite small for all reasonable sample sizes. In Normal distributions the sample correlation coefficient is the mle, which means that it is asymptotically unbiased. You can also see that from the above formula as $\mathbb{E} \widehat{\rho} \to \rho$. Note that this already follows from the boundedness and the consistency of the sample correlation coefficient through the bounded convergence theorem.
Is the sample correlation coefficient an unbiased estimator of the population correlation coefficien
This is not an easy question but some expressions are available. If you are talking about the Normal distribution in particular, then the answer is NO! We have $$\mathbb{E} \widehat{\rho} = \rho \left
Is the sample correlation coefficient an unbiased estimator of the population correlation coefficient? This is not an easy question but some expressions are available. If you are talking about the Normal distribution in particular, then the answer is NO! We have $$\mathbb{E} \widehat{\rho} = \rho \left[1 - \frac{\left(1-\rho^2 \right)}{2n} + O\left( \frac{1}{n^2} \right) \right]$$ as seen in Chapter 2 of Lehmann's Theory of Point Estimation. There are infinitely many terms in the expression above but we are essentially considering terms of equal or lower order than $n^{-2}$ negligible. This formula shows that the sample correlation coefficient is only unbiased for $\rho = 0$, i.e. independence, as one would expect. It is also unbiased for the degenerate cases with $|\rho| = 1$, but that is not very interesting. In general cases the bias will be of order $\frac{1}{n}$ but quite small for all reasonable sample sizes. In Normal distributions the sample correlation coefficient is the mle, which means that it is asymptotically unbiased. You can also see that from the above formula as $\mathbb{E} \widehat{\rho} \to \rho$. Note that this already follows from the boundedness and the consistency of the sample correlation coefficient through the bounded convergence theorem.
Is the sample correlation coefficient an unbiased estimator of the population correlation coefficien This is not an easy question but some expressions are available. If you are talking about the Normal distribution in particular, then the answer is NO! We have $$\mathbb{E} \widehat{\rho} = \rho \left
14,940
Bootstrap methodology. Why resample "with replacement" instead of random subsampling?
One way to understand this choice is to think of the sample at hand as being the best representation you have of the underlying population. You may not have the whole population to sample from any more, but you do have this particular representation of the population. A truly random re-sample from this representation of the population means that you must sample with replacement, otherwise your later sampling would depend on the results of your initial sampling. The presence of a repeated case in a particular bootstrap sample represents members of the underlying population that have characteristics close to those of that particular repeated case. Leave-one-out or leave-several-out approaches, as you suggest, can also be used but that's cross validation rather than bootstrapping. I think this pretty much just puts into other words the comment from @kjetil_b_halvorsen
Bootstrap methodology. Why resample "with replacement" instead of random subsampling?
One way to understand this choice is to think of the sample at hand as being the best representation you have of the underlying population. You may not have the whole population to sample from any mor
Bootstrap methodology. Why resample "with replacement" instead of random subsampling? One way to understand this choice is to think of the sample at hand as being the best representation you have of the underlying population. You may not have the whole population to sample from any more, but you do have this particular representation of the population. A truly random re-sample from this representation of the population means that you must sample with replacement, otherwise your later sampling would depend on the results of your initial sampling. The presence of a repeated case in a particular bootstrap sample represents members of the underlying population that have characteristics close to those of that particular repeated case. Leave-one-out or leave-several-out approaches, as you suggest, can also be used but that's cross validation rather than bootstrapping. I think this pretty much just puts into other words the comment from @kjetil_b_halvorsen
Bootstrap methodology. Why resample "with replacement" instead of random subsampling? One way to understand this choice is to think of the sample at hand as being the best representation you have of the underlying population. You may not have the whole population to sample from any mor
14,941
Pearson VS Deviance Residuals in logistic regression
Logistic regression seeks to maximize the log likelihood function $LL = \sum^k \ln(P_i) + \sum^r \ln(1-P_i)$ where $P_i$ is the predicted probability that case i is $\hat Y=1$; $k$ is the number of cases observed as $Y=1$ and $r$ is the number of (the rest) cases observed as $Y=0$. That expression is equal to $LL = ({\sum^k d_i^2} + {\sum^r d_i^2})/-2$ because a case's deviance residual is defined as: $d_i = \begin{cases} \sqrt{-2\ln(P_i)} &\text{if } Y_i=1\\ -\sqrt{-2\ln(1-P_i)} &\text{if } Y_i=0\\ \end{cases}$ Thus, binary logistic regression seeks directly to minimize the sum of squared deviance residuals. It is the deviance residuals which are implied in the ML algorithm of the regression. The Chi-sq statistic of the model fit is $2(LL_\text{full model} - LL_\text{reduced model})$, where full model contains predictors and reduced model does not.
Pearson VS Deviance Residuals in logistic regression
Logistic regression seeks to maximize the log likelihood function $LL = \sum^k \ln(P_i) + \sum^r \ln(1-P_i)$ where $P_i$ is the predicted probability that case i is $\hat Y=1$; $k$ is the number of ca
Pearson VS Deviance Residuals in logistic regression Logistic regression seeks to maximize the log likelihood function $LL = \sum^k \ln(P_i) + \sum^r \ln(1-P_i)$ where $P_i$ is the predicted probability that case i is $\hat Y=1$; $k$ is the number of cases observed as $Y=1$ and $r$ is the number of (the rest) cases observed as $Y=0$. That expression is equal to $LL = ({\sum^k d_i^2} + {\sum^r d_i^2})/-2$ because a case's deviance residual is defined as: $d_i = \begin{cases} \sqrt{-2\ln(P_i)} &\text{if } Y_i=1\\ -\sqrt{-2\ln(1-P_i)} &\text{if } Y_i=0\\ \end{cases}$ Thus, binary logistic regression seeks directly to minimize the sum of squared deviance residuals. It is the deviance residuals which are implied in the ML algorithm of the regression. The Chi-sq statistic of the model fit is $2(LL_\text{full model} - LL_\text{reduced model})$, where full model contains predictors and reduced model does not.
Pearson VS Deviance Residuals in logistic regression Logistic regression seeks to maximize the log likelihood function $LL = \sum^k \ln(P_i) + \sum^r \ln(1-P_i)$ where $P_i$ is the predicted probability that case i is $\hat Y=1$; $k$ is the number of ca
14,942
Pearson VS Deviance Residuals in logistic regression
In response to this question I have added som R code to show how to manually apply the formula for calculation of deviance residuals The model in the code is a logit model where $$p_i := Pr(Y_i = 1) = \frac{\exp(b_0 + b_1x_i)}{1+\exp(b_0 + b_1x_i)}.$$ I define $v_i := b_0 + b_1x_i$ such that the model can be written as $$p_i := Pr(Y_i = 1) = \frac{\exp(v_i)}{1+\exp(v_i)}.$$ Estimating the model I get estimates $\hat b_0$ and $\hat b_1$. Using these estimates the predicted latent values $$\hat v_i := \hat b_0 + \hat b_1 x_i,$$ are calculated and then the predicted probabilities are calculated $$\hat p_i =\frac{\exp(\hat v_i )}{1+\exp(\hat v_i )}.$$ Using these predicted probabilities the formula for the deviance residuals are applied in the coding step sign(y-pred_p) * ifelse(y==1,sqrt(-2*log(pred_p)),sqrt(-2*log(1-pred_p))) which is simply an application of the formula $d_i = \begin{cases} \sqrt{-2\ln(\hat p_i)} &\text{if } Y_i=1\\ -\sqrt{-2\ln(1-\hat p_i)} &\text{if } Y_i=0\\ \end{cases}$ # Simulate some data N <- 1000 b0 <- 0.5 b1 <- 1 x <- rnorm(N) v <- b0 + b1*x p <- exp(v)/(1+exp(v)) y <- as.numeric(runif(N)<p) # Estimate model model <- glm(y~x,family=binomial) summary_model <- summary(model) summary_dev_res <- summary_model$deviance.resid # This is the output you get: quantile(summary_dev_res) # Calculate manually deviance residuals # First calculate predicted v's pred_v <- coef(model)[1] + coef(model)[2]*x # The calculate predicted probabilities pred_p <- exp(pred_v)/(1+exp(pred_v)) # Apply formula for deviance residuals dev_res <- sign(y-pred_p) * ifelse(y==1,sqrt(-2*log(pred_p)),sqrt(-2*log(1-pred_p))) # Check that it is the same as deviance residuals returned from summary plot(summary_dev_res,dev_res) points(seq(-3,3,length.out=100),seq(-3,3,length.out=100),type="l",col="red",lwd=2) # all points should be on the red line # Also compare the quantiles ... quantile(summary_dev_res) quantile(dev_res)
Pearson VS Deviance Residuals in logistic regression
In response to this question I have added som R code to show how to manually apply the formula for calculation of deviance residuals The model in the code is a logit model where $$p_i := Pr(Y_i = 1)
Pearson VS Deviance Residuals in logistic regression In response to this question I have added som R code to show how to manually apply the formula for calculation of deviance residuals The model in the code is a logit model where $$p_i := Pr(Y_i = 1) = \frac{\exp(b_0 + b_1x_i)}{1+\exp(b_0 + b_1x_i)}.$$ I define $v_i := b_0 + b_1x_i$ such that the model can be written as $$p_i := Pr(Y_i = 1) = \frac{\exp(v_i)}{1+\exp(v_i)}.$$ Estimating the model I get estimates $\hat b_0$ and $\hat b_1$. Using these estimates the predicted latent values $$\hat v_i := \hat b_0 + \hat b_1 x_i,$$ are calculated and then the predicted probabilities are calculated $$\hat p_i =\frac{\exp(\hat v_i )}{1+\exp(\hat v_i )}.$$ Using these predicted probabilities the formula for the deviance residuals are applied in the coding step sign(y-pred_p) * ifelse(y==1,sqrt(-2*log(pred_p)),sqrt(-2*log(1-pred_p))) which is simply an application of the formula $d_i = \begin{cases} \sqrt{-2\ln(\hat p_i)} &\text{if } Y_i=1\\ -\sqrt{-2\ln(1-\hat p_i)} &\text{if } Y_i=0\\ \end{cases}$ # Simulate some data N <- 1000 b0 <- 0.5 b1 <- 1 x <- rnorm(N) v <- b0 + b1*x p <- exp(v)/(1+exp(v)) y <- as.numeric(runif(N)<p) # Estimate model model <- glm(y~x,family=binomial) summary_model <- summary(model) summary_dev_res <- summary_model$deviance.resid # This is the output you get: quantile(summary_dev_res) # Calculate manually deviance residuals # First calculate predicted v's pred_v <- coef(model)[1] + coef(model)[2]*x # The calculate predicted probabilities pred_p <- exp(pred_v)/(1+exp(pred_v)) # Apply formula for deviance residuals dev_res <- sign(y-pred_p) * ifelse(y==1,sqrt(-2*log(pred_p)),sqrt(-2*log(1-pred_p))) # Check that it is the same as deviance residuals returned from summary plot(summary_dev_res,dev_res) points(seq(-3,3,length.out=100),seq(-3,3,length.out=100),type="l",col="red",lwd=2) # all points should be on the red line # Also compare the quantiles ... quantile(summary_dev_res) quantile(dev_res)
Pearson VS Deviance Residuals in logistic regression In response to this question I have added som R code to show how to manually apply the formula for calculation of deviance residuals The model in the code is a logit model where $$p_i := Pr(Y_i = 1)
14,943
Combining multiple metrics to provide comparisons/ranking of k objects [Question and Reference Request]
Awesome question. Question 1: I approach this problem using standard deviations ($n\sigma$) to create a standardized scale where $n$ is the number of standard deviations from the mean ($\mu$) and $\sigma$ is the standard deviation. I will use an example of a call center agent making calls. Here is a possible way to define the scale using $n$: $m_+ = n$: Metrics you want to maximize. Direct relationship so as $n$ increases so does the score, as $n$ decreases the score goes down. Example: number of sales. $m_-$ = -n: Metrics you want to minimize. Inverse relationship so as $n$ decreases the score increases. Example: Number of mistakes made in a call. $m_{\mu} = -\lvert n\rvert$: Metrics you want as close to the mean as possible. As $n$ gets farther from the mean in either direction the score goes down. A perfect score is 0, at the median. Example: # of voicemails / hangups / do not call requests a agent received (should be equally distributed). Then you have a scale that is independent of units of measure, size / amplitude, etc. You can then easily normalize scale above from $[0, 1]$ where $0$ is always the worst and $1$ is always the best. So each normalized metric becomes: $\overline m_+$, $\overline m_-$, and $\overline m_{\mu}$ So the simple solution ($f_s$) becomes: $$ f_s = \sum \overline m_+ + \sum \overline m_- + \sum \overline m_{\mu} $$ Question 2 With the above solution for $f_s$ adding asymmetric weights ($W$) gives us the weighted solution $f_w$. Each one can be weighed by multiplying each of the metrics by the weight: $$ f_w = \sum\limits_{j_+} (W_{+1}* \overline m_{+1} + W_{+2}* \overline m_{+2} ... W_{+j_+}* \overline m_{+j_+}) + \sum\limits_{j_-} (W_{-1}* \overline m_{-1} + W_{-1}* \overline m_{-2} ... W_{-j}* \overline m_{-j_-}) + \sum\limits_{j_\mu} (W_{\mu1}* \overline m_{\mu1} + W_{\mu2}* \overline m_{\mu2} ... W_{\mu j}* \overline m_{\mu j_\mu}) $$ Or more succinctly: $$ f_w = \sum\limits_{j_+} W_{j_+} * \overline m_{+j_+} + \sum\limits_{j_-} W_{j_-} \overline m_{-j_-} + \sum\limits_{j_\mu} W_{j_\mu} \overline m_{\mu j_\mu} $$ Now you have a score that can take into account individual weights, minimizing metrics, maximizing metrics and metrics you want close to the mean. Question 3 Example Now that you have your score $f_w$ you can again normalize it and multiply it against a a weight if you want a unit of measure. Following the call center agent example: * agent 1: 1 sale, logged in for 30 min * agent 2: 5 sales, logged in for 5 hours * agent 3: 12 sales, logged in for 4 hours Picking your metrics is very, very important. Bad Example: Sales alone $\mu = \frac{1 + 5 + 12}{3} = 6$ $Var(f_w) = \frac{5 + 1 + 6}{3} = 4 $ $\sigma = \sqrt{Var(f_w)} = \sqrt 4 = 2$ So now we need the number of standard deviations: $a_1 = -2.5 \sigma$ away from the mean $a_2 = -0.5 \sigma$ away from the mean $a3 = +3 \sigma$ away from the mean So the stack ranking of best to worst would be a3, a2, a1. The problem is that agent 2 has been payable / billable for much longer and is really the worst. So you need to be careful when crafting the metrics to make sure that they have the desired effect. In the above example it would be better to take a sales / hour approach as your metric and then multiply at the end by how long the agent has been making calls. Better Example: Sales / Hour Sales Per Hour: $a_1 = \frac{1}{\frac{1}{2}} = 2$ $a_2 = \frac{5}{5} = 1$ $a_3 = \frac{12}{4} = 3$ $\mu = \frac{ 2 + 1 + 3}{3} = 2$ $Var(f_w) = \frac{0 + 1 + 1}{3} = \frac{2}{3} $ $\sigma = \sqrt \frac{2}{3} \approx 0.82 $ So in this case, the agents have the following $n$ standard deviations away from $\mu$: $a_1 = 0 \sigma $ $a_2 \approx -1.2 \sigma $ $a_3 \approx 1.2 \sigma $ So now they are in the proper order but we still don't have a gauge on how much of a problem it is that agent $a_2$ is lagging. It is more of a problem because that agent has been logged in for a longer period of time. So adding a weight $W$ of the login time gives you the following: $a_1 = 0 $ $a_2 \approx -1.2 * 5 \approx -6.12 $ $a_3 \approx 1.2 * 4 \approx 4.90 $ You can now normalize these numbers to compare to other metrics in the same way. As you can see, $a_1$ is doing well, $a_3$ is doing the best and $a_1$ in the scenario is lagging way behind. These are the results you would expect. This number now portrays: quality (of the agent) severity (to the business) This is not the only way to solve multiple criteria decision analysis problems but it is a very practical way. From what I understand this method is called "Goal Programming" and is a pretty straightforward way to come to conclusions about complex problems. For more information see Charnes, A. and Cooper, W.W. (1961). Management Models and Industrial Applications of Linear Programming. New York: Wiley.
Combining multiple metrics to provide comparisons/ranking of k objects [Question and Reference Reque
Awesome question. Question 1: I approach this problem using standard deviations ($n\sigma$) to create a standardized scale where $n$ is the number of standard deviations from the mean ($\mu$) and $\
Combining multiple metrics to provide comparisons/ranking of k objects [Question and Reference Request] Awesome question. Question 1: I approach this problem using standard deviations ($n\sigma$) to create a standardized scale where $n$ is the number of standard deviations from the mean ($\mu$) and $\sigma$ is the standard deviation. I will use an example of a call center agent making calls. Here is a possible way to define the scale using $n$: $m_+ = n$: Metrics you want to maximize. Direct relationship so as $n$ increases so does the score, as $n$ decreases the score goes down. Example: number of sales. $m_-$ = -n: Metrics you want to minimize. Inverse relationship so as $n$ decreases the score increases. Example: Number of mistakes made in a call. $m_{\mu} = -\lvert n\rvert$: Metrics you want as close to the mean as possible. As $n$ gets farther from the mean in either direction the score goes down. A perfect score is 0, at the median. Example: # of voicemails / hangups / do not call requests a agent received (should be equally distributed). Then you have a scale that is independent of units of measure, size / amplitude, etc. You can then easily normalize scale above from $[0, 1]$ where $0$ is always the worst and $1$ is always the best. So each normalized metric becomes: $\overline m_+$, $\overline m_-$, and $\overline m_{\mu}$ So the simple solution ($f_s$) becomes: $$ f_s = \sum \overline m_+ + \sum \overline m_- + \sum \overline m_{\mu} $$ Question 2 With the above solution for $f_s$ adding asymmetric weights ($W$) gives us the weighted solution $f_w$. Each one can be weighed by multiplying each of the metrics by the weight: $$ f_w = \sum\limits_{j_+} (W_{+1}* \overline m_{+1} + W_{+2}* \overline m_{+2} ... W_{+j_+}* \overline m_{+j_+}) + \sum\limits_{j_-} (W_{-1}* \overline m_{-1} + W_{-1}* \overline m_{-2} ... W_{-j}* \overline m_{-j_-}) + \sum\limits_{j_\mu} (W_{\mu1}* \overline m_{\mu1} + W_{\mu2}* \overline m_{\mu2} ... W_{\mu j}* \overline m_{\mu j_\mu}) $$ Or more succinctly: $$ f_w = \sum\limits_{j_+} W_{j_+} * \overline m_{+j_+} + \sum\limits_{j_-} W_{j_-} \overline m_{-j_-} + \sum\limits_{j_\mu} W_{j_\mu} \overline m_{\mu j_\mu} $$ Now you have a score that can take into account individual weights, minimizing metrics, maximizing metrics and metrics you want close to the mean. Question 3 Example Now that you have your score $f_w$ you can again normalize it and multiply it against a a weight if you want a unit of measure. Following the call center agent example: * agent 1: 1 sale, logged in for 30 min * agent 2: 5 sales, logged in for 5 hours * agent 3: 12 sales, logged in for 4 hours Picking your metrics is very, very important. Bad Example: Sales alone $\mu = \frac{1 + 5 + 12}{3} = 6$ $Var(f_w) = \frac{5 + 1 + 6}{3} = 4 $ $\sigma = \sqrt{Var(f_w)} = \sqrt 4 = 2$ So now we need the number of standard deviations: $a_1 = -2.5 \sigma$ away from the mean $a_2 = -0.5 \sigma$ away from the mean $a3 = +3 \sigma$ away from the mean So the stack ranking of best to worst would be a3, a2, a1. The problem is that agent 2 has been payable / billable for much longer and is really the worst. So you need to be careful when crafting the metrics to make sure that they have the desired effect. In the above example it would be better to take a sales / hour approach as your metric and then multiply at the end by how long the agent has been making calls. Better Example: Sales / Hour Sales Per Hour: $a_1 = \frac{1}{\frac{1}{2}} = 2$ $a_2 = \frac{5}{5} = 1$ $a_3 = \frac{12}{4} = 3$ $\mu = \frac{ 2 + 1 + 3}{3} = 2$ $Var(f_w) = \frac{0 + 1 + 1}{3} = \frac{2}{3} $ $\sigma = \sqrt \frac{2}{3} \approx 0.82 $ So in this case, the agents have the following $n$ standard deviations away from $\mu$: $a_1 = 0 \sigma $ $a_2 \approx -1.2 \sigma $ $a_3 \approx 1.2 \sigma $ So now they are in the proper order but we still don't have a gauge on how much of a problem it is that agent $a_2$ is lagging. It is more of a problem because that agent has been logged in for a longer period of time. So adding a weight $W$ of the login time gives you the following: $a_1 = 0 $ $a_2 \approx -1.2 * 5 \approx -6.12 $ $a_3 \approx 1.2 * 4 \approx 4.90 $ You can now normalize these numbers to compare to other metrics in the same way. As you can see, $a_1$ is doing well, $a_3$ is doing the best and $a_1$ in the scenario is lagging way behind. These are the results you would expect. This number now portrays: quality (of the agent) severity (to the business) This is not the only way to solve multiple criteria decision analysis problems but it is a very practical way. From what I understand this method is called "Goal Programming" and is a pretty straightforward way to come to conclusions about complex problems. For more information see Charnes, A. and Cooper, W.W. (1961). Management Models and Industrial Applications of Linear Programming. New York: Wiley.
Combining multiple metrics to provide comparisons/ranking of k objects [Question and Reference Reque Awesome question. Question 1: I approach this problem using standard deviations ($n\sigma$) to create a standardized scale where $n$ is the number of standard deviations from the mean ($\mu$) and $\
14,944
Understanding the Chi-squared test and the Chi-squared distribution
We could as well use a binomial distribution but it is not the point of the question… Nevertheless, it is our starting point even for your actual question. I'll cover it somewhat informally. Let's consider with the binomial case more generally: $Y\sim \text{Bin}(n,p)$ Assume $n$ and $p$ are such that $Y$ is well approximated by a normal with the same mean and variance (some typical requirements are that $\min(np,n(1-p))$ is not small, or that $np(1-p)$ is not small). Then $(Y-E(Y))^2/\text{Var}(Y)$ will be approximately $\sim\chi^2_1$. Here $Y$ is the number of successes. We have $E(Y) = np$ and $\text{Var}(Y)=np(1-p)$. (In the testing case, $n$ is known and $p$ is specified under $H_0$. We don't do any estimation.) So if $H_0$ is true $(Y-np)^2/np(1-p)$ will be approximately $\sim\chi^2_1$. Note that $(Y-np)^2 = [(n-Y)-n(1-p)]^2$. Also note that $\frac{1}{p} + \frac{1}{1-p} = \frac{1}{p(1-p)}$. Hence $\frac{(Y-np)^2}{np(1-p)} = \frac{(Y-np)^2}{np}+\frac{(Y-np)^2}{n(1-p)}\\ \quad= \frac{(Y-np)^2}{np}+\frac{[(n-Y)-n(1-p)]^2}{n(1-p)} \\ \quad= \frac{(O_S-E_S)^2}{E_S}+\frac{(O_F-E_F)^2}{E_F}$ Which is just the chi-square statistic for the binomial case. So in that case the chi-square statistic should have the distribution of the square of an (approximately) standard-normal random variable.
Understanding the Chi-squared test and the Chi-squared distribution
We could as well use a binomial distribution but it is not the point of the question… Nevertheless, it is our starting point even for your actual question. I'll cover it somewhat informally. Let's co
Understanding the Chi-squared test and the Chi-squared distribution We could as well use a binomial distribution but it is not the point of the question… Nevertheless, it is our starting point even for your actual question. I'll cover it somewhat informally. Let's consider with the binomial case more generally: $Y\sim \text{Bin}(n,p)$ Assume $n$ and $p$ are such that $Y$ is well approximated by a normal with the same mean and variance (some typical requirements are that $\min(np,n(1-p))$ is not small, or that $np(1-p)$ is not small). Then $(Y-E(Y))^2/\text{Var}(Y)$ will be approximately $\sim\chi^2_1$. Here $Y$ is the number of successes. We have $E(Y) = np$ and $\text{Var}(Y)=np(1-p)$. (In the testing case, $n$ is known and $p$ is specified under $H_0$. We don't do any estimation.) So if $H_0$ is true $(Y-np)^2/np(1-p)$ will be approximately $\sim\chi^2_1$. Note that $(Y-np)^2 = [(n-Y)-n(1-p)]^2$. Also note that $\frac{1}{p} + \frac{1}{1-p} = \frac{1}{p(1-p)}$. Hence $\frac{(Y-np)^2}{np(1-p)} = \frac{(Y-np)^2}{np}+\frac{(Y-np)^2}{n(1-p)}\\ \quad= \frac{(Y-np)^2}{np}+\frac{[(n-Y)-n(1-p)]^2}{n(1-p)} \\ \quad= \frac{(O_S-E_S)^2}{E_S}+\frac{(O_F-E_F)^2}{E_F}$ Which is just the chi-square statistic for the binomial case. So in that case the chi-square statistic should have the distribution of the square of an (approximately) standard-normal random variable.
Understanding the Chi-squared test and the Chi-squared distribution We could as well use a binomial distribution but it is not the point of the question… Nevertheless, it is our starting point even for your actual question. I'll cover it somewhat informally. Let's co
14,945
How to interpret PCA loadings?
Loadings (which should not be confused with eigenvectors) have the following properties: Their sums of squares within each component are the eigenvalues (components' variances). Loadings are coefficients in linear combination predicting a variable by the (standardized) components. You extracted 2 first PCs out of 4. Matrix of loadings $\bf A$ and the eigenvalues: A (loadings) PC1 PC2 X1 .5000000000 .5000000000 X2 .5000000000 .5000000000 X3 .5000000000 -.5000000000 X4 .5000000000 -.5000000000 Eigenvalues: 1.0000000000 1.0000000000 In this instance, both eigenvalues are equal. It is a rare case in real world, it says that PC1 and PC2 are of equal explanatory "strength". Suppose you also computed component values, Nx2 matrix $\bf C$, and you z-standardized (mean=0, st. dev.=1) them within each column. Then (as point 2 above says), $\bf \hat {X}=CA'$. But, because you left only 2 PCs out of 4 (you lack 2 more columns in $\bf A$) the restored data values $\bf \hat {X}$ are not exact, - there is an error (if eigenvalues 3, 4 are not zero). OK. What are the coefficients to predict components by variables? Clearly, if $\bf A$ were full 4x4, these would be $\bf B=(A^{-1})'$. With non-square loading matrix, we may compute them as $\bf B= A \cdot diag(eigenvalues)^{-1}=(A^+)'$, where diag(eigenvalues) is the square diagonal matrix with the eigenvalues on its diagonal, and + superscript denotes pseudoinverse. In your case: diag(eigenvalues): 1 0 0 1 B (coefficients to predict components by original variables): PC1 PC2 X1 .5000000000 .5000000000 X2 .5000000000 .5000000000 X3 .5000000000 -.5000000000 X4 .5000000000 -.5000000000 So, if $\bf X$ is Nx4 matrix of original centered variables (or standardized variables, if you are doing PCA based on correlations rather than covariances), then $\bf C=XB$; $\bf C$ are standardized principal component scores. Which in your example is: PC1 = 0.5*X1 + 0.5*X2 + 0.5*X3 + 0.5*X4 ~ (X1+X2+X3+X4)/4 "the first component is proportional to the average score" PC2 = 0.5*X1 + 0.5*X2 - 0.5*X3 - 0.5*X4 = (0.5*X1 + 0.5*X2) - (0.5*X3 + 0.5*X4) "the second component measures the difference between the first pair of scores and the second pair of scores" In this example it appeared that $\bf B=A$, but in general case they are different. Note: The above formula for the coefficients to compute component scores, $\bf B= A \cdot diag(eigenvalues)^{-1}$, is equivalent to $\bf B=R^{-1}A$, with $\bf R$ being the covariance (or correlation) matrix of variables. The latter formula comes directly from linear regression theory. The two formulas are equivalent within PCA context only. In factor analysis, they are not and to compute factor scores (which are always approximate in FA) one should rely on the second formula. Related answers of mine: More detailed about loadings vs eigenvectors. How principal component scores and factor scores are computed.
How to interpret PCA loadings?
Loadings (which should not be confused with eigenvectors) have the following properties: Their sums of squares within each component are the eigenvalues (components' variances). Loadings are coeffici
How to interpret PCA loadings? Loadings (which should not be confused with eigenvectors) have the following properties: Their sums of squares within each component are the eigenvalues (components' variances). Loadings are coefficients in linear combination predicting a variable by the (standardized) components. You extracted 2 first PCs out of 4. Matrix of loadings $\bf A$ and the eigenvalues: A (loadings) PC1 PC2 X1 .5000000000 .5000000000 X2 .5000000000 .5000000000 X3 .5000000000 -.5000000000 X4 .5000000000 -.5000000000 Eigenvalues: 1.0000000000 1.0000000000 In this instance, both eigenvalues are equal. It is a rare case in real world, it says that PC1 and PC2 are of equal explanatory "strength". Suppose you also computed component values, Nx2 matrix $\bf C$, and you z-standardized (mean=0, st. dev.=1) them within each column. Then (as point 2 above says), $\bf \hat {X}=CA'$. But, because you left only 2 PCs out of 4 (you lack 2 more columns in $\bf A$) the restored data values $\bf \hat {X}$ are not exact, - there is an error (if eigenvalues 3, 4 are not zero). OK. What are the coefficients to predict components by variables? Clearly, if $\bf A$ were full 4x4, these would be $\bf B=(A^{-1})'$. With non-square loading matrix, we may compute them as $\bf B= A \cdot diag(eigenvalues)^{-1}=(A^+)'$, where diag(eigenvalues) is the square diagonal matrix with the eigenvalues on its diagonal, and + superscript denotes pseudoinverse. In your case: diag(eigenvalues): 1 0 0 1 B (coefficients to predict components by original variables): PC1 PC2 X1 .5000000000 .5000000000 X2 .5000000000 .5000000000 X3 .5000000000 -.5000000000 X4 .5000000000 -.5000000000 So, if $\bf X$ is Nx4 matrix of original centered variables (or standardized variables, if you are doing PCA based on correlations rather than covariances), then $\bf C=XB$; $\bf C$ are standardized principal component scores. Which in your example is: PC1 = 0.5*X1 + 0.5*X2 + 0.5*X3 + 0.5*X4 ~ (X1+X2+X3+X4)/4 "the first component is proportional to the average score" PC2 = 0.5*X1 + 0.5*X2 - 0.5*X3 - 0.5*X4 = (0.5*X1 + 0.5*X2) - (0.5*X3 + 0.5*X4) "the second component measures the difference between the first pair of scores and the second pair of scores" In this example it appeared that $\bf B=A$, but in general case they are different. Note: The above formula for the coefficients to compute component scores, $\bf B= A \cdot diag(eigenvalues)^{-1}$, is equivalent to $\bf B=R^{-1}A$, with $\bf R$ being the covariance (or correlation) matrix of variables. The latter formula comes directly from linear regression theory. The two formulas are equivalent within PCA context only. In factor analysis, they are not and to compute factor scores (which are always approximate in FA) one should rely on the second formula. Related answers of mine: More detailed about loadings vs eigenvectors. How principal component scores and factor scores are computed.
How to interpret PCA loadings? Loadings (which should not be confused with eigenvectors) have the following properties: Their sums of squares within each component are the eigenvalues (components' variances). Loadings are coeffici
14,946
How to interpret PCA loadings?
Although years are passed since last comments, I think the answer to the original question should be toward a more qualitative interpretation on how to read a "loadings matrix" (regardless of the assumptions we used to build it). If the vertical 'weights' are all the same (as in the original case for PC1 with all 0.5) it means that for PC1 all variables have same weight (0.5). If all variables have same weight it means that the 'scores' (in the PC matrix which is the matrix of the original data matrix projected along the eigenvectors) are proportional to th average of scores in the original data matrix. So PC1 tells me to evaluate a generic student based on its PC scores average (which is different in this case from the original average by a factor of 2x) In relation to the second question, it's true that mathematically it's the difference between the scores of the two pairs, but the analysis of the PC2 tell us something about where the student is good or bad (as defined by PC1): so we can say that x1 and x2 move together and as much as x1 (and x2) is far from the average of its scores, x3 (and x4) is far from the average of its scores by the same amount in the opposite direction => as much more a student is good in math and phisics its scores in read/vocabulary decreas by the same amount. So in conclusion by reading the Loadings Matrix we can formulate hypothesis that can be verified by looking in the 'PC matrix' and the 'scores': if you average the row for a generic student you can say how much he is good or bad by just looking at the value (don't forget that we decide that high/low means good/bad), if you then pick x1 (or x2) you can expect they are similar (both high or both low) and you can say from that if that student is good or bad in that subject, and by consequence you can expect he's bad or good in x3 (or x4).
How to interpret PCA loadings?
Although years are passed since last comments, I think the answer to the original question should be toward a more qualitative interpretation on how to read a "loadings matrix" (regardless of the assu
How to interpret PCA loadings? Although years are passed since last comments, I think the answer to the original question should be toward a more qualitative interpretation on how to read a "loadings matrix" (regardless of the assumptions we used to build it). If the vertical 'weights' are all the same (as in the original case for PC1 with all 0.5) it means that for PC1 all variables have same weight (0.5). If all variables have same weight it means that the 'scores' (in the PC matrix which is the matrix of the original data matrix projected along the eigenvectors) are proportional to th average of scores in the original data matrix. So PC1 tells me to evaluate a generic student based on its PC scores average (which is different in this case from the original average by a factor of 2x) In relation to the second question, it's true that mathematically it's the difference between the scores of the two pairs, but the analysis of the PC2 tell us something about where the student is good or bad (as defined by PC1): so we can say that x1 and x2 move together and as much as x1 (and x2) is far from the average of its scores, x3 (and x4) is far from the average of its scores by the same amount in the opposite direction => as much more a student is good in math and phisics its scores in read/vocabulary decreas by the same amount. So in conclusion by reading the Loadings Matrix we can formulate hypothesis that can be verified by looking in the 'PC matrix' and the 'scores': if you average the row for a generic student you can say how much he is good or bad by just looking at the value (don't forget that we decide that high/low means good/bad), if you then pick x1 (or x2) you can expect they are similar (both high or both low) and you can say from that if that student is good or bad in that subject, and by consequence you can expect he's bad or good in x3 (or x4).
How to interpret PCA loadings? Although years are passed since last comments, I think the answer to the original question should be toward a more qualitative interpretation on how to read a "loadings matrix" (regardless of the assu
14,947
Proper bootstrapping technique for clustered data?
The second approach you suggest seems reasonable, but it turns out that it is better to only sample with replacement at the highest level, and without replacement at the remaining sublevels when bootstrapping hierarchical data. This is shown from simulations by Ren et al (2010) : http://www.tandfonline.com/doi/abs/10.1080/02664760903046102 Field & Welsh (2007) theoretically investigated different approaches for 2-level data sets and found that sampling with replacement at both levels was not a brilliant idea. http://onlinelibrary.wiley.com/doi/10.1111/j.1467-9868.2007.00593.x/full The autocorrelation that you mention is a serious problem. On the other hand, selecting without replacement from episodes of care would preserve the autocorrelation structure so maybe it is not such a big problem.
Proper bootstrapping technique for clustered data?
The second approach you suggest seems reasonable, but it turns out that it is better to only sample with replacement at the highest level, and without replacement at the remaining sublevels when boots
Proper bootstrapping technique for clustered data? The second approach you suggest seems reasonable, but it turns out that it is better to only sample with replacement at the highest level, and without replacement at the remaining sublevels when bootstrapping hierarchical data. This is shown from simulations by Ren et al (2010) : http://www.tandfonline.com/doi/abs/10.1080/02664760903046102 Field & Welsh (2007) theoretically investigated different approaches for 2-level data sets and found that sampling with replacement at both levels was not a brilliant idea. http://onlinelibrary.wiley.com/doi/10.1111/j.1467-9868.2007.00593.x/full The autocorrelation that you mention is a serious problem. On the other hand, selecting without replacement from episodes of care would preserve the autocorrelation structure so maybe it is not such a big problem.
Proper bootstrapping technique for clustered data? The second approach you suggest seems reasonable, but it turns out that it is better to only sample with replacement at the highest level, and without replacement at the remaining sublevels when boots
14,948
Time dependent coefficients in R - how to do it?
@mpiktas came close in offering a feasible model, however the term that needs to be used for the quadratic in time=t would be I(t^2)) . This is so because in R the formula interpretation of "^" creates interactions and does not perform exponentiation, so the interaction of "t" with "t" is just "t". (Shouldn't this be migrated to SO with an [r] tag?) For alternatives to this process, which looks to me somewhat dubious for inference purposes, and one which probably fits your interest in using the supportive functions in Harrell's rms/Hmisc packages, see Harrell's "Regression Modeling Strategies". He mentions (but only in passing although he does cite some of his own papers) constructing spline fits to the time scale to model bathtub-shaped hazards. His chapter on parametric survival models describes a variety of plotting techniques for checking proportional hazards assumptions and for examining the linearity of estimated log-hazard effects on the time scale. Edit: An additional option is to use coxph's 'tt' parameter described as an "optional list of time-transform functions."
Time dependent coefficients in R - how to do it?
@mpiktas came close in offering a feasible model, however the term that needs to be used for the quadratic in time=t would be I(t^2)) . This is so because in R the formula interpretation of "^" create
Time dependent coefficients in R - how to do it? @mpiktas came close in offering a feasible model, however the term that needs to be used for the quadratic in time=t would be I(t^2)) . This is so because in R the formula interpretation of "^" creates interactions and does not perform exponentiation, so the interaction of "t" with "t" is just "t". (Shouldn't this be migrated to SO with an [r] tag?) For alternatives to this process, which looks to me somewhat dubious for inference purposes, and one which probably fits your interest in using the supportive functions in Harrell's rms/Hmisc packages, see Harrell's "Regression Modeling Strategies". He mentions (but only in passing although he does cite some of his own papers) constructing spline fits to the time scale to model bathtub-shaped hazards. His chapter on parametric survival models describes a variety of plotting techniques for checking proportional hazards assumptions and for examining the linearity of estimated log-hazard effects on the time scale. Edit: An additional option is to use coxph's 'tt' parameter described as an "optional list of time-transform functions."
Time dependent coefficients in R - how to do it? @mpiktas came close in offering a feasible model, however the term that needs to be used for the quadratic in time=t would be I(t^2)) . This is so because in R the formula interpretation of "^" create
14,949
Time dependent coefficients in R - how to do it?
I've changed the answer to this as neither @DWin's or @Zach's answers fully answers how to model time-varying coefficients. I've recently wrote a post about this. Here's the gist of it. The core concept in the Cox regression model is the hazard function, $h(t)$. It is defined as: $$h(t) = \frac{f(t)}{S(t)}$$ Where the $f(t)$ is the risk of having an event at any given time while the $S(t)$ is the probability of surviving that fare. The number is thus a fraction with a theoretical range from $0$ to $\infty$. An interesting feature of the hazard function is that we can include observations at other points in time than $time_0$, e.g. if "Peter" is operated with a hip arthroplasty in England, arrives after 1 year to Sweden, he has been alive for 1 year when we choose to include him. Note that any patient that would have died prior to that would never have come to our attention and we can therefore not include Peter in the $S(t)$ when looking at the hazard prior to 1 year. After 1 year we may include Peter. When allowing subjects entering at other time points we must change the Surv from Surv(time, status) to Surv(start_time, end_time, status). While the end_time is strongly correlated with the outcome the start_time is now available as an interaction term (just as hinted in the original suggestions). In a regular setting the start_time is 0 except for a few subjects that appear later but is we split each observation into several periods we suddenly have plenty start times that are non-zero. The only difference is that each observation occurs multiple times where all but the last observation has the option of a non-censored outcome. Time splitting in practice I've just published on CRAN the Greg package that makes this time-split easy. First we start with some theoretical observations: library(Greg) test_data <- data.frame( id = 1:4, time = c(4, 3.5, 1, 5), event = c("censored", "dead", "alive", "dead"), age = c(62.2, 55.3, 73.7, 46.3), date = as.Date( c("2003-01-01", "2010-04-01", "2013-09-20", "2002-02-23")) ) We can show this graphically with * being an indicator of event: If we apply the timeSplitter as following: library(dplyr) split_data <- test_data %>% select(id, event, time, age, date) %>% timeSplitter(by = 2, # The time that we want to split by event_var = "event", time_var = "time", event_start_status = "alive", time_related_vars = c("age", "date")) We get the following: As you can see each object has been split into multiple events where the last time span contains the actual event status. This allows us to now build models that have simple : interaction terms (do not use the * as this expands to time + var + time:var and we're not interested in the time per se). There is no need for using the I() function although if you want to check nonlinearity with time I often create a separate time-interaction variable that I add a spline to and then display using rms::contrast. Anyway, your regression call should now look like this: coxp(Surv(start_time, end_time, event) ~ var1 + var2 + var2:time, data = time_split_data) Using the survival package's tt function There is also a way to model time dependent coefficients directly in the survival package using the tt function. Prof. Therneau provides a thorough introduction to the subject in his vignette. Unfortunately in large datasets this is hard to do due to memory limitations. It seems that the tt function splits the time into very fine pieces generating in the process a huge matrix.
Time dependent coefficients in R - how to do it?
I've changed the answer to this as neither @DWin's or @Zach's answers fully answers how to model time-varying coefficients. I've recently wrote a post about this. Here's the gist of it. The core conce
Time dependent coefficients in R - how to do it? I've changed the answer to this as neither @DWin's or @Zach's answers fully answers how to model time-varying coefficients. I've recently wrote a post about this. Here's the gist of it. The core concept in the Cox regression model is the hazard function, $h(t)$. It is defined as: $$h(t) = \frac{f(t)}{S(t)}$$ Where the $f(t)$ is the risk of having an event at any given time while the $S(t)$ is the probability of surviving that fare. The number is thus a fraction with a theoretical range from $0$ to $\infty$. An interesting feature of the hazard function is that we can include observations at other points in time than $time_0$, e.g. if "Peter" is operated with a hip arthroplasty in England, arrives after 1 year to Sweden, he has been alive for 1 year when we choose to include him. Note that any patient that would have died prior to that would never have come to our attention and we can therefore not include Peter in the $S(t)$ when looking at the hazard prior to 1 year. After 1 year we may include Peter. When allowing subjects entering at other time points we must change the Surv from Surv(time, status) to Surv(start_time, end_time, status). While the end_time is strongly correlated with the outcome the start_time is now available as an interaction term (just as hinted in the original suggestions). In a regular setting the start_time is 0 except for a few subjects that appear later but is we split each observation into several periods we suddenly have plenty start times that are non-zero. The only difference is that each observation occurs multiple times where all but the last observation has the option of a non-censored outcome. Time splitting in practice I've just published on CRAN the Greg package that makes this time-split easy. First we start with some theoretical observations: library(Greg) test_data <- data.frame( id = 1:4, time = c(4, 3.5, 1, 5), event = c("censored", "dead", "alive", "dead"), age = c(62.2, 55.3, 73.7, 46.3), date = as.Date( c("2003-01-01", "2010-04-01", "2013-09-20", "2002-02-23")) ) We can show this graphically with * being an indicator of event: If we apply the timeSplitter as following: library(dplyr) split_data <- test_data %>% select(id, event, time, age, date) %>% timeSplitter(by = 2, # The time that we want to split by event_var = "event", time_var = "time", event_start_status = "alive", time_related_vars = c("age", "date")) We get the following: As you can see each object has been split into multiple events where the last time span contains the actual event status. This allows us to now build models that have simple : interaction terms (do not use the * as this expands to time + var + time:var and we're not interested in the time per se). There is no need for using the I() function although if you want to check nonlinearity with time I often create a separate time-interaction variable that I add a spline to and then display using rms::contrast. Anyway, your regression call should now look like this: coxp(Surv(start_time, end_time, event) ~ var1 + var2 + var2:time, data = time_split_data) Using the survival package's tt function There is also a way to model time dependent coefficients directly in the survival package using the tt function. Prof. Therneau provides a thorough introduction to the subject in his vignette. Unfortunately in large datasets this is hard to do due to memory limitations. It seems that the tt function splits the time into very fine pieces generating in the process a huge matrix.
Time dependent coefficients in R - how to do it? I've changed the answer to this as neither @DWin's or @Zach's answers fully answers how to model time-varying coefficients. I've recently wrote a post about this. Here's the gist of it. The core conce
14,950
Time dependent coefficients in R - how to do it?
You can use the apply.rolling function in PerformanceAnalytics to run a linear regression through a rolling window, which will allow your coefficients to vary over time. For example: library(PerformanceAnalytics) library(quantmod) getSymbols(c('AAPL','SPY'), from='01-01-1900') chart.RollingRegression(Cl(AAPL),Cl(SPY), width=252, attribute='Beta') #Note: Alpha=y-intercept, Beta=regression coeffient This works with other functions too.
Time dependent coefficients in R - how to do it?
You can use the apply.rolling function in PerformanceAnalytics to run a linear regression through a rolling window, which will allow your coefficients to vary over time. For example: library(Performan
Time dependent coefficients in R - how to do it? You can use the apply.rolling function in PerformanceAnalytics to run a linear regression through a rolling window, which will allow your coefficients to vary over time. For example: library(PerformanceAnalytics) library(quantmod) getSymbols(c('AAPL','SPY'), from='01-01-1900') chart.RollingRegression(Cl(AAPL),Cl(SPY), width=252, attribute='Beta') #Note: Alpha=y-intercept, Beta=regression coeffient This works with other functions too.
Time dependent coefficients in R - how to do it? You can use the apply.rolling function in PerformanceAnalytics to run a linear regression through a rolling window, which will allow your coefficients to vary over time. For example: library(Performan
14,951
Average precision vs precision
Precision refers to precision at a particular decision threshold. For example, if you count any model output less than 0.5 as negative, and greater than 0.5 as positive. But sometimes (especially if your classes are not balanced, or if you want to favor precision over recall or vice versa), you may want to vary this threshold. Average precision gives you average precision at all such possible thresholds, which is also similar to the area under the precision-recall curve. It is a useful metric to compare how well models are ordering the predictions, without considering any specific decision threshold. Reference: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html
Average precision vs precision
Precision refers to precision at a particular decision threshold. For example, if you count any model output less than 0.5 as negative, and greater than 0.5 as positive. But sometimes (especially if y
Average precision vs precision Precision refers to precision at a particular decision threshold. For example, if you count any model output less than 0.5 as negative, and greater than 0.5 as positive. But sometimes (especially if your classes are not balanced, or if you want to favor precision over recall or vice versa), you may want to vary this threshold. Average precision gives you average precision at all such possible thresholds, which is also similar to the area under the precision-recall curve. It is a useful metric to compare how well models are ordering the predictions, without considering any specific decision threshold. Reference: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html
Average precision vs precision Precision refers to precision at a particular decision threshold. For example, if you count any model output less than 0.5 as negative, and greater than 0.5 as positive. But sometimes (especially if y
14,952
Average precision vs precision
Precision is Pr = TP/(TP+FP) where is TP and FP are True positives and False positives. so, we use this metric to evaluate systems like classifiers to know how precisely we found positives. if your classifier marked an entry True even if it is False in real, it increases FP, which in turn decreases Pr. So your system is not precise. so, in case of classifiers we don't need to know which entry has the highest probability to belong to a class or things like that. where as let's say you built an app which searches for music videos. so, if a query is made about a song(lets say I want to break free), if the first 5 retrieved entries from query are not at all related to the song or the band 'Queen' and entries from 6 to 10 are related to them, then your app is utter waste. so, in these cases where the order matters, we calculate precision and recall(Re = TP/(TP+FN)) and the area under the curve is MAP (mean average precision) The intuition behind the idea is as follows, as the number of true entries in real are fixed, moving to a next entry either increases the recall(when you encounter true positive) or keeps it the same(when you encounter a false positive) where as precision decreases(if FP was encountered) and remains same or increases (if TP was encountered) so, if you get irrelevant results at the starting, the precision remains almost 0, which makes your MAP 0, where as if you find all the accurate results at the starting (which basically means zero FPs) so precision is close to 1, results in MAP close to 1. which certifies your system as the best one this article gives a detailed description with examples Breaking Down Mean Average Precision (mAP)
Average precision vs precision
Precision is Pr = TP/(TP+FP) where is TP and FP are True positives and False positives. so, we use this metric to evaluate systems like classifiers to know how precisely we found positives. if your cl
Average precision vs precision Precision is Pr = TP/(TP+FP) where is TP and FP are True positives and False positives. so, we use this metric to evaluate systems like classifiers to know how precisely we found positives. if your classifier marked an entry True even if it is False in real, it increases FP, which in turn decreases Pr. So your system is not precise. so, in case of classifiers we don't need to know which entry has the highest probability to belong to a class or things like that. where as let's say you built an app which searches for music videos. so, if a query is made about a song(lets say I want to break free), if the first 5 retrieved entries from query are not at all related to the song or the band 'Queen' and entries from 6 to 10 are related to them, then your app is utter waste. so, in these cases where the order matters, we calculate precision and recall(Re = TP/(TP+FN)) and the area under the curve is MAP (mean average precision) The intuition behind the idea is as follows, as the number of true entries in real are fixed, moving to a next entry either increases the recall(when you encounter true positive) or keeps it the same(when you encounter a false positive) where as precision decreases(if FP was encountered) and remains same or increases (if TP was encountered) so, if you get irrelevant results at the starting, the precision remains almost 0, which makes your MAP 0, where as if you find all the accurate results at the starting (which basically means zero FPs) so precision is close to 1, results in MAP close to 1. which certifies your system as the best one this article gives a detailed description with examples Breaking Down Mean Average Precision (mAP)
Average precision vs precision Precision is Pr = TP/(TP+FP) where is TP and FP are True positives and False positives. so, we use this metric to evaluate systems like classifiers to know how precisely we found positives. if your cl
14,953
Tensors in neural network literature: what's the simplest definition out there?
For the purposes of data analysis, you can effectively consider them as arrays, possibly multidimensional. Thus they include scalars, vectors, matrices, and all higher order arrays. The precise mathematical definition is more complicated. Basically the idea is that tensors transform multilinear functions to linear functions. See (1) or (2). (Multilinear functions are functions which are linear in each of their components, an example being the determinant considered as a function of column vectors.) One consequence of this mathematical property defining tensors is that tensors transform nicely with respect to Jacobians, which encode transformations from one system of coordinates to another. This is why one often sees the definition of tensor as "an object which transforms in a certain way under changes of coordinates" in physics. See this video for example, or this one. If we are dealing with sufficiently "nice" objects (all of the derivatives we would like to exist and well-defined are), then all of these ways of thinking about tensors are essentially equivalent. Note that the first way to think of tensors which I mentioned (multidimensional arrays) ignores the distinction between covariant and contravariant tensors. (The distinction is with regards to how their coefficients change under a change of basis of the underlying vector space, i.e. between row and column vectors essentially.) See these other StackExchange questions: (1) (2) (3) (4) For a book used by researchers studying applications of tensors to neural networks (for example at Technion in Israel), there is Wolfgang Hackbusch's Tensor Spaces and Numerical Calculus. I have not read it yet myself, although some of the later chapters seem to use advanced mathematics.
Tensors in neural network literature: what's the simplest definition out there?
For the purposes of data analysis, you can effectively consider them as arrays, possibly multidimensional. Thus they include scalars, vectors, matrices, and all higher order arrays. The precise mathe
Tensors in neural network literature: what's the simplest definition out there? For the purposes of data analysis, you can effectively consider them as arrays, possibly multidimensional. Thus they include scalars, vectors, matrices, and all higher order arrays. The precise mathematical definition is more complicated. Basically the idea is that tensors transform multilinear functions to linear functions. See (1) or (2). (Multilinear functions are functions which are linear in each of their components, an example being the determinant considered as a function of column vectors.) One consequence of this mathematical property defining tensors is that tensors transform nicely with respect to Jacobians, which encode transformations from one system of coordinates to another. This is why one often sees the definition of tensor as "an object which transforms in a certain way under changes of coordinates" in physics. See this video for example, or this one. If we are dealing with sufficiently "nice" objects (all of the derivatives we would like to exist and well-defined are), then all of these ways of thinking about tensors are essentially equivalent. Note that the first way to think of tensors which I mentioned (multidimensional arrays) ignores the distinction between covariant and contravariant tensors. (The distinction is with regards to how their coefficients change under a change of basis of the underlying vector space, i.e. between row and column vectors essentially.) See these other StackExchange questions: (1) (2) (3) (4) For a book used by researchers studying applications of tensors to neural networks (for example at Technion in Israel), there is Wolfgang Hackbusch's Tensor Spaces and Numerical Calculus. I have not read it yet myself, although some of the later chapters seem to use advanced mathematics.
Tensors in neural network literature: what's the simplest definition out there? For the purposes of data analysis, you can effectively consider them as arrays, possibly multidimensional. Thus they include scalars, vectors, matrices, and all higher order arrays. The precise mathe
14,954
Tensors in neural network literature: what's the simplest definition out there?
Tensor = multi-dimensional array In the machine learning literature, a tensor is simply a synonym for multi-dimensional array: Tensors, also known as multidimensional arrays, are generalizations of matrices to higher orders and are useful data representation architectures. Tensors in Statistics Annual Review of Statistics and Its Application (2021) Hence a 1.d tensor is a "vector/tuple", and a 2.d. tensor is a "matrix/2.d.array". Theano vs TensorFlow vs Pytorch vs ... In specific libraries the term may be restricted to numerical arrays: Theano is a Python library that allows you to define, optimize, and efficiently evaluate mathematical expressions involving multi-dimensional arrays. or those containing a broader range of data-types: Tensor - The primary data structure in TensorFlow programs. Tensors are N-dimensional (where N could be very large) data structures, most commonly scalars, vectors, or matrices. The elements of a Tensor can hold integer, floating-point, or string values. Etymology Tensor has a more specific meaning in mathematics as an abstraction of a multilinear map between vector spaces, but given a fixed basis such maps can be represented as multidimensional arrays, and it is from this usage that the machine learning term gets its name.
Tensors in neural network literature: what's the simplest definition out there?
Tensor = multi-dimensional array In the machine learning literature, a tensor is simply a synonym for multi-dimensional array: Tensors, also known as multidimensional arrays, are generalizations of m
Tensors in neural network literature: what's the simplest definition out there? Tensor = multi-dimensional array In the machine learning literature, a tensor is simply a synonym for multi-dimensional array: Tensors, also known as multidimensional arrays, are generalizations of matrices to higher orders and are useful data representation architectures. Tensors in Statistics Annual Review of Statistics and Its Application (2021) Hence a 1.d tensor is a "vector/tuple", and a 2.d. tensor is a "matrix/2.d.array". Theano vs TensorFlow vs Pytorch vs ... In specific libraries the term may be restricted to numerical arrays: Theano is a Python library that allows you to define, optimize, and efficiently evaluate mathematical expressions involving multi-dimensional arrays. or those containing a broader range of data-types: Tensor - The primary data structure in TensorFlow programs. Tensors are N-dimensional (where N could be very large) data structures, most commonly scalars, vectors, or matrices. The elements of a Tensor can hold integer, floating-point, or string values. Etymology Tensor has a more specific meaning in mathematics as an abstraction of a multilinear map between vector spaces, but given a fixed basis such maps can be represented as multidimensional arrays, and it is from this usage that the machine learning term gets its name.
Tensors in neural network literature: what's the simplest definition out there? Tensor = multi-dimensional array In the machine learning literature, a tensor is simply a synonym for multi-dimensional array: Tensors, also known as multidimensional arrays, are generalizations of m
14,955
What are the differences between autoencoders and t-SNE?
Both of them try to find a lower dimensionality embedding of your data. However, there are different minimization problems. More specifically, an autoencoder tries to minimize the reconstruction error, while t-SNE tries to find a lower dimensional space and at the same time it tries to preserve the neighborhood distances. As a result of this attribute, t-SNE is usually preferred for plots and visualizations.
What are the differences between autoencoders and t-SNE?
Both of them try to find a lower dimensionality embedding of your data. However, there are different minimization problems. More specifically, an autoencoder tries to minimize the reconstruction error
What are the differences between autoencoders and t-SNE? Both of them try to find a lower dimensionality embedding of your data. However, there are different minimization problems. More specifically, an autoencoder tries to minimize the reconstruction error, while t-SNE tries to find a lower dimensional space and at the same time it tries to preserve the neighborhood distances. As a result of this attribute, t-SNE is usually preferred for plots and visualizations.
What are the differences between autoencoders and t-SNE? Both of them try to find a lower dimensionality embedding of your data. However, there are different minimization problems. More specifically, an autoencoder tries to minimize the reconstruction error
14,956
What are the differences between autoencoders and t-SNE?
[Autoencoders] primarily focus on maximizing the variance of the data in the latent space, as a result of which autoencoders are less successful in retaining the local structure of the data in the latent space than manifold learners... From "Learning a Parametric Embedding by Preserving Local Structure", Laurens van der Maaten (https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf)
What are the differences between autoencoders and t-SNE?
[Autoencoders] primarily focus on maximizing the variance of the data in the latent space, as a result of which autoencoders are less successful in retaining the local structure of the data in t
What are the differences between autoencoders and t-SNE? [Autoencoders] primarily focus on maximizing the variance of the data in the latent space, as a result of which autoencoders are less successful in retaining the local structure of the data in the latent space than manifold learners... From "Learning a Parametric Embedding by Preserving Local Structure", Laurens van der Maaten (https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf)
What are the differences between autoencoders and t-SNE? [Autoencoders] primarily focus on maximizing the variance of the data in the latent space, as a result of which autoencoders are less successful in retaining the local structure of the data in t
14,957
What are the differences between autoencoders and t-SNE?
Autoencoder and t-SNE can be used together for better visualization in high dimensional data, as described in [1]: For 2D visualization specifically, t-SNE is probably the best algorithm around, but it typically requires relatively low-dimensional data. So a good strategy for visualizing similarity relationships in high-dimensional data is to start by using an autoencoder to compress your data into a low-dimensional space (e.g. 32 dimensional), then use t-SNE for mapping the compressed data to a 2D plane. [1] https://blog.keras.io/building-autoencoders-in-keras.html
What are the differences between autoencoders and t-SNE?
Autoencoder and t-SNE can be used together for better visualization in high dimensional data, as described in [1]: For 2D visualization specifically, t-SNE is probably the best algorithm around, b
What are the differences between autoencoders and t-SNE? Autoencoder and t-SNE can be used together for better visualization in high dimensional data, as described in [1]: For 2D visualization specifically, t-SNE is probably the best algorithm around, but it typically requires relatively low-dimensional data. So a good strategy for visualizing similarity relationships in high-dimensional data is to start by using an autoencoder to compress your data into a low-dimensional space (e.g. 32 dimensional), then use t-SNE for mapping the compressed data to a 2D plane. [1] https://blog.keras.io/building-autoencoders-in-keras.html
What are the differences between autoencoders and t-SNE? Autoencoder and t-SNE can be used together for better visualization in high dimensional data, as described in [1]: For 2D visualization specifically, t-SNE is probably the best algorithm around, b
14,958
What are the differences between autoencoders and t-SNE?
Autoencoder is designed to preserve previous data in a 2-norm sense, which can be thought as preserve the kinetic energy of the data, if data is velocity. While t-SNE, use KL divergence which is not symmetrical, it will lead to t-SNE focus more on local structure, while autoencoder tends to keep overall L2 error small, which is in a global sense.
What are the differences between autoencoders and t-SNE?
Autoencoder is designed to preserve previous data in a 2-norm sense, which can be thought as preserve the kinetic energy of the data, if data is velocity. While t-SNE, use KL divergence which is not
What are the differences between autoencoders and t-SNE? Autoencoder is designed to preserve previous data in a 2-norm sense, which can be thought as preserve the kinetic energy of the data, if data is velocity. While t-SNE, use KL divergence which is not symmetrical, it will lead to t-SNE focus more on local structure, while autoencoder tends to keep overall L2 error small, which is in a global sense.
What are the differences between autoencoders and t-SNE? Autoencoder is designed to preserve previous data in a 2-norm sense, which can be thought as preserve the kinetic energy of the data, if data is velocity. While t-SNE, use KL divergence which is not
14,959
Creating a single index from several principal components or factors retained from PCA/FA
This answer is deliberately non-mathematical and is oriented towards non-statistician psychologist (say) who inquires whether he may sum/average factor scores of different factors to obtain a "composite index" score for each respondent. Summing or averaging some variables' scores assumes that the variables belong to the same dimension and are fungible measures. (In the question, "variables" are component or factor scores, which doesn't change the thing, since they are examples of variables.) Really (Fig. 1), respondents 1 and 2 may be seen as equally atypical (i.e. deviated from 0, the locus of the data centre or the scale origin), both having same mean score $(.8+.8)/2=.8$ and $(1.2+.4)/2=.8$. Value $.8$ is valid, as the extent of atypicality, for the construct $X+Y$ as perfectly as it was for $X$ and $Y$ separately. Correlated variables, representing same one dimension, can be seen as repeated measurements of the same characteristic and the difference or non-equivalence of their scores as random error. It is therefore warranded to sum/average the scores since random errors are expected to cancel each other out in spe. That is not so if $X$ and $Y$ do not correlate enough to be seen same "dimension". For then, the deviation/atypicality of a respondent is conveyed by Euclidean distance from the origin (Fig. 2). That distance is different for respondents 1 and 2: $\sqrt{.8^2+.8^2} \approx 1.13$ and $\sqrt{1.2^2+.4^2} \approx 1.26$, - respondend 2 being away farther. If variables are independent dimensions, euclidean distance still relates a respondent's position wrt the zero benchmark, but mean score does not. Take just an utmost example with $X=.8$ and $Y=-.8$. From the "point of view" of the mean score, this respondent is absolutely typical, like $X=0$, $Y=0$. Is that true for you? Another answer here mentions weighted sum or average, i.e. $w_XX_i+w_YY_i$ with some reasonable weights, for example - if $X$,$Y$ are principal components - proportional to the component st. deviation or variance. But such weighting changes nothing in principle, it only stretches & squeezes the circle on Fig. 2 along the axes into an ellipse. Weights $w_X$, $w_Y$ are set constant for all respondents i, which is the cause of the flaw. To relate a respondent's bivariate deviation - in a circle or ellipse - weights dependent on his scores must be introduced; the euclidean distance considered earlier is actually an example of such weighted sum with weights dependent on the values. And if it is important for you incorporate unequal variances of the variables (e.g. of the principal components, as in the question) you may compute the weighted euclidean distance, the distance that will be found on Fig. 2 after the circle becomes elongated. Euclidean distance (weighted or unweighted) as deviation is the most intuitive solution to measure bivariate or multivariate atypicality of respondents. It is based on a presupposition of the uncorreltated ("independent") variables forming a smooth, isotropic space. Manhatten distance could be one of other options. It views the feature space as consisting of blocks so only horizontal/erect, not diagonal, distances are allowed. $|.8|+|.8|=1.6$ and $|1.2|+|.4|=1.6$ give equal Manhattan atypicalities for two our respondents; it is actually the sum of scores - but only when the scores are all positive. In case of $X=.8$ and $Y=-.8$ the distance is $1.6$ but the sum is $0$. (You might exclaim "I will make all data scores positive and compute sum (or average) with good conscience since I've chosen Manhatten distance", but please think - are you in right to move the origin freely? Principal components or factors, for example, are extracted under the condition the data having been centered to the mean, which makes good sense. Other origin would have produced other components/factors with other scores. No, most of the time you may not play with origin - the locus of "typical respondent" or of "zero-level trait" - as you fancy to play.) To sum up, if the aim of the composite construct is to reflect respondent positions relative some "zero" or typical locus but the variables hardly at all correlate, some sort of spatial distance from that origin, and not mean (or sum), weighted or unweighted, should be chosen. Well, the mean (sum) will make sense if you decide to view the (uncorrelated) variables as alternative modes to measure the same thing. This way you are deliberately ignoring the variables' different nature. In other words, you consciously leave Fig. 2 in favour of Fig. 1: you "forget" that the variables are independent. Then - do sum or average. For example, score on "material welfare" and on "emotional welfare" could be averaged, likewise scores on "spatial IQ" and on "verbal IQ". This type of purely pragmatic, not approved satistically composites are called battery indices (a collection of tests or questionnaires which measure unrelated things or correlated things whose correlations we ignore is called "battery"). Battery indices make sense only if the scores have same direction (such as both wealth and emotional health are seen as "better" pole). Their usefulness outside narrow ad hoc settings is limited. If the variables are in-between relations - they are considerably correlated still not strongly enough to see them as duplicates, alternatives, of each other, we often sum (or average) their values in a weighted manner. Then these weights should be carefully designed and they should reflect, this or that way, the correlations. This what we do, for example, by means of PCA or factor analysis (FA) where we specially compute component/factor scores. If your variables are themselves already component or factor scores (like the OP question here says) and they are correlated (because of oblique rotation), you may subject them (or directly the loading matrix) to the second-order PCA/FA to find the weights and get the second-order PC/factor that will serve the "composite index" for you. But if your component/factor scores were uncorrelated or weakly correlated, there is no statistical reason neither to sum them bluntly nor via inferring weights. Use some distance instead. The problem with distance is that it is always positive: you can say how much atypical a respondent is but cannot say if he is "above" or "below". But this is the price you have to pay for demanding a single index out from multi-trait space. If you want both deviation and sign in such space I would say you're too exigent. In the last point, the OP asks whether it is right to take only the score of one, strongest variable in respect to its variance - 1st principal component in this instance - as the only proxy, for the "index". It makes sense if that PC is much stronger than the rest PCs. Though one might ask then "if it is so much stronger, why didn't you extract/retain just it sole?".
Creating a single index from several principal components or factors retained from PCA/FA
This answer is deliberately non-mathematical and is oriented towards non-statistician psychologist (say) who inquires whether he may sum/average factor scores of different factors to obtain a "composi
Creating a single index from several principal components or factors retained from PCA/FA This answer is deliberately non-mathematical and is oriented towards non-statistician psychologist (say) who inquires whether he may sum/average factor scores of different factors to obtain a "composite index" score for each respondent. Summing or averaging some variables' scores assumes that the variables belong to the same dimension and are fungible measures. (In the question, "variables" are component or factor scores, which doesn't change the thing, since they are examples of variables.) Really (Fig. 1), respondents 1 and 2 may be seen as equally atypical (i.e. deviated from 0, the locus of the data centre or the scale origin), both having same mean score $(.8+.8)/2=.8$ and $(1.2+.4)/2=.8$. Value $.8$ is valid, as the extent of atypicality, for the construct $X+Y$ as perfectly as it was for $X$ and $Y$ separately. Correlated variables, representing same one dimension, can be seen as repeated measurements of the same characteristic and the difference or non-equivalence of their scores as random error. It is therefore warranded to sum/average the scores since random errors are expected to cancel each other out in spe. That is not so if $X$ and $Y$ do not correlate enough to be seen same "dimension". For then, the deviation/atypicality of a respondent is conveyed by Euclidean distance from the origin (Fig. 2). That distance is different for respondents 1 and 2: $\sqrt{.8^2+.8^2} \approx 1.13$ and $\sqrt{1.2^2+.4^2} \approx 1.26$, - respondend 2 being away farther. If variables are independent dimensions, euclidean distance still relates a respondent's position wrt the zero benchmark, but mean score does not. Take just an utmost example with $X=.8$ and $Y=-.8$. From the "point of view" of the mean score, this respondent is absolutely typical, like $X=0$, $Y=0$. Is that true for you? Another answer here mentions weighted sum or average, i.e. $w_XX_i+w_YY_i$ with some reasonable weights, for example - if $X$,$Y$ are principal components - proportional to the component st. deviation or variance. But such weighting changes nothing in principle, it only stretches & squeezes the circle on Fig. 2 along the axes into an ellipse. Weights $w_X$, $w_Y$ are set constant for all respondents i, which is the cause of the flaw. To relate a respondent's bivariate deviation - in a circle or ellipse - weights dependent on his scores must be introduced; the euclidean distance considered earlier is actually an example of such weighted sum with weights dependent on the values. And if it is important for you incorporate unequal variances of the variables (e.g. of the principal components, as in the question) you may compute the weighted euclidean distance, the distance that will be found on Fig. 2 after the circle becomes elongated. Euclidean distance (weighted or unweighted) as deviation is the most intuitive solution to measure bivariate or multivariate atypicality of respondents. It is based on a presupposition of the uncorreltated ("independent") variables forming a smooth, isotropic space. Manhatten distance could be one of other options. It views the feature space as consisting of blocks so only horizontal/erect, not diagonal, distances are allowed. $|.8|+|.8|=1.6$ and $|1.2|+|.4|=1.6$ give equal Manhattan atypicalities for two our respondents; it is actually the sum of scores - but only when the scores are all positive. In case of $X=.8$ and $Y=-.8$ the distance is $1.6$ but the sum is $0$. (You might exclaim "I will make all data scores positive and compute sum (or average) with good conscience since I've chosen Manhatten distance", but please think - are you in right to move the origin freely? Principal components or factors, for example, are extracted under the condition the data having been centered to the mean, which makes good sense. Other origin would have produced other components/factors with other scores. No, most of the time you may not play with origin - the locus of "typical respondent" or of "zero-level trait" - as you fancy to play.) To sum up, if the aim of the composite construct is to reflect respondent positions relative some "zero" or typical locus but the variables hardly at all correlate, some sort of spatial distance from that origin, and not mean (or sum), weighted or unweighted, should be chosen. Well, the mean (sum) will make sense if you decide to view the (uncorrelated) variables as alternative modes to measure the same thing. This way you are deliberately ignoring the variables' different nature. In other words, you consciously leave Fig. 2 in favour of Fig. 1: you "forget" that the variables are independent. Then - do sum or average. For example, score on "material welfare" and on "emotional welfare" could be averaged, likewise scores on "spatial IQ" and on "verbal IQ". This type of purely pragmatic, not approved satistically composites are called battery indices (a collection of tests or questionnaires which measure unrelated things or correlated things whose correlations we ignore is called "battery"). Battery indices make sense only if the scores have same direction (such as both wealth and emotional health are seen as "better" pole). Their usefulness outside narrow ad hoc settings is limited. If the variables are in-between relations - they are considerably correlated still not strongly enough to see them as duplicates, alternatives, of each other, we often sum (or average) their values in a weighted manner. Then these weights should be carefully designed and they should reflect, this or that way, the correlations. This what we do, for example, by means of PCA or factor analysis (FA) where we specially compute component/factor scores. If your variables are themselves already component or factor scores (like the OP question here says) and they are correlated (because of oblique rotation), you may subject them (or directly the loading matrix) to the second-order PCA/FA to find the weights and get the second-order PC/factor that will serve the "composite index" for you. But if your component/factor scores were uncorrelated or weakly correlated, there is no statistical reason neither to sum them bluntly nor via inferring weights. Use some distance instead. The problem with distance is that it is always positive: you can say how much atypical a respondent is but cannot say if he is "above" or "below". But this is the price you have to pay for demanding a single index out from multi-trait space. If you want both deviation and sign in such space I would say you're too exigent. In the last point, the OP asks whether it is right to take only the score of one, strongest variable in respect to its variance - 1st principal component in this instance - as the only proxy, for the "index". It makes sense if that PC is much stronger than the rest PCs. Though one might ask then "if it is so much stronger, why didn't you extract/retain just it sole?".
Creating a single index from several principal components or factors retained from PCA/FA This answer is deliberately non-mathematical and is oriented towards non-statistician psychologist (say) who inquires whether he may sum/average factor scores of different factors to obtain a "composi
14,960
Creating a single index from several principal components or factors retained from PCA/FA
Creating composite index using PCA from time series links to http://www.cup.ualberta.ca/wp-content/uploads/2013/04/SEICUPWebsite_10April13.pdf. In that article on page 19, the authors mention a way to create a Non-Standardised Index (NSI) by using the proportion of variation explained by each factor to the total variation explained by the chosen factors. This NSI was then normalised.
Creating a single index from several principal components or factors retained from PCA/FA
Creating composite index using PCA from time series links to http://www.cup.ualberta.ca/wp-content/uploads/2013/04/SEICUPWebsite_10April13.pdf. In that article on page 19, the authors mention a way t
Creating a single index from several principal components or factors retained from PCA/FA Creating composite index using PCA from time series links to http://www.cup.ualberta.ca/wp-content/uploads/2013/04/SEICUPWebsite_10April13.pdf. In that article on page 19, the authors mention a way to create a Non-Standardised Index (NSI) by using the proportion of variation explained by each factor to the total variation explained by the chosen factors. This NSI was then normalised.
Creating a single index from several principal components or factors retained from PCA/FA Creating composite index using PCA from time series links to http://www.cup.ualberta.ca/wp-content/uploads/2013/04/SEICUPWebsite_10April13.pdf. In that article on page 19, the authors mention a way t
14,961
Under exactly what conditions is ridge regression able to provide an improvement over ordinary least squares regression?
The answer to both 1 and 2 is no, but care is needed in interpreting the existence theorem. Variance of Ridge Estimator Let $\hat{\beta^*}$ be the ridge estimate under penalty $k$, and let $\beta$ be the true parameter for the model $Y = X \beta + \epsilon$. Let $\lambda_1, \dotsc, \lambda_p$ be the eigenvalues of $X^T X$. From Hoerl & Kennard equations 4.2-4.5, the risk, (in terms of the expected $L^2$ norm of the error) is $$ \begin{align*} E \left( \left[ \hat{\beta^*} - \beta \right]^T \left[ \hat{\beta^*} - \beta \right] \right)& = \sigma^2 \sum_{j=1}^p \lambda_j/ \left( \lambda_j +k \right)^2 + k^2 \beta^T \left( X^T X + k \mathbf{I}_p \right)^{-2} \beta \\ & = \gamma_1 (k) + \gamma_2(k) \\ & = R(k) \end{align*} $$ where as far as I can tell, $\left( X^T X + k \mathbf{I}_p \right)^{-2} = \left( X^T X + k \mathbf{I}_p \right)^{-1} \left( X^T X + k \mathbf{I}_p \right)^{-1}.$ They remark that $\gamma_1$ has the interpretation of the variance of the inner product of $\hat{\beta^*} - \beta$, while $\gamma_2$ is the inner product of the bias. Supposing $X^T X = \mathbf{I}_p$, then $$R(k) = \frac{p \sigma^2 + k^2 \beta^T \beta}{(1+k)^2}.$$ Let $$R^\prime (k) = 2\frac{k(1+k)\beta^T \beta - (p\sigma^2 + k^2 \beta^T \beta)}{(1+k)^3}$$ be the derivative of the risk w/r/t $k$. Since $\lim_{k \rightarrow 0^+} R^\prime (k) = -2p \sigma^2 < 0$, we conclude that there is some $k^*>0$ such that $R(k^*)<R(0)$. The authors remark that orthogonality is the best that you can hope for in terms of the risk at $k=0$, and that as the condition number of $X^T X$ increases, $\lim_{k \rightarrow 0^+} R^\prime (k)$ approaches $- \infty$. Comment There appears to be a paradox here, in that if $p=1$ and $X$ is constant, then we are just estimating the mean of a sequence of Normal$(\beta, \sigma^2)$ variables, and we know the the vanilla unbiased estimate is admissible in this case. This is resolved by noticing that the above reasoning merely provides that a minimizing value of $k$ exists for fixed $\beta^T \beta$. But for any $k$, we can make the risk explode by making $\beta^T \beta$ large, so this argument alone does not show admissibility for the ridge estimate. Why is ridge regression usually recommended only in the case of correlated predictors? H&K's risk derivation shows that if we think that $\beta ^T \beta$ is small, and if the design $X^T X$ is nearly-singular, then we can achieve large reductions in the risk of the estimate. I think ridge regression isn't used ubiquitously because the OLS estimate is a safe default, and that the invariance and unbiasedness properties are attractive. When it fails, it fails honestly--your covariance matrix explodes. There is also perhaps a philosophical/inferential point, that if your design is nearly singular, and you have observational data, then the interpretation of $\beta$ as giving changes in $E Y$ for unit changes in $X$ is suspect--the large covariance matrix is a symptom of that. But if your goal is solely prediction, the inferential concerns no longer hold, and you have a strong argument for using some sort of shrinkage estimator.
Under exactly what conditions is ridge regression able to provide an improvement over ordinary least
The answer to both 1 and 2 is no, but care is needed in interpreting the existence theorem. Variance of Ridge Estimator Let $\hat{\beta^*}$ be the ridge estimate under penalty $k$, and let $\beta$ be
Under exactly what conditions is ridge regression able to provide an improvement over ordinary least squares regression? The answer to both 1 and 2 is no, but care is needed in interpreting the existence theorem. Variance of Ridge Estimator Let $\hat{\beta^*}$ be the ridge estimate under penalty $k$, and let $\beta$ be the true parameter for the model $Y = X \beta + \epsilon$. Let $\lambda_1, \dotsc, \lambda_p$ be the eigenvalues of $X^T X$. From Hoerl & Kennard equations 4.2-4.5, the risk, (in terms of the expected $L^2$ norm of the error) is $$ \begin{align*} E \left( \left[ \hat{\beta^*} - \beta \right]^T \left[ \hat{\beta^*} - \beta \right] \right)& = \sigma^2 \sum_{j=1}^p \lambda_j/ \left( \lambda_j +k \right)^2 + k^2 \beta^T \left( X^T X + k \mathbf{I}_p \right)^{-2} \beta \\ & = \gamma_1 (k) + \gamma_2(k) \\ & = R(k) \end{align*} $$ where as far as I can tell, $\left( X^T X + k \mathbf{I}_p \right)^{-2} = \left( X^T X + k \mathbf{I}_p \right)^{-1} \left( X^T X + k \mathbf{I}_p \right)^{-1}.$ They remark that $\gamma_1$ has the interpretation of the variance of the inner product of $\hat{\beta^*} - \beta$, while $\gamma_2$ is the inner product of the bias. Supposing $X^T X = \mathbf{I}_p$, then $$R(k) = \frac{p \sigma^2 + k^2 \beta^T \beta}{(1+k)^2}.$$ Let $$R^\prime (k) = 2\frac{k(1+k)\beta^T \beta - (p\sigma^2 + k^2 \beta^T \beta)}{(1+k)^3}$$ be the derivative of the risk w/r/t $k$. Since $\lim_{k \rightarrow 0^+} R^\prime (k) = -2p \sigma^2 < 0$, we conclude that there is some $k^*>0$ such that $R(k^*)<R(0)$. The authors remark that orthogonality is the best that you can hope for in terms of the risk at $k=0$, and that as the condition number of $X^T X$ increases, $\lim_{k \rightarrow 0^+} R^\prime (k)$ approaches $- \infty$. Comment There appears to be a paradox here, in that if $p=1$ and $X$ is constant, then we are just estimating the mean of a sequence of Normal$(\beta, \sigma^2)$ variables, and we know the the vanilla unbiased estimate is admissible in this case. This is resolved by noticing that the above reasoning merely provides that a minimizing value of $k$ exists for fixed $\beta^T \beta$. But for any $k$, we can make the risk explode by making $\beta^T \beta$ large, so this argument alone does not show admissibility for the ridge estimate. Why is ridge regression usually recommended only in the case of correlated predictors? H&K's risk derivation shows that if we think that $\beta ^T \beta$ is small, and if the design $X^T X$ is nearly-singular, then we can achieve large reductions in the risk of the estimate. I think ridge regression isn't used ubiquitously because the OLS estimate is a safe default, and that the invariance and unbiasedness properties are attractive. When it fails, it fails honestly--your covariance matrix explodes. There is also perhaps a philosophical/inferential point, that if your design is nearly singular, and you have observational data, then the interpretation of $\beta$ as giving changes in $E Y$ for unit changes in $X$ is suspect--the large covariance matrix is a symptom of that. But if your goal is solely prediction, the inferential concerns no longer hold, and you have a strong argument for using some sort of shrinkage estimator.
Under exactly what conditions is ridge regression able to provide an improvement over ordinary least The answer to both 1 and 2 is no, but care is needed in interpreting the existence theorem. Variance of Ridge Estimator Let $\hat{\beta^*}$ be the ridge estimate under penalty $k$, and let $\beta$ be
14,962
Methods in R or Python to perform feature selection in unsupervised learning [closed]
It's a year old but I still feel it is relevant, so I just wanted to share my python implementation of Principal Feature Analysis (PFA) as proposed in the paper that Charles linked to in his answer. from sklearn.decomposition import PCA from sklearn.cluster import KMeans from collections import defaultdict from sklearn.metrics.pairwise import euclidean_distances from sklearn.preprocessing import StandardScaler class PFA(object): def __init__(self, n_features, q=None): self.q = q self.n_features = n_features def fit(self, X): if not self.q: self.q = X.shape[1] sc = StandardScaler() X = sc.fit_transform(X) pca = PCA(n_components=self.q).fit(X) A_q = pca.components_.T kmeans = KMeans(n_clusters=self.n_features).fit(A_q) clusters = kmeans.predict(A_q) cluster_centers = kmeans.cluster_centers_ dists = defaultdict(list) for i, c in enumerate(clusters): dist = euclidean_distances([A_q[i, :]], [cluster_centers[c, :]])[0][0] dists[c].append((i, dist)) self.indices_ = [sorted(f, key=lambda x: x[1])[0][0] for f in dists.values()] self.features_ = X[:, self.indices_] You can use it like this: import numpy as np X = np.random.random((1000,1000)) pfa = PFA(n_features=10) pfa.fit(X) # To get the transformed matrix X = pfa.features_ # To get the column indices of the kept features column_indices = pfa.indices_ This is strictly following the described algorithm from the article. I think the method has promise, but honestly I don't think it's the most robust approach to unsupervised feature selection. I'll post an update if I come up with something better.
Methods in R or Python to perform feature selection in unsupervised learning [closed]
It's a year old but I still feel it is relevant, so I just wanted to share my python implementation of Principal Feature Analysis (PFA) as proposed in the paper that Charles linked to in his answer. f
Methods in R or Python to perform feature selection in unsupervised learning [closed] It's a year old but I still feel it is relevant, so I just wanted to share my python implementation of Principal Feature Analysis (PFA) as proposed in the paper that Charles linked to in his answer. from sklearn.decomposition import PCA from sklearn.cluster import KMeans from collections import defaultdict from sklearn.metrics.pairwise import euclidean_distances from sklearn.preprocessing import StandardScaler class PFA(object): def __init__(self, n_features, q=None): self.q = q self.n_features = n_features def fit(self, X): if not self.q: self.q = X.shape[1] sc = StandardScaler() X = sc.fit_transform(X) pca = PCA(n_components=self.q).fit(X) A_q = pca.components_.T kmeans = KMeans(n_clusters=self.n_features).fit(A_q) clusters = kmeans.predict(A_q) cluster_centers = kmeans.cluster_centers_ dists = defaultdict(list) for i, c in enumerate(clusters): dist = euclidean_distances([A_q[i, :]], [cluster_centers[c, :]])[0][0] dists[c].append((i, dist)) self.indices_ = [sorted(f, key=lambda x: x[1])[0][0] for f in dists.values()] self.features_ = X[:, self.indices_] You can use it like this: import numpy as np X = np.random.random((1000,1000)) pfa = PFA(n_features=10) pfa.fit(X) # To get the transformed matrix X = pfa.features_ # To get the column indices of the kept features column_indices = pfa.indices_ This is strictly following the described algorithm from the article. I think the method has promise, but honestly I don't think it's the most robust approach to unsupervised feature selection. I'll post an update if I come up with something better.
Methods in R or Python to perform feature selection in unsupervised learning [closed] It's a year old but I still feel it is relevant, so I just wanted to share my python implementation of Principal Feature Analysis (PFA) as proposed in the paper that Charles linked to in his answer. f
14,963
Methods in R or Python to perform feature selection in unsupervised learning [closed]
The sparcl package in R performs sparse hierarchical and sparse K-means clustering. This may be useful. http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2930825/
Methods in R or Python to perform feature selection in unsupervised learning [closed]
The sparcl package in R performs sparse hierarchical and sparse K-means clustering. This may be useful. http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2930825/
Methods in R or Python to perform feature selection in unsupervised learning [closed] The sparcl package in R performs sparse hierarchical and sparse K-means clustering. This may be useful. http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2930825/
Methods in R or Python to perform feature selection in unsupervised learning [closed] The sparcl package in R performs sparse hierarchical and sparse K-means clustering. This may be useful. http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2930825/
14,964
Methods in R or Python to perform feature selection in unsupervised learning [closed]
Principal Feature Analysis looks to be a solution to unsupervised feature selection. It's described in this paper.
Methods in R or Python to perform feature selection in unsupervised learning [closed]
Principal Feature Analysis looks to be a solution to unsupervised feature selection. It's described in this paper.
Methods in R or Python to perform feature selection in unsupervised learning [closed] Principal Feature Analysis looks to be a solution to unsupervised feature selection. It's described in this paper.
Methods in R or Python to perform feature selection in unsupervised learning [closed] Principal Feature Analysis looks to be a solution to unsupervised feature selection. It's described in this paper.
14,965
Methods in R or Python to perform feature selection in unsupervised learning [closed]
I've found a link wich could be useful, those are matlab implementations, they may work out for you http://www.cad.zju.edu.cn/home/dengcai/Data/MCFS.html it's a multicluster feature selection method, you can find strong foundation about it in recent papers Let me know if it works for you
Methods in R or Python to perform feature selection in unsupervised learning [closed]
I've found a link wich could be useful, those are matlab implementations, they may work out for you http://www.cad.zju.edu.cn/home/dengcai/Data/MCFS.html it's a multicluster feature selection method,
Methods in R or Python to perform feature selection in unsupervised learning [closed] I've found a link wich could be useful, those are matlab implementations, they may work out for you http://www.cad.zju.edu.cn/home/dengcai/Data/MCFS.html it's a multicluster feature selection method, you can find strong foundation about it in recent papers Let me know if it works for you
Methods in R or Python to perform feature selection in unsupervised learning [closed] I've found a link wich could be useful, those are matlab implementations, they may work out for you http://www.cad.zju.edu.cn/home/dengcai/Data/MCFS.html it's a multicluster feature selection method,
14,966
Methods in R or Python to perform feature selection in unsupervised learning [closed]
There are many options available in R. A nice place to look is the caret package which provides a nice interface to many other packages and options. You can take a look at the website here. There are many options out there, but I will illustrate one. Here is an example of using a simple filter using the built into R "mtcars" datasets (shown below). mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Now some code setup (loading packages, etc.): # setup a parallel environment library(doParallel) cl <- makeCluster(2) # number of cores to use registerDoParallel(cl) library(caret) And we can fit a simple model to select variables: fit1 <- sbf(mtcars[, -1], mtcars[, 1], sbfControl = sbfControl(functions = rfSBF, method = "repeatedcv", repeats = 10) ) Viewing the results, we get: fit1 Selection By Filter Outer resampling method: Cross-Validated (10 fold, repeated 10 times) Resampling performance: RMSE Rsquared RMSESD RsquaredSD 2.266 0.9224 0.8666 0.1523 Using the training set, 7 variables were selected: cyl, disp, hp, wt, vs... During resampling, the top 5 selected variables (out of a possible 9): am (100%), cyl (100%), disp (100%), gear (100%), vs (100%) On average, 7 variables were selected (min = 5, max = 9) Finally we can plot the selected variables (in fit1$optVariables ) against the outcome, mpg: library(ggplot2) library(gridExtra) do.call(grid.arrange, lapply(fit1$optVariables, function(v) { ggplot(mtcars, aes_string(x = v, y = "mpg")) + geom_jitter() })) Resulting in this graph:
Methods in R or Python to perform feature selection in unsupervised learning [closed]
There are many options available in R. A nice place to look is the caret package which provides a nice interface to many other packages and options. You can take a look at the website here. There a
Methods in R or Python to perform feature selection in unsupervised learning [closed] There are many options available in R. A nice place to look is the caret package which provides a nice interface to many other packages and options. You can take a look at the website here. There are many options out there, but I will illustrate one. Here is an example of using a simple filter using the built into R "mtcars" datasets (shown below). mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Now some code setup (loading packages, etc.): # setup a parallel environment library(doParallel) cl <- makeCluster(2) # number of cores to use registerDoParallel(cl) library(caret) And we can fit a simple model to select variables: fit1 <- sbf(mtcars[, -1], mtcars[, 1], sbfControl = sbfControl(functions = rfSBF, method = "repeatedcv", repeats = 10) ) Viewing the results, we get: fit1 Selection By Filter Outer resampling method: Cross-Validated (10 fold, repeated 10 times) Resampling performance: RMSE Rsquared RMSESD RsquaredSD 2.266 0.9224 0.8666 0.1523 Using the training set, 7 variables were selected: cyl, disp, hp, wt, vs... During resampling, the top 5 selected variables (out of a possible 9): am (100%), cyl (100%), disp (100%), gear (100%), vs (100%) On average, 7 variables were selected (min = 5, max = 9) Finally we can plot the selected variables (in fit1$optVariables ) against the outcome, mpg: library(ggplot2) library(gridExtra) do.call(grid.arrange, lapply(fit1$optVariables, function(v) { ggplot(mtcars, aes_string(x = v, y = "mpg")) + geom_jitter() })) Resulting in this graph:
Methods in R or Python to perform feature selection in unsupervised learning [closed] There are many options available in R. A nice place to look is the caret package which provides a nice interface to many other packages and options. You can take a look at the website here. There a
14,967
Methods in R or Python to perform feature selection in unsupervised learning [closed]
The nsprcomp R package provides methods for sparse Principal Component Analysis, which could suit your needs. For example, if you believe your features are generally correlated linearly, and want to select the top five, you could run sparse PCA with a max of five features, and limit to the first principal component: m <- nsprcomp(x, scale.=T, k=5, ncomp=1) m$rotation[, 1] Alternatively, if you want to capture the orthogonal nature of features, you can select the top feature from each of the top five PCs, limiting each PC to one feature: m <- nsprcomp(x, scale.=T, k=1, ncomp=5) m$rotation An ensemble of these could be useful too; i.e., features that consistently come to the top across different methods are likely to explain a large amount of variance in the feature space. Having played around with nsprcomp a bit, it seems like the first two methods raise ~1/2 of the same features to the top. That said, optimizing this process may be an empirical effort.
Methods in R or Python to perform feature selection in unsupervised learning [closed]
The nsprcomp R package provides methods for sparse Principal Component Analysis, which could suit your needs. For example, if you believe your features are generally correlated linearly, and want to
Methods in R or Python to perform feature selection in unsupervised learning [closed] The nsprcomp R package provides methods for sparse Principal Component Analysis, which could suit your needs. For example, if you believe your features are generally correlated linearly, and want to select the top five, you could run sparse PCA with a max of five features, and limit to the first principal component: m <- nsprcomp(x, scale.=T, k=5, ncomp=1) m$rotation[, 1] Alternatively, if you want to capture the orthogonal nature of features, you can select the top feature from each of the top five PCs, limiting each PC to one feature: m <- nsprcomp(x, scale.=T, k=1, ncomp=5) m$rotation An ensemble of these could be useful too; i.e., features that consistently come to the top across different methods are likely to explain a large amount of variance in the feature space. Having played around with nsprcomp a bit, it seems like the first two methods raise ~1/2 of the same features to the top. That said, optimizing this process may be an empirical effort.
Methods in R or Python to perform feature selection in unsupervised learning [closed] The nsprcomp R package provides methods for sparse Principal Component Analysis, which could suit your needs. For example, if you believe your features are generally correlated linearly, and want to
14,968
Kernel Bandwidth: Scott's vs. Silverman's rules
The comments in the code seem to end up defining the two essentially identically (aside a relatively small difference in the constant). Both are of the form $cAn^{-1/5}$, both with what looks like the same $A$ (estimate of scale), and $c$'s very close to 1 (close relative to the typical uncertainty in the estimate of the optimum bandwidth). [The binwdith estimate that more usually seems to be associated with Scott is the one from his 1979 paper[1] ($3.49 s n^{-1/3}$) -- e.g. see Wikipedia - scroll down a little - or R's nclass.scott.] The 1.059 in what the code calls the "Scott estimate" is in the (prior) book by Silverman (see p45 of the Silverman reference at your link -- Scott's derivation of it is on p130-131 of the book they refer to). It comes from a normal-theory estimate. The optimum bandwidth (in integrated mean square error terms) is a function of of the integrated squared second derivative, and $1.059\sigma$ comes out of that calculation for a normal, but in many cases that's a good deal wider than is optimum for other distributions. The $A$ term is an estimate of $\sigma$ (sort of a robustified estimate, in a way that reduces the tendency for it to be too large if there are outliers/skewness/heavy tails). See eq 3.30 on p47, justified on p46-7. For similar reasons to those I suggested before, Silverman goes on to suggest reducing 1.059 (in fact he actually uses 1.06 throughout, not 1.059 -- as does Scott in his book). He chooses a reduced value that loses no more than 10% efficiency on IMSE at the normal, which is where the 0.9 comes from. So both those binwidths are based on the IMSE-optimal binwidth at the normal, one right at the optimum, the other (about 15% smaller, to get within 90% of the efficiency of the optimum at the normal). [I'd call both of them "Silverman" estimates. I have no idea why they name the 1.059 one for Scott.] In my opinion, both are far too large. I don't use histograms to get IMSE-optimal estimates of the density. If that (obtaining estimates of the density that are optimal in the IMSE sense) was what I wanted to do, I wouldn't want to use histograms for that purpose. Histograms should be erring on the noisier side (let the eye do the necessary smoothing). I nearly always double (or more) the default number of bins these kinds of rules give. So I wouldn't use 1.06 or 0.9, I'd tend to use something around 0.5, maybe less at really large sample sizes. There's really very little to choose between them, since they both give far too few bins to be much use at finding what's going on in the data (on which, at least at small sample sizes, see here. [1]: Scott, D.W. (1979), "On optimal and data-based histograms," Biometrika, 66, 605-610.
Kernel Bandwidth: Scott's vs. Silverman's rules
The comments in the code seem to end up defining the two essentially identically (aside a relatively small difference in the constant). Both are of the form $cAn^{-1/5}$, both with what looks like the
Kernel Bandwidth: Scott's vs. Silverman's rules The comments in the code seem to end up defining the two essentially identically (aside a relatively small difference in the constant). Both are of the form $cAn^{-1/5}$, both with what looks like the same $A$ (estimate of scale), and $c$'s very close to 1 (close relative to the typical uncertainty in the estimate of the optimum bandwidth). [The binwdith estimate that more usually seems to be associated with Scott is the one from his 1979 paper[1] ($3.49 s n^{-1/3}$) -- e.g. see Wikipedia - scroll down a little - or R's nclass.scott.] The 1.059 in what the code calls the "Scott estimate" is in the (prior) book by Silverman (see p45 of the Silverman reference at your link -- Scott's derivation of it is on p130-131 of the book they refer to). It comes from a normal-theory estimate. The optimum bandwidth (in integrated mean square error terms) is a function of of the integrated squared second derivative, and $1.059\sigma$ comes out of that calculation for a normal, but in many cases that's a good deal wider than is optimum for other distributions. The $A$ term is an estimate of $\sigma$ (sort of a robustified estimate, in a way that reduces the tendency for it to be too large if there are outliers/skewness/heavy tails). See eq 3.30 on p47, justified on p46-7. For similar reasons to those I suggested before, Silverman goes on to suggest reducing 1.059 (in fact he actually uses 1.06 throughout, not 1.059 -- as does Scott in his book). He chooses a reduced value that loses no more than 10% efficiency on IMSE at the normal, which is where the 0.9 comes from. So both those binwidths are based on the IMSE-optimal binwidth at the normal, one right at the optimum, the other (about 15% smaller, to get within 90% of the efficiency of the optimum at the normal). [I'd call both of them "Silverman" estimates. I have no idea why they name the 1.059 one for Scott.] In my opinion, both are far too large. I don't use histograms to get IMSE-optimal estimates of the density. If that (obtaining estimates of the density that are optimal in the IMSE sense) was what I wanted to do, I wouldn't want to use histograms for that purpose. Histograms should be erring on the noisier side (let the eye do the necessary smoothing). I nearly always double (or more) the default number of bins these kinds of rules give. So I wouldn't use 1.06 or 0.9, I'd tend to use something around 0.5, maybe less at really large sample sizes. There's really very little to choose between them, since they both give far too few bins to be much use at finding what's going on in the data (on which, at least at small sample sizes, see here. [1]: Scott, D.W. (1979), "On optimal and data-based histograms," Biometrika, 66, 605-610.
Kernel Bandwidth: Scott's vs. Silverman's rules The comments in the code seem to end up defining the two essentially identically (aside a relatively small difference in the constant). Both are of the form $cAn^{-1/5}$, both with what looks like the
14,969
Set seed before each code block or once per project?
It depends how you will run the code or if there is any code that is somewhat stochastic in that it draws random numbers in a random way. (An example of this is the permutation tests in our vegan package where we only continue permuting until we have amassed enough data to know whether a result is different from the stated Type I error tacking into account a Type II error rate.) Although even that shouldn't affect the draws... If the final script will only ever be run as a batch job or in its entirety and there are no stochastic draws from the pseudo-random number generator then it is safe to set a seed at the top of the script and run it in its entirety. If you want to step through code, perhaps rerunning blocks then you need a set.seed() call before each function call that will draw from the pseudo-random number generator. For my scientific papers I routinely go super defensive and set seeds prior to each code chunk; this allows for updates to the script at a later date that might need to be inserted into the existing script at any point - say to respond to reviewers' or co-authors' comments. Your results will hopefully not be contingent on a particular set of pseduo-random values, so the issue is being able to reproduce the exact values stated in a report or paper. Even though you might be super defensive and set a seed on each code chunk, you still may need to recreate the exact installation --- R version and package versions so recording those details is essential. To be extra safe you'll need to keep previous R versions and packages around for specific projects/papers. Indeed, many people do this.
Set seed before each code block or once per project?
It depends how you will run the code or if there is any code that is somewhat stochastic in that it draws random numbers in a random way. (An example of this is the permutation tests in our vegan pack
Set seed before each code block or once per project? It depends how you will run the code or if there is any code that is somewhat stochastic in that it draws random numbers in a random way. (An example of this is the permutation tests in our vegan package where we only continue permuting until we have amassed enough data to know whether a result is different from the stated Type I error tacking into account a Type II error rate.) Although even that shouldn't affect the draws... If the final script will only ever be run as a batch job or in its entirety and there are no stochastic draws from the pseudo-random number generator then it is safe to set a seed at the top of the script and run it in its entirety. If you want to step through code, perhaps rerunning blocks then you need a set.seed() call before each function call that will draw from the pseudo-random number generator. For my scientific papers I routinely go super defensive and set seeds prior to each code chunk; this allows for updates to the script at a later date that might need to be inserted into the existing script at any point - say to respond to reviewers' or co-authors' comments. Your results will hopefully not be contingent on a particular set of pseduo-random values, so the issue is being able to reproduce the exact values stated in a report or paper. Even though you might be super defensive and set a seed on each code chunk, you still may need to recreate the exact installation --- R version and package versions so recording those details is essential. To be extra safe you'll need to keep previous R versions and packages around for specific projects/papers. Indeed, many people do this.
Set seed before each code block or once per project? It depends how you will run the code or if there is any code that is somewhat stochastic in that it draws random numbers in a random way. (An example of this is the permutation tests in our vegan pack
14,970
Under which conditions do Bayesian and frequentist point estimators coincide?
The question is interesting but somewhat hopeless unless the notion of frequentist estimator is made precise. It is definitely not the one set in the question $$\hat x(\,. ) = \text{argmin} \; \mathbb{E} \left( L(x,\hat x(Y)) \; | \; x \right)$$ since the answer to the minimisation is $\hat{x}(y)=x$ for all $y$'s as pointed out in Programmer2134's answer. The fundamental issue is that there is no single frequentist estimator for an estimation problem, without introducing supplementary constraints or classes of estimators. Without those, all Bayes estimators are also frequentist estimators. As pointed out in the comments, unbiasedness may be such a constraint, in which case Bayes estimators are excluded. But this frequentist notion clashes with other frequentist notions such as admissibility, since the James-Stein phenomenon demonstrated that unbiased estimators may be inadmissible (depending on the loss function and on the dimension of the problem); invariance under reparameterisation, since unbiasedness does not keep under transforms. Plus unbiasedness only applies to a restricted class of estimation problems. By this, I mean that the class of unbiased estimators of a certain parameter $\theta$ or of a transform $h(\theta)$ is most of the time empty. Speaking of admissibility, another frequentist notion, there exist settings for which the only admissible estimators are Bayes estimators and conversely. This type of settings relates to the complete class theorems established by Abraham Wald in the 1950's. (The same applies to the best invariant estimators which are Bayes under the appropriate right Haar measure.)
Under which conditions do Bayesian and frequentist point estimators coincide?
The question is interesting but somewhat hopeless unless the notion of frequentist estimator is made precise. It is definitely not the one set in the question $$\hat x(\,. ) = \text{argmin} \; \mathbb
Under which conditions do Bayesian and frequentist point estimators coincide? The question is interesting but somewhat hopeless unless the notion of frequentist estimator is made precise. It is definitely not the one set in the question $$\hat x(\,. ) = \text{argmin} \; \mathbb{E} \left( L(x,\hat x(Y)) \; | \; x \right)$$ since the answer to the minimisation is $\hat{x}(y)=x$ for all $y$'s as pointed out in Programmer2134's answer. The fundamental issue is that there is no single frequentist estimator for an estimation problem, without introducing supplementary constraints or classes of estimators. Without those, all Bayes estimators are also frequentist estimators. As pointed out in the comments, unbiasedness may be such a constraint, in which case Bayes estimators are excluded. But this frequentist notion clashes with other frequentist notions such as admissibility, since the James-Stein phenomenon demonstrated that unbiased estimators may be inadmissible (depending on the loss function and on the dimension of the problem); invariance under reparameterisation, since unbiasedness does not keep under transforms. Plus unbiasedness only applies to a restricted class of estimation problems. By this, I mean that the class of unbiased estimators of a certain parameter $\theta$ or of a transform $h(\theta)$ is most of the time empty. Speaking of admissibility, another frequentist notion, there exist settings for which the only admissible estimators are Bayes estimators and conversely. This type of settings relates to the complete class theorems established by Abraham Wald in the 1950's. (The same applies to the best invariant estimators which are Bayes under the appropriate right Haar measure.)
Under which conditions do Bayesian and frequentist point estimators coincide? The question is interesting but somewhat hopeless unless the notion of frequentist estimator is made precise. It is definitely not the one set in the question $$\hat x(\,. ) = \text{argmin} \; \mathbb
14,971
Under which conditions do Bayesian and frequentist point estimators coincide?
In general, frequentist and Bayesian estimators do not coincide, unless you use a degenerate flat prior. The main reason is this: Frequentist estimators often strive to be unbiased. For example, frequentists often try to find the minimum variance unbiased estimator (http://en.wikipedia.org/wiki/Minimum-variance_unbiased_estimator). Meanwhile, all non-degenerate Bayes estimators are biased (in the frequentist sense of bias). See, for example, http://www.stat.washington.edu/~hoff/courses/581/LectureNotes/bayes.pdf, Theorem 5. To summarize: Most of the popular frequentist estimators strive to be unbiased, while all Bayes estimators are biased. Thus, Bayes and frequentist estimators rarely coincide.
Under which conditions do Bayesian and frequentist point estimators coincide?
In general, frequentist and Bayesian estimators do not coincide, unless you use a degenerate flat prior. The main reason is this: Frequentist estimators often strive to be unbiased. For example, frequ
Under which conditions do Bayesian and frequentist point estimators coincide? In general, frequentist and Bayesian estimators do not coincide, unless you use a degenerate flat prior. The main reason is this: Frequentist estimators often strive to be unbiased. For example, frequentists often try to find the minimum variance unbiased estimator (http://en.wikipedia.org/wiki/Minimum-variance_unbiased_estimator). Meanwhile, all non-degenerate Bayes estimators are biased (in the frequentist sense of bias). See, for example, http://www.stat.washington.edu/~hoff/courses/581/LectureNotes/bayes.pdf, Theorem 5. To summarize: Most of the popular frequentist estimators strive to be unbiased, while all Bayes estimators are biased. Thus, Bayes and frequentist estimators rarely coincide.
Under which conditions do Bayesian and frequentist point estimators coincide? In general, frequentist and Bayesian estimators do not coincide, unless you use a degenerate flat prior. The main reason is this: Frequentist estimators often strive to be unbiased. For example, frequ
14,972
Under which conditions do Bayesian and frequentist point estimators coincide?
This is not a full answer, but while these two $\text{argmin}$'s look very similar, they are fundamentally different in a way: the Bayesian one minimizes the expression with respect to a single value (that is, the value of $\hat x(y)$, depending on $y$). But the Frequentist one has to minimize the loss function with respect to a single value for every value that $x$ could take, without knowing $x$. This is because the minimum of the function $f(x,\hat x)=E(L(x-\hat x(Y))|x)$ depends on $x$, even though we have to minimize it without knowing $x$. (note that if we would simply minimize $f(x, \hat x)$ w.r.t. $\hat x$, we would simply get the minimizing value of $\hat x = x$.) The Frequentist problem is therefore undefined. I am not sure whether it is even possible to make it well-defined.
Under which conditions do Bayesian and frequentist point estimators coincide?
This is not a full answer, but while these two $\text{argmin}$'s look very similar, they are fundamentally different in a way: the Bayesian one minimizes the expression with respect to a single value
Under which conditions do Bayesian and frequentist point estimators coincide? This is not a full answer, but while these two $\text{argmin}$'s look very similar, they are fundamentally different in a way: the Bayesian one minimizes the expression with respect to a single value (that is, the value of $\hat x(y)$, depending on $y$). But the Frequentist one has to minimize the loss function with respect to a single value for every value that $x$ could take, without knowing $x$. This is because the minimum of the function $f(x,\hat x)=E(L(x-\hat x(Y))|x)$ depends on $x$, even though we have to minimize it without knowing $x$. (note that if we would simply minimize $f(x, \hat x)$ w.r.t. $\hat x$, we would simply get the minimizing value of $\hat x = x$.) The Frequentist problem is therefore undefined. I am not sure whether it is even possible to make it well-defined.
Under which conditions do Bayesian and frequentist point estimators coincide? This is not a full answer, but while these two $\text{argmin}$'s look very similar, they are fundamentally different in a way: the Bayesian one minimizes the expression with respect to a single value
14,973
Under which conditions do Bayesian and frequentist point estimators coincide?
There may exist no answer to this question. An alternative could be to ask for methods to determine the two estimates efficiently for any problem at hand. The Bayesian methods are pretty close to this ideal. However, even though minimax methods could be used to determine the frequentist point estimate, in general, the application of the minimax method remains difficult, and tends not to be used in practice. An other alternative would be to rephrase the question as to the conditions under which Bayesian and frequentist estimators provide “consistent” results and try to identify methods to efficiently calculate those estimators. Here "consistent" is taken to imply that Bayesian and frequentist estimators are derived from a common theory and that the same criterion of optimality is used for both estimators. This is very different from trying to oppose Bayesian and frequentist statistics, and may render the above question superfluous. One possible approach is to aim, both for the frequentist case and the Bayesian case, at decision sets that minimize the loss for a given size, i.e., as proposed by Schafer, Chad M, and Philip B Stark. "Constructing confidence regions of optimal expected size." Journal of the American Statistical Association 104.487 (2009): 1080-1089. It turns out that this is possible - both for the frequentist and the Bayesian case - by including by preference observations and parameters with large pointwise mutual information. The decision sets will not be identical, since the question being asked is different: Independent of what is the true parameter, limit the risk of making wrong decisions (the frequentist view) Given some observations, limit the risk of including wrong parameters into the decision set (Bayesian view) However the sets will overlap largely and become identical in some situations, if flat priors are used. The idea is discussed in more detail together with an efficient impementation in Bartels, Christian (2015): Generic and consistent confidence and credible regions. figshare. https://doi.org/10.6084/m9.figshare.1528163 For informative priors, the decision sets deviate more (as is commonly known and was pointed out in the question and in answers above). However within the consistent framework, one obtains frequentist tests, that guarantee the desired frequentist coverage, but take into account prior knowledge. Bartels, Christian (2017): Using prior knowledge in frequentist tests. figshare. https://doi.org/10.6084/m9.figshare.4819597 The proposed methods still lack an efficient implementation of marginaization.
Under which conditions do Bayesian and frequentist point estimators coincide?
There may exist no answer to this question. An alternative could be to ask for methods to determine the two estimates efficiently for any problem at hand. The Bayesian methods are pretty close to thi
Under which conditions do Bayesian and frequentist point estimators coincide? There may exist no answer to this question. An alternative could be to ask for methods to determine the two estimates efficiently for any problem at hand. The Bayesian methods are pretty close to this ideal. However, even though minimax methods could be used to determine the frequentist point estimate, in general, the application of the minimax method remains difficult, and tends not to be used in practice. An other alternative would be to rephrase the question as to the conditions under which Bayesian and frequentist estimators provide “consistent” results and try to identify methods to efficiently calculate those estimators. Here "consistent" is taken to imply that Bayesian and frequentist estimators are derived from a common theory and that the same criterion of optimality is used for both estimators. This is very different from trying to oppose Bayesian and frequentist statistics, and may render the above question superfluous. One possible approach is to aim, both for the frequentist case and the Bayesian case, at decision sets that minimize the loss for a given size, i.e., as proposed by Schafer, Chad M, and Philip B Stark. "Constructing confidence regions of optimal expected size." Journal of the American Statistical Association 104.487 (2009): 1080-1089. It turns out that this is possible - both for the frequentist and the Bayesian case - by including by preference observations and parameters with large pointwise mutual information. The decision sets will not be identical, since the question being asked is different: Independent of what is the true parameter, limit the risk of making wrong decisions (the frequentist view) Given some observations, limit the risk of including wrong parameters into the decision set (Bayesian view) However the sets will overlap largely and become identical in some situations, if flat priors are used. The idea is discussed in more detail together with an efficient impementation in Bartels, Christian (2015): Generic and consistent confidence and credible regions. figshare. https://doi.org/10.6084/m9.figshare.1528163 For informative priors, the decision sets deviate more (as is commonly known and was pointed out in the question and in answers above). However within the consistent framework, one obtains frequentist tests, that guarantee the desired frequentist coverage, but take into account prior knowledge. Bartels, Christian (2017): Using prior knowledge in frequentist tests. figshare. https://doi.org/10.6084/m9.figshare.4819597 The proposed methods still lack an efficient implementation of marginaization.
Under which conditions do Bayesian and frequentist point estimators coincide? There may exist no answer to this question. An alternative could be to ask for methods to determine the two estimates efficiently for any problem at hand. The Bayesian methods are pretty close to thi
14,974
Pearson's residuals
The standard statistical model underlying analysis of contingency tables is to assume that (unconditional on the total count) the cell counts are independent Poisson random variables. So if you have an $n \times m$ contingency table, the statistical model used as a basis for analysis takes each cell count to have unconditional distribution: $$X_{i,j} \sim \text{Pois}(\mu_{i,j}).$$ Once you impose a total cell count for the contingency table, or a row or column count, the resulting conditional distributions of the cell counts then become multinomial. In any case, for a Poisson distribution we have $\mathbb{E}(X_{i,j}) = \mathbb{V}(X_{i,j}) = \mu_{i,j}$, so the standardised cell count is: $$\text{STD}(X_{i,j}) \equiv \frac{X_{i,j} - \mathbb{E}(X_{i,j})}{\sqrt{\mathbb{V}(X_{i,j})}} = \frac{X_{i,j} - \mu_{i,j}}{\sqrt{\mu_{i,j}}}.$$ So, what you're seeing in the formula you are enquiring about, is the standardised cell count, under the assumption that the cell counts have an (unconditional) Poisson distribution. From here it is common to test independence of the row and column variable in the data, and in this case you can use a test statistic that looks at the sum-of-squares of the above values (which is equivalent to the squared-norm of the vector of standardised values). The chi-squared test provides a p-value for this kind of test based on a large-sample approximation to the null distribution of the test statistic. It is usually applied in cases where none of the sell counts are too small.
Pearson's residuals
The standard statistical model underlying analysis of contingency tables is to assume that (unconditional on the total count) the cell counts are independent Poisson random variables. So if you have
Pearson's residuals The standard statistical model underlying analysis of contingency tables is to assume that (unconditional on the total count) the cell counts are independent Poisson random variables. So if you have an $n \times m$ contingency table, the statistical model used as a basis for analysis takes each cell count to have unconditional distribution: $$X_{i,j} \sim \text{Pois}(\mu_{i,j}).$$ Once you impose a total cell count for the contingency table, or a row or column count, the resulting conditional distributions of the cell counts then become multinomial. In any case, for a Poisson distribution we have $\mathbb{E}(X_{i,j}) = \mathbb{V}(X_{i,j}) = \mu_{i,j}$, so the standardised cell count is: $$\text{STD}(X_{i,j}) \equiv \frac{X_{i,j} - \mathbb{E}(X_{i,j})}{\sqrt{\mathbb{V}(X_{i,j})}} = \frac{X_{i,j} - \mu_{i,j}}{\sqrt{\mu_{i,j}}}.$$ So, what you're seeing in the formula you are enquiring about, is the standardised cell count, under the assumption that the cell counts have an (unconditional) Poisson distribution. From here it is common to test independence of the row and column variable in the data, and in this case you can use a test statistic that looks at the sum-of-squares of the above values (which is equivalent to the squared-norm of the vector of standardised values). The chi-squared test provides a p-value for this kind of test based on a large-sample approximation to the null distribution of the test statistic. It is usually applied in cases where none of the sell counts are too small.
Pearson's residuals The standard statistical model underlying analysis of contingency tables is to assume that (unconditional on the total count) the cell counts are independent Poisson random variables. So if you have
14,975
Pearson's residuals
In the context of goodness of fit, you may refer to this http://www.stat.yale.edu/Courses/1997-98/101/chigf.htm. If you want to know how the denominator got there, you will have to view the chi-squared here as a normal approximation to the binomial, for starters, which then can be extended to multinomials.
Pearson's residuals
In the context of goodness of fit, you may refer to this http://www.stat.yale.edu/Courses/1997-98/101/chigf.htm. If you want to know how the denominator got there, you will have to view the chi-square
Pearson's residuals In the context of goodness of fit, you may refer to this http://www.stat.yale.edu/Courses/1997-98/101/chigf.htm. If you want to know how the denominator got there, you will have to view the chi-squared here as a normal approximation to the binomial, for starters, which then can be extended to multinomials.
Pearson's residuals In the context of goodness of fit, you may refer to this http://www.stat.yale.edu/Courses/1997-98/101/chigf.htm. If you want to know how the denominator got there, you will have to view the chi-square
14,976
Finding the MLE for a univariate exponential Hawkes process
The Nelder-Mead simplex algorithm seems to work well.. It is implemented in Java by the Apache Commons Math library at https://commons.apache.org/math/ . I've also written a paper about the Hawkes processes at Point Process Models for Multivariate High-Frequency Irregularly Spaced Data . felix, using exp/log transforms seems to ensure positivity of the parameters. As for the small alpha thing, search the arxiv.org for a paper called "limit theorems for nearly unstable hawkes processes"
Finding the MLE for a univariate exponential Hawkes process
The Nelder-Mead simplex algorithm seems to work well.. It is implemented in Java by the Apache Commons Math library at https://commons.apache.org/math/ . I've also written a paper about the Hawkes pro
Finding the MLE for a univariate exponential Hawkes process The Nelder-Mead simplex algorithm seems to work well.. It is implemented in Java by the Apache Commons Math library at https://commons.apache.org/math/ . I've also written a paper about the Hawkes processes at Point Process Models for Multivariate High-Frequency Irregularly Spaced Data . felix, using exp/log transforms seems to ensure positivity of the parameters. As for the small alpha thing, search the arxiv.org for a paper called "limit theorems for nearly unstable hawkes processes"
Finding the MLE for a univariate exponential Hawkes process The Nelder-Mead simplex algorithm seems to work well.. It is implemented in Java by the Apache Commons Math library at https://commons.apache.org/math/ . I've also written a paper about the Hawkes pro
14,977
Finding the MLE for a univariate exponential Hawkes process
I solved this problem using the nlopt library. I found a number of the methods converged quite quickly.
Finding the MLE for a univariate exponential Hawkes process
I solved this problem using the nlopt library. I found a number of the methods converged quite quickly.
Finding the MLE for a univariate exponential Hawkes process I solved this problem using the nlopt library. I found a number of the methods converged quite quickly.
Finding the MLE for a univariate exponential Hawkes process I solved this problem using the nlopt library. I found a number of the methods converged quite quickly.
14,978
Finding the MLE for a univariate exponential Hawkes process
You could also do a simple maximization. In R: neg.loglik <- function(params, data, opt=TRUE) { mu <- params[1] alpha <- params[2] beta <- params[3] t <- sort(data) r <- rep(0,length(t)) for(i in 2:length(t)) { r[i] <- exp(-beta*(t[i]-t[i-1]))*(1+r[i-1]) } loglik <- -tail(t,1)*mu loglik <- loglik+alpha/beta*sum(exp(-beta*(tail(t,1)-t))-1) loglik <- loglik+sum(log(mu+alpha*r)) if(!opt) { return(list(negloglik=-loglik, mu=mu, alpha=alpha, beta=beta, t=t, r=r)) } else { return(-loglik) } } # insert your values for (mu, alpha, beta) in par # insert your times for data opt <- optim(par=c(1,2,3), fn=neg.loglik, data=data)
Finding the MLE for a univariate exponential Hawkes process
You could also do a simple maximization. In R: neg.loglik <- function(params, data, opt=TRUE) { mu <- params[1] alpha <- params[2] beta <- params[3] t <- sort(data) r <- rep(0,length(t)) f
Finding the MLE for a univariate exponential Hawkes process You could also do a simple maximization. In R: neg.loglik <- function(params, data, opt=TRUE) { mu <- params[1] alpha <- params[2] beta <- params[3] t <- sort(data) r <- rep(0,length(t)) for(i in 2:length(t)) { r[i] <- exp(-beta*(t[i]-t[i-1]))*(1+r[i-1]) } loglik <- -tail(t,1)*mu loglik <- loglik+alpha/beta*sum(exp(-beta*(tail(t,1)-t))-1) loglik <- loglik+sum(log(mu+alpha*r)) if(!opt) { return(list(negloglik=-loglik, mu=mu, alpha=alpha, beta=beta, t=t, r=r)) } else { return(-loglik) } } # insert your values for (mu, alpha, beta) in par # insert your times for data opt <- optim(par=c(1,2,3), fn=neg.loglik, data=data)
Finding the MLE for a univariate exponential Hawkes process You could also do a simple maximization. In R: neg.loglik <- function(params, data, opt=TRUE) { mu <- params[1] alpha <- params[2] beta <- params[3] t <- sort(data) r <- rep(0,length(t)) f
14,979
Finding the MLE for a univariate exponential Hawkes process
Here is my solution to "What is the simplest practical method to implement?" using python, specifically numpy, scipy and tick. One modification is that I set the exponential kernel such that alpha x beta x exp (-beta (t - ti)), to coincide with how tick defines exponential kernels: https://x-datainitiative.github.io/tick/modules/generated/tick.hawkes.HawkesExpKern.html#tick.hawkes.HawkesExpKern I'm assuming the reader might not be familiar with python. Import the relevant libraries: import numpy as np from scipy.optimize import minimize from tick.hawkes import SimuHawkesExpKernels Define the recursive function (R(i) in the question above) which returns an array the same size as the number of events: def _recursive(timestamps, beta): r_array = np.zeros(len(timestamps)) for i in range(1, len(timestamps)): r_array[i] = np.exp(-beta * (timestamps[i] - timestamps[i - 1])) * (1 + r_array[i - 1]) return r_array Define the log likelihood function specifying the various parameters: def log_likelihood(timestamps, mu, alpha, beta, runtime): r = _recursive(timestamps, beta) return -runtime * mu + alpha * np.sum(np.exp(-beta * (runtime - timestamps)) - 1) + \ np.sum(np.log(mu + alpha * beta * r)) Simulate some Hawkes data using the tick library (or some other means): m = 0.5 a = 0.2 b = 0.3 rt = 1000 simu = SimuHawkesExpKernels([[a]], b, [m], rt, seed=0) simu.simulate() t = simu.timestamps[0] Scipy's minimize function is probably the most common python optimisation for scalar functions. It expects a function with only two sets of parameters; those you want to minimise and those which are fixed. There are various possible minimisation methods, I am using the default which is L-BFGS-B for bounded problems and is a quasi-newton Method. Note that I should have started with a brute search first but the question asked for the simplest practical method. I could have also split into a minimisation over mu and alpha and then used simulated annealing over beta since the log-logarithm is convex over mu and alpha only. Define a new function to be used by the minimize function and returns the negative log-likelihood: def crit(params, *args): mu, alpha, beta = params timestamps, runtime = args return -log_likelihood(timestamps, mu, alpha, beta, runtime) Call the minimize function and set the bounds for m,a and b to be positive: minimize(crit, [m + 0.1, a + 0.1, b+ 0.1], args=(t, rt), bounds=((1e-10, None), (1e-10, None), (1e-10, None),)) Which gives estimates of m,a,b: array([0.43835767, 0.25823306, 0.14769243])
Finding the MLE for a univariate exponential Hawkes process
Here is my solution to "What is the simplest practical method to implement?" using python, specifically numpy, scipy and tick. One modification is that I set the exponential kernel such that alpha x b
Finding the MLE for a univariate exponential Hawkes process Here is my solution to "What is the simplest practical method to implement?" using python, specifically numpy, scipy and tick. One modification is that I set the exponential kernel such that alpha x beta x exp (-beta (t - ti)), to coincide with how tick defines exponential kernels: https://x-datainitiative.github.io/tick/modules/generated/tick.hawkes.HawkesExpKern.html#tick.hawkes.HawkesExpKern I'm assuming the reader might not be familiar with python. Import the relevant libraries: import numpy as np from scipy.optimize import minimize from tick.hawkes import SimuHawkesExpKernels Define the recursive function (R(i) in the question above) which returns an array the same size as the number of events: def _recursive(timestamps, beta): r_array = np.zeros(len(timestamps)) for i in range(1, len(timestamps)): r_array[i] = np.exp(-beta * (timestamps[i] - timestamps[i - 1])) * (1 + r_array[i - 1]) return r_array Define the log likelihood function specifying the various parameters: def log_likelihood(timestamps, mu, alpha, beta, runtime): r = _recursive(timestamps, beta) return -runtime * mu + alpha * np.sum(np.exp(-beta * (runtime - timestamps)) - 1) + \ np.sum(np.log(mu + alpha * beta * r)) Simulate some Hawkes data using the tick library (or some other means): m = 0.5 a = 0.2 b = 0.3 rt = 1000 simu = SimuHawkesExpKernels([[a]], b, [m], rt, seed=0) simu.simulate() t = simu.timestamps[0] Scipy's minimize function is probably the most common python optimisation for scalar functions. It expects a function with only two sets of parameters; those you want to minimise and those which are fixed. There are various possible minimisation methods, I am using the default which is L-BFGS-B for bounded problems and is a quasi-newton Method. Note that I should have started with a brute search first but the question asked for the simplest practical method. I could have also split into a minimisation over mu and alpha and then used simulated annealing over beta since the log-logarithm is convex over mu and alpha only. Define a new function to be used by the minimize function and returns the negative log-likelihood: def crit(params, *args): mu, alpha, beta = params timestamps, runtime = args return -log_likelihood(timestamps, mu, alpha, beta, runtime) Call the minimize function and set the bounds for m,a and b to be positive: minimize(crit, [m + 0.1, a + 0.1, b+ 0.1], args=(t, rt), bounds=((1e-10, None), (1e-10, None), (1e-10, None),)) Which gives estimates of m,a,b: array([0.43835767, 0.25823306, 0.14769243])
Finding the MLE for a univariate exponential Hawkes process Here is my solution to "What is the simplest practical method to implement?" using python, specifically numpy, scipy and tick. One modification is that I set the exponential kernel such that alpha x b
14,980
What does it mean to make the sample size a random variable?
I'm not meaning to use models close to the data collecting process but rather doing continuous Bayesian monitoring of posterior probabilities, which require no penalty for multiplicity. Instead of computing an arbitrary target sample size I'd prefer to compute a maximum possible sample size (for budget approval) and otherwise to stop "when we get the answer" as usually done to good effect in physics. I'll say more about that in my blog http://fharrell.com some day before long.
What does it mean to make the sample size a random variable?
I'm not meaning to use models close to the data collecting process but rather doing continuous Bayesian monitoring of posterior probabilities, which require no penalty for multiplicity. Instead of co
What does it mean to make the sample size a random variable? I'm not meaning to use models close to the data collecting process but rather doing continuous Bayesian monitoring of posterior probabilities, which require no penalty for multiplicity. Instead of computing an arbitrary target sample size I'd prefer to compute a maximum possible sample size (for budget approval) and otherwise to stop "when we get the answer" as usually done to good effect in physics. I'll say more about that in my blog http://fharrell.com some day before long.
What does it mean to make the sample size a random variable? I'm not meaning to use models close to the data collecting process but rather doing continuous Bayesian monitoring of posterior probabilities, which require no penalty for multiplicity. Instead of co
14,981
How to calculate prediction intervals for LOESS?
I don't know how to do prediction bands with the original loess function but there is a function loess.sd in the msir package that does just that! Almost verbatim from the msir documentation: library(msir) data(cars) # Calculates and plots a 1.96 * SD prediction band, that is, # a 95% prediction band l <- loess.sd(cars, nsigma = 1.96) plot(cars, main = "loess.sd(cars)", col="red", pch=19) lines(l$x, l$y) lines(l$x, l$upper, lty=2) lines(l$x, l$lower, lty=2) Your second question is a bit trickier since loess.sd doesn't come with a prediction function, but you can hack it together by linearly interpolating the predicted means and SDs you get out of loess.sd (using approx). These can, in turn, be used to simulate data using a normal distribution with the predicted means and SDs: # Simulate x data uniformly and y data acording to the loess fit sim_x <- runif(100, min(cars[,1]), max(cars[,1])) pred_mean <- approx(l$x, l$y, xout = sim_x)$y pred_sd <- approx(l$x, l$sd, xout = sim_x)$y sim_y <- rnorm(100, pred_mean, pred_sd) # Plots 95% prediction bands with simulated data plot(cars, main = "loess.sd(cars)", col="red", pch=19) points(sim_x, sim_y, col="blue") lines(l$x, l$y) lines(l$x, l$upper, lty=2) lines(l$x, l$lower, lty=2)
How to calculate prediction intervals for LOESS?
I don't know how to do prediction bands with the original loess function but there is a function loess.sd in the msir package that does just that! Almost verbatim from the msir documentation: library(
How to calculate prediction intervals for LOESS? I don't know how to do prediction bands with the original loess function but there is a function loess.sd in the msir package that does just that! Almost verbatim from the msir documentation: library(msir) data(cars) # Calculates and plots a 1.96 * SD prediction band, that is, # a 95% prediction band l <- loess.sd(cars, nsigma = 1.96) plot(cars, main = "loess.sd(cars)", col="red", pch=19) lines(l$x, l$y) lines(l$x, l$upper, lty=2) lines(l$x, l$lower, lty=2) Your second question is a bit trickier since loess.sd doesn't come with a prediction function, but you can hack it together by linearly interpolating the predicted means and SDs you get out of loess.sd (using approx). These can, in turn, be used to simulate data using a normal distribution with the predicted means and SDs: # Simulate x data uniformly and y data acording to the loess fit sim_x <- runif(100, min(cars[,1]), max(cars[,1])) pred_mean <- approx(l$x, l$y, xout = sim_x)$y pred_sd <- approx(l$x, l$sd, xout = sim_x)$y sim_y <- rnorm(100, pred_mean, pred_sd) # Plots 95% prediction bands with simulated data plot(cars, main = "loess.sd(cars)", col="red", pch=19) points(sim_x, sim_y, col="blue") lines(l$x, l$y) lines(l$x, l$upper, lty=2) lines(l$x, l$lower, lty=2)
How to calculate prediction intervals for LOESS? I don't know how to do prediction bands with the original loess function but there is a function loess.sd in the msir package that does just that! Almost verbatim from the msir documentation: library(
14,982
Why is "relaxed lasso" different from standard lasso?
From definition 1 of Meinshausen(2007), there are two parameters controlling the solution of the relaxed Lasso. The first one, $\lambda$, controls the variable selection, whereas the second, $\phi$, controls the shrinkage level. When $\phi= 1$ both Lasso and relaxed-Lasso are the same (as you said!), but for $\phi<1$ you obtain a solution with coefficients closer to what would give an orthogonal projection on the selected variables (kind of soft de-biasing). This formulation actually corresponds to solve two problems: First the full Lasso with penalization parameter $\lambda$ Second the Lasso on $X_S$, which is $X$ reduced to variables selected by 1, with a penalization parameter $\lambda\phi$.
Why is "relaxed lasso" different from standard lasso?
From definition 1 of Meinshausen(2007), there are two parameters controlling the solution of the relaxed Lasso. The first one, $\lambda$, controls the variable selection, whereas the second, $\phi$, c
Why is "relaxed lasso" different from standard lasso? From definition 1 of Meinshausen(2007), there are two parameters controlling the solution of the relaxed Lasso. The first one, $\lambda$, controls the variable selection, whereas the second, $\phi$, controls the shrinkage level. When $\phi= 1$ both Lasso and relaxed-Lasso are the same (as you said!), but for $\phi<1$ you obtain a solution with coefficients closer to what would give an orthogonal projection on the selected variables (kind of soft de-biasing). This formulation actually corresponds to solve two problems: First the full Lasso with penalization parameter $\lambda$ Second the Lasso on $X_S$, which is $X$ reduced to variables selected by 1, with a penalization parameter $\lambda\phi$.
Why is "relaxed lasso" different from standard lasso? From definition 1 of Meinshausen(2007), there are two parameters controlling the solution of the relaxed Lasso. The first one, $\lambda$, controls the variable selection, whereas the second, $\phi$, c
14,983
Good data example needed with covariate affected by treatments
You may want to check out the mediation R package. It does include experimental data like jobs and framing where the treatment variable affects both a response variable and covariates (i.e., mediators of the treatment effect), along with covariates not affected by the treatment. I looked into the mediation literature because I though you exactly described a mediation study: the fertilizer effect on the crop quality is mediated through its effect on soil acidity. Even if the datasets in the mediation package do not satisfy you, you may find one if you look into the mediation literature.
Good data example needed with covariate affected by treatments
You may want to check out the mediation R package. It does include experimental data like jobs and framing where the treatment variable affects both a response variable and covariates (i.e., mediators
Good data example needed with covariate affected by treatments You may want to check out the mediation R package. It does include experimental data like jobs and framing where the treatment variable affects both a response variable and covariates (i.e., mediators of the treatment effect), along with covariates not affected by the treatment. I looked into the mediation literature because I though you exactly described a mediation study: the fertilizer effect on the crop quality is mediated through its effect on soil acidity. Even if the datasets in the mediation package do not satisfy you, you may find one if you look into the mediation literature.
Good data example needed with covariate affected by treatments You may want to check out the mediation R package. It does include experimental data like jobs and framing where the treatment variable affects both a response variable and covariates (i.e., mediators
14,984
Good data example needed with covariate affected by treatments
I thought I'd show how an analysis comes out with one of the datasets in the mediation package. In framing, an experiment is done where subjects have the opportunity to send a message to Congress regarding immigration. However, some subjects (treat=1) were first shown a news story that portrays Latinos in a negative way. Besides the binary response (whether or not they sent a message), we also measured emp, the subjects' emotional state after the treatment was applied. There are various demographic variables as well. First, let's load the needed packages in R, and change the labels for educ to shorter strings. > library("lsmeans") > library("mediation") > levels(framing$educ) = c("NA","Ref","< HS", "HS", "> HS","Coll +") Now fit a logistic regression model > framing.glm = glm(cong_mesg ~ age + income + educ + emo + gender * factor(treat), + family = binomial, data = framing) Here is a display of the conventional adjusted means, where predictions are made with the covariates age, income, and emo set at their mean values: > lsmip(framing.glm, treat ~ educ | gender, type = "response") This is a curious result because the displayed treatment effects are the opposite for females as for males, and the effect of education isn't monotone as one might expect. Note, hHowever, emo is a post-treatment measurement. This means that the treatment could have affected it, i.e. emo is a mediating covariate; and so it may not be meaningful to compare predictions of the response variable while holding emo constant. Instead, let's look at the predictions where emo is set to its predicted values given treat and the demographic variables. > lsmip(framing.glm, treat ~ educ | gender, type = "response", + cov.reduce = emo ~ treat*gender + age + educ + income) This result is quite different, suggesting that emo plays a strong mediating role. (The mediation package has functions for estimating the strength of these effects.) The above predictions suggest that, taking emotional response into account, male subjects exposed to the negative news story are more likely to send the message than are females or those not seeing the negative news story. Also, the effect of educ is (almost) monotone. Thanks again to @MasatoNakagawa for pointing me to this interesting example and attuning me to some recent research on causality.
Good data example needed with covariate affected by treatments
I thought I'd show how an analysis comes out with one of the datasets in the mediation package. In framing, an experiment is done where subjects have the opportunity to send a message to Congress rega
Good data example needed with covariate affected by treatments I thought I'd show how an analysis comes out with one of the datasets in the mediation package. In framing, an experiment is done where subjects have the opportunity to send a message to Congress regarding immigration. However, some subjects (treat=1) were first shown a news story that portrays Latinos in a negative way. Besides the binary response (whether or not they sent a message), we also measured emp, the subjects' emotional state after the treatment was applied. There are various demographic variables as well. First, let's load the needed packages in R, and change the labels for educ to shorter strings. > library("lsmeans") > library("mediation") > levels(framing$educ) = c("NA","Ref","< HS", "HS", "> HS","Coll +") Now fit a logistic regression model > framing.glm = glm(cong_mesg ~ age + income + educ + emo + gender * factor(treat), + family = binomial, data = framing) Here is a display of the conventional adjusted means, where predictions are made with the covariates age, income, and emo set at their mean values: > lsmip(framing.glm, treat ~ educ | gender, type = "response") This is a curious result because the displayed treatment effects are the opposite for females as for males, and the effect of education isn't monotone as one might expect. Note, hHowever, emo is a post-treatment measurement. This means that the treatment could have affected it, i.e. emo is a mediating covariate; and so it may not be meaningful to compare predictions of the response variable while holding emo constant. Instead, let's look at the predictions where emo is set to its predicted values given treat and the demographic variables. > lsmip(framing.glm, treat ~ educ | gender, type = "response", + cov.reduce = emo ~ treat*gender + age + educ + income) This result is quite different, suggesting that emo plays a strong mediating role. (The mediation package has functions for estimating the strength of these effects.) The above predictions suggest that, taking emotional response into account, male subjects exposed to the negative news story are more likely to send the message than are females or those not seeing the negative news story. Also, the effect of educ is (almost) monotone. Thanks again to @MasatoNakagawa for pointing me to this interesting example and attuning me to some recent research on causality.
Good data example needed with covariate affected by treatments I thought I'd show how an analysis comes out with one of the datasets in the mediation package. In framing, an experiment is done where subjects have the opportunity to send a message to Congress rega
14,985
Good data example needed with covariate affected by treatments
Look up gene-environment interaction GWAS studies. The statistical analysis they perform in essence is what you have described. The question is does your environment matter to a phenotype (observable feature)? One school of thought generally ignores all environmental information and says your genetic makeup describes your phenotype. This is in complete contrast with ecological studies where the story is environment is everything and they ignore the genes. Since both parties are trying to understand the same problem, there have been recent attempts to coalesce the two. Say we are studying BMI. We take the first few principal components of the genetic matrix as the fixed effects due to genes. We fit education with an index 1 for well educated and 0 for poorly educated as a fixed effect. There is a reasonably strong correlation between the education index and wealth of the community the person is from. So one would argue that the low income communities are more likely to have more fast food restaurants. The fast food acts as an obesogenic trigger.. "Triggers something in your genetic setup which encourages fat accumulation" so it will show up in the genetic makeup in some form. Simulating such data is not a problem. Look up http://pngu.mgh.harvard.edu/~purcell/plink/simulate.shtml This lets you simulate GWAS (think of this as genetic units) data responsible for a symptom. If not instructed otherwise it will generate 1000 with the symptom and 1000 controls. The norm in these simulations which I use is 9990 SNPs do not cause the symptom and 10 SNPs do. Read the instructions on how these are simulated. The output will be 1 if the person is obese and 0 if he isn't. Simulate education factors (finished college eduction/not finished college education )based on some reasonable correlation with obesity levels. Hope this helps!!!
Good data example needed with covariate affected by treatments
Look up gene-environment interaction GWAS studies. The statistical analysis they perform in essence is what you have described. The question is does your environment matter to a phenotype (observable
Good data example needed with covariate affected by treatments Look up gene-environment interaction GWAS studies. The statistical analysis they perform in essence is what you have described. The question is does your environment matter to a phenotype (observable feature)? One school of thought generally ignores all environmental information and says your genetic makeup describes your phenotype. This is in complete contrast with ecological studies where the story is environment is everything and they ignore the genes. Since both parties are trying to understand the same problem, there have been recent attempts to coalesce the two. Say we are studying BMI. We take the first few principal components of the genetic matrix as the fixed effects due to genes. We fit education with an index 1 for well educated and 0 for poorly educated as a fixed effect. There is a reasonably strong correlation between the education index and wealth of the community the person is from. So one would argue that the low income communities are more likely to have more fast food restaurants. The fast food acts as an obesogenic trigger.. "Triggers something in your genetic setup which encourages fat accumulation" so it will show up in the genetic makeup in some form. Simulating such data is not a problem. Look up http://pngu.mgh.harvard.edu/~purcell/plink/simulate.shtml This lets you simulate GWAS (think of this as genetic units) data responsible for a symptom. If not instructed otherwise it will generate 1000 with the symptom and 1000 controls. The norm in these simulations which I use is 9990 SNPs do not cause the symptom and 10 SNPs do. Read the instructions on how these are simulated. The output will be 1 if the person is obese and 0 if he isn't. Simulate education factors (finished college eduction/not finished college education )based on some reasonable correlation with obesity levels. Hope this helps!!!
Good data example needed with covariate affected by treatments Look up gene-environment interaction GWAS studies. The statistical analysis they perform in essence is what you have described. The question is does your environment matter to a phenotype (observable
14,986
Good data example needed with covariate affected by treatments
I'd recommend reading Freakonomics, and finding the papers their work is based on, and seeing if you can grab that data. They have some really interesting work on really interesting datasets, and in some cases they figure out very clever ways to test hypotheses despite limitations in the data.
Good data example needed with covariate affected by treatments
I'd recommend reading Freakonomics, and finding the papers their work is based on, and seeing if you can grab that data. They have some really interesting work on really interesting datasets, and in s
Good data example needed with covariate affected by treatments I'd recommend reading Freakonomics, and finding the papers their work is based on, and seeing if you can grab that data. They have some really interesting work on really interesting datasets, and in some cases they figure out very clever ways to test hypotheses despite limitations in the data.
Good data example needed with covariate affected by treatments I'd recommend reading Freakonomics, and finding the papers their work is based on, and seeing if you can grab that data. They have some really interesting work on really interesting datasets, and in s
14,987
max_delta_step in xgboost
eta introduces a 'relative' regularization (multiplying the weight by a constant factor) but in extreme cases where hessian is nearly zero (like when we have very unbalanced classes) this isn't enough because the weights (in which computation the hessian is in denominator) becomes to nearly infinite. So what max_delta_steps do is to introduce an 'absolute' regularization capping the weight before apply eta correction. If you see the code of xgboost (file parameter.h, procedure CalcWeight), you can see this, and you see the effect of other regularization parameters, lambda and alpha (that are equivalents to L1 and L2 regularization). In special lambda effect complement (or may substitute) max_delta_step, as a lambda greater than zero do the weight smaller.
max_delta_step in xgboost
eta introduces a 'relative' regularization (multiplying the weight by a constant factor) but in extreme cases where hessian is nearly zero (like when we have very unbalanced classes) this isn't enough
max_delta_step in xgboost eta introduces a 'relative' regularization (multiplying the weight by a constant factor) but in extreme cases where hessian is nearly zero (like when we have very unbalanced classes) this isn't enough because the weights (in which computation the hessian is in denominator) becomes to nearly infinite. So what max_delta_steps do is to introduce an 'absolute' regularization capping the weight before apply eta correction. If you see the code of xgboost (file parameter.h, procedure CalcWeight), you can see this, and you see the effect of other regularization parameters, lambda and alpha (that are equivalents to L1 and L2 regularization). In special lambda effect complement (or may substitute) max_delta_step, as a lambda greater than zero do the weight smaller.
max_delta_step in xgboost eta introduces a 'relative' regularization (multiplying the weight by a constant factor) but in extreme cases where hessian is nearly zero (like when we have very unbalanced classes) this isn't enough
14,988
Is gradient boosting appropriate for data with low event rates like 1%?
(To give short answer to this:) It is fine to use a gradient boosting machine algorithm when dealing with an imbalanced dataset. When dealing with a strongly imbalanced dataset it much more relevant to question the suitability of the metric used. We should potentially avoid metrics, like Accuracy or Recall, that are based on arbitrary thresholds, and opt for metrics, like AUCPR or Brier scoring, that give a more accurate picture - see the excellent CV.SE thread on: Why is accuracy not the best measure for assessing classification models? for more). Similarly, we could potentially employ a cost-sensitive approach by assigning different misclassification costs (e.g. see Masnadi-Shirazi & Vasconcelos (2011) Cost-Sensitive Boosting for a general view and proposed changes to known boosting algorithms or for a particular interesting application with a simpler approach check the Higgs Boson challenge report for the XGBoost algorithm; Chen & He (2015) Higgs Boson Discovery with Boosted Trees provide more details). It is also worth noting that if we employ a probabilistic classifier (like GBMs) we can/should actively look into calibrating the returned probabilities (e.g. see Zadrozny & Elkan (2002) Transforming classifier scores into accurate multiclass probability estimates or Kull et al. (2017) Beta calibration: a well-founded and easily implemented improvement on logistic calibration for binary classifiers) to potentially augment our learner's performance. Especially when working with imbalanced data adequately capturing tendency changes might be more informative than simply labelling the data. To that extent, some might argue that cost-sensitive approaches are not that beneficial in the end (e.g. see Nikolaou et al. (2016) Cost-sensitive boosting algorithms: Do we really need them?). To reiterate the original point though, boosting algorithms are not inherently bad for imbalanced data and in certain cases they can offer a very competitive option.
Is gradient boosting appropriate for data with low event rates like 1%?
(To give short answer to this:) It is fine to use a gradient boosting machine algorithm when dealing with an imbalanced dataset. When dealing with a strongly imbalanced dataset it much more relevant t
Is gradient boosting appropriate for data with low event rates like 1%? (To give short answer to this:) It is fine to use a gradient boosting machine algorithm when dealing with an imbalanced dataset. When dealing with a strongly imbalanced dataset it much more relevant to question the suitability of the metric used. We should potentially avoid metrics, like Accuracy or Recall, that are based on arbitrary thresholds, and opt for metrics, like AUCPR or Brier scoring, that give a more accurate picture - see the excellent CV.SE thread on: Why is accuracy not the best measure for assessing classification models? for more). Similarly, we could potentially employ a cost-sensitive approach by assigning different misclassification costs (e.g. see Masnadi-Shirazi & Vasconcelos (2011) Cost-Sensitive Boosting for a general view and proposed changes to known boosting algorithms or for a particular interesting application with a simpler approach check the Higgs Boson challenge report for the XGBoost algorithm; Chen & He (2015) Higgs Boson Discovery with Boosted Trees provide more details). It is also worth noting that if we employ a probabilistic classifier (like GBMs) we can/should actively look into calibrating the returned probabilities (e.g. see Zadrozny & Elkan (2002) Transforming classifier scores into accurate multiclass probability estimates or Kull et al. (2017) Beta calibration: a well-founded and easily implemented improvement on logistic calibration for binary classifiers) to potentially augment our learner's performance. Especially when working with imbalanced data adequately capturing tendency changes might be more informative than simply labelling the data. To that extent, some might argue that cost-sensitive approaches are not that beneficial in the end (e.g. see Nikolaou et al. (2016) Cost-sensitive boosting algorithms: Do we really need them?). To reiterate the original point though, boosting algorithms are not inherently bad for imbalanced data and in certain cases they can offer a very competitive option.
Is gradient boosting appropriate for data with low event rates like 1%? (To give short answer to this:) It is fine to use a gradient boosting machine algorithm when dealing with an imbalanced dataset. When dealing with a strongly imbalanced dataset it much more relevant t
14,989
ARIMA estimation by hand
There is the concept of exact likelihood. It requires the knowledge of initial parameters such as the fist value of the MA error (one of your questions). Implementations usually differ regarding how they treat the initial values. What I usually do is (which is not mentioned in many books) is to also maximize ML w.r.t. the initial values as well. Please take a look at the following from Tsay, it is not covering all cases, but was quite helpful for me: http://faculty.chicagobooth.edu/ruey.tsay/teaching/uts/lec8-08.pdf
ARIMA estimation by hand
There is the concept of exact likelihood. It requires the knowledge of initial parameters such as the fist value of the MA error (one of your questions). Implementations usually differ regarding how t
ARIMA estimation by hand There is the concept of exact likelihood. It requires the knowledge of initial parameters such as the fist value of the MA error (one of your questions). Implementations usually differ regarding how they treat the initial values. What I usually do is (which is not mentioned in many books) is to also maximize ML w.r.t. the initial values as well. Please take a look at the following from Tsay, it is not covering all cases, but was quite helpful for me: http://faculty.chicagobooth.edu/ruey.tsay/teaching/uts/lec8-08.pdf
ARIMA estimation by hand There is the concept of exact likelihood. It requires the knowledge of initial parameters such as the fist value of the MA error (one of your questions). Implementations usually differ regarding how t
14,990
ARIMA estimation by hand
Did you read the the help page of arima function? Here is the relevant excerpt: The exact likelihood is computed via a state-space representation of the ARIMA process, and the innovations and their variance found by a Kalman filter. The initialization of the differenced ARMA process uses stationarity and is based on Gardner et al. (1980). For a differenced process the non-stationary components are given a diffuse prior (controlled by kappa). Observations which are still controlled by the diffuse prior (determined by having a Kalman gain of at least 1e4) are excluded from the likelihood calculations. (This gives comparable results to arima0 in the absence of missing values, when the observations excluded are precisely those dropped by the differencing.) Also relevant is a parameter method=c("CSS-ML", "ML", "CSS"): Fitting method: maximum likelihood or minimize conditional sum-of-squares. The default (unless there are missing values) is to use conditional-sum-of-squares to find starting values, then maximum likelihood. Your results do not differ that much from the ones produced by arima function, so you definitely got everything right. Remember that if you want to compare results of two optimisation procedures, you need to make sure, that the starting values are the same, and the same optimisation method is used, otherwise the results might differ.
ARIMA estimation by hand
Did you read the the help page of arima function? Here is the relevant excerpt: The exact likelihood is computed via a state-space representation of the ARIMA process, and the innovations and their
ARIMA estimation by hand Did you read the the help page of arima function? Here is the relevant excerpt: The exact likelihood is computed via a state-space representation of the ARIMA process, and the innovations and their variance found by a Kalman filter. The initialization of the differenced ARMA process uses stationarity and is based on Gardner et al. (1980). For a differenced process the non-stationary components are given a diffuse prior (controlled by kappa). Observations which are still controlled by the diffuse prior (determined by having a Kalman gain of at least 1e4) are excluded from the likelihood calculations. (This gives comparable results to arima0 in the absence of missing values, when the observations excluded are precisely those dropped by the differencing.) Also relevant is a parameter method=c("CSS-ML", "ML", "CSS"): Fitting method: maximum likelihood or minimize conditional sum-of-squares. The default (unless there are missing values) is to use conditional-sum-of-squares to find starting values, then maximum likelihood. Your results do not differ that much from the ones produced by arima function, so you definitely got everything right. Remember that if you want to compare results of two optimisation procedures, you need to make sure, that the starting values are the same, and the same optimisation method is used, otherwise the results might differ.
ARIMA estimation by hand Did you read the the help page of arima function? Here is the relevant excerpt: The exact likelihood is computed via a state-space representation of the ARIMA process, and the innovations and their
14,991
Computation of new standard deviation using old standard deviation after change in dataset
A section in the Wikipedia article on "Algorithms for calculating variance" shows how to compute the variance if elements are added to your observations. (Recall that the standard deviation is the square root of the variance.) Assume that you append $x_{n+1}$ to your array, then $$\sigma_{new}^2 = \sigma_{old}^2 + (x_{n+1} - \mu_{new})(x_{n+1} - \mu_{old}).$$ EDIT: Above formula seems to be wrong, see comment. Now, replacing an element means adding an observation and removing another one; both can be computed with the formula above. However, keep in mind that problems of numerical stability may ensue; the quoted article also proposes numerically stable variants. To derive the formula by yourself, compute $(n-1)(\sigma_{new}^2 - \sigma_{old}^2)$ using the definition of sample variance and substitute $\mu_{new}$ by the formula you gave when appropriate. This gives you $\sigma_{new}^2 - \sigma_{old}^2$ in the end, and thus a formula for $\sigma_{new}$ given $\sigma_{old}$ and $\mu_{old}$. In my notation, I assume you replace the element $x_n$ by $x_n'$: $$ \begin{eqnarray*} \sigma^2 &=& (n-1)^{-1} \sum_k (x_k - \mu)^2 \\ (n-1)(\sigma_{new}^2 - \sigma_{old}^2) &=& \sum_{k=1}^{n-1} ((x_k - \mu_{new})^2 - (x_k - \mu_{old})^2) \\ &&+\ ((x_n' - \mu_{new})^2 - (x_n - \mu_{old})^2) \\ &=& \sum_{k=1}^{n-1} ((x_k - \mu_{old} - n^{-1}(x_n'-x_n))^2 - (x_k - \mu_{old})^2) \\ &&+\ ((x_n' - \mu_{old} - n^{-1}(x_n'-x_n))^2 - (x_n - \mu_{old})^2) \\ \end{eqnarray*}\\ $$ The $x_k$ in the sum transform into something dependent of $\mu_{old}$, but you'll have to work the equation a little bit more to derive a neat result. This should give you the general idea.
Computation of new standard deviation using old standard deviation after change in dataset
A section in the Wikipedia article on "Algorithms for calculating variance" shows how to compute the variance if elements are added to your observations. (Recall that the standard deviation is the squ
Computation of new standard deviation using old standard deviation after change in dataset A section in the Wikipedia article on "Algorithms for calculating variance" shows how to compute the variance if elements are added to your observations. (Recall that the standard deviation is the square root of the variance.) Assume that you append $x_{n+1}$ to your array, then $$\sigma_{new}^2 = \sigma_{old}^2 + (x_{n+1} - \mu_{new})(x_{n+1} - \mu_{old}).$$ EDIT: Above formula seems to be wrong, see comment. Now, replacing an element means adding an observation and removing another one; both can be computed with the formula above. However, keep in mind that problems of numerical stability may ensue; the quoted article also proposes numerically stable variants. To derive the formula by yourself, compute $(n-1)(\sigma_{new}^2 - \sigma_{old}^2)$ using the definition of sample variance and substitute $\mu_{new}$ by the formula you gave when appropriate. This gives you $\sigma_{new}^2 - \sigma_{old}^2$ in the end, and thus a formula for $\sigma_{new}$ given $\sigma_{old}$ and $\mu_{old}$. In my notation, I assume you replace the element $x_n$ by $x_n'$: $$ \begin{eqnarray*} \sigma^2 &=& (n-1)^{-1} \sum_k (x_k - \mu)^2 \\ (n-1)(\sigma_{new}^2 - \sigma_{old}^2) &=& \sum_{k=1}^{n-1} ((x_k - \mu_{new})^2 - (x_k - \mu_{old})^2) \\ &&+\ ((x_n' - \mu_{new})^2 - (x_n - \mu_{old})^2) \\ &=& \sum_{k=1}^{n-1} ((x_k - \mu_{old} - n^{-1}(x_n'-x_n))^2 - (x_k - \mu_{old})^2) \\ &&+\ ((x_n' - \mu_{old} - n^{-1}(x_n'-x_n))^2 - (x_n - \mu_{old})^2) \\ \end{eqnarray*}\\ $$ The $x_k$ in the sum transform into something dependent of $\mu_{old}$, but you'll have to work the equation a little bit more to derive a neat result. This should give you the general idea.
Computation of new standard deviation using old standard deviation after change in dataset A section in the Wikipedia article on "Algorithms for calculating variance" shows how to compute the variance if elements are added to your observations. (Recall that the standard deviation is the squ
14,992
Computation of new standard deviation using old standard deviation after change in dataset
Based on what i think i'm reading on the linked Wikipedia article you can maintain a "running" standard deviation: real sum = 0; int count = 0; real S = 0; real variance = 0; real GetRunningStandardDeviation(ref sum, ref count, ref S, x) { real oldMean; if (count >= 1) { real oldMean = sum / count; sum = sum + x; count = count + 1; real newMean = sum / count; S = S + (x-oldMean)*(x-newMean) } else { sum = x; count = 1; S = 0; } //estimated Variance = (S / (k-1) ) //estimated Standard Deviation = sqrt(variance) if (count > 1) return sqrt(S / (count-1) ); else return 0; } Although in the article they don't maintain a separate running sum and count, but instead have the single mean. Since in thing i'm doing today i keep a count (for statistical purposes), it is more useful to calculate the means each time.
Computation of new standard deviation using old standard deviation after change in dataset
Based on what i think i'm reading on the linked Wikipedia article you can maintain a "running" standard deviation: real sum = 0; int count = 0; real S = 0; real variance = 0; real GetRunningStandardD
Computation of new standard deviation using old standard deviation after change in dataset Based on what i think i'm reading on the linked Wikipedia article you can maintain a "running" standard deviation: real sum = 0; int count = 0; real S = 0; real variance = 0; real GetRunningStandardDeviation(ref sum, ref count, ref S, x) { real oldMean; if (count >= 1) { real oldMean = sum / count; sum = sum + x; count = count + 1; real newMean = sum / count; S = S + (x-oldMean)*(x-newMean) } else { sum = x; count = 1; S = 0; } //estimated Variance = (S / (k-1) ) //estimated Standard Deviation = sqrt(variance) if (count > 1) return sqrt(S / (count-1) ); else return 0; } Although in the article they don't maintain a separate running sum and count, but instead have the single mean. Since in thing i'm doing today i keep a count (for statistical purposes), it is more useful to calculate the means each time.
Computation of new standard deviation using old standard deviation after change in dataset Based on what i think i'm reading on the linked Wikipedia article you can maintain a "running" standard deviation: real sum = 0; int count = 0; real S = 0; real variance = 0; real GetRunningStandardD
14,993
Computation of new standard deviation using old standard deviation after change in dataset
Given original $\bar x$, $s$, and $n$, as well as the change of a given element $x_n$ to $x_n'$, I believe your new standard deviation $s'$ will be the square root of $$s^2 + \frac{1}{n-1}\left(2n\Delta \bar x(x_n-\bar x) +n(n-1)(\Delta \bar x)^2\right),$$ where $\Delta \bar x = \bar x' - \bar x$, with $\bar x'$ denoting the new mean. Maybe there is a snazzier way of writing it? I checked this against a small test case and it seemed to work.
Computation of new standard deviation using old standard deviation after change in dataset
Given original $\bar x$, $s$, and $n$, as well as the change of a given element $x_n$ to $x_n'$, I believe your new standard deviation $s'$ will be the square root of $$s^2 + \frac{1}{n-1}\left(2n\Del
Computation of new standard deviation using old standard deviation after change in dataset Given original $\bar x$, $s$, and $n$, as well as the change of a given element $x_n$ to $x_n'$, I believe your new standard deviation $s'$ will be the square root of $$s^2 + \frac{1}{n-1}\left(2n\Delta \bar x(x_n-\bar x) +n(n-1)(\Delta \bar x)^2\right),$$ where $\Delta \bar x = \bar x' - \bar x$, with $\bar x'$ denoting the new mean. Maybe there is a snazzier way of writing it? I checked this against a small test case and it seemed to work.
Computation of new standard deviation using old standard deviation after change in dataset Given original $\bar x$, $s$, and $n$, as well as the change of a given element $x_n$ to $x_n'$, I believe your new standard deviation $s'$ will be the square root of $$s^2 + \frac{1}{n-1}\left(2n\Del
14,994
Computation of new standard deviation using old standard deviation after change in dataset
If you make the assumption that the preliminary data that you have represents all of the values within the population with the relative frequencies, then increasing the sample size as a multiple of $n$ will be like copying the data set and pasting it below and then recalculating the mean and standard deviation. The mean will remain the same, but the standard deviation will decrease. Using this model, you can derive a formula that allows you to estimate the new standard deviation based on a new sample size, $n$. That formula is $$S_{2} = S_{1} \times \sqrt{\frac{n_2 - (n_2/n_1)}{n_2 - 1} }.$$
Computation of new standard deviation using old standard deviation after change in dataset
If you make the assumption that the preliminary data that you have represents all of the values within the population with the relative frequencies, then increasing the sample size as a multiple of $n
Computation of new standard deviation using old standard deviation after change in dataset If you make the assumption that the preliminary data that you have represents all of the values within the population with the relative frequencies, then increasing the sample size as a multiple of $n$ will be like copying the data set and pasting it below and then recalculating the mean and standard deviation. The mean will remain the same, but the standard deviation will decrease. Using this model, you can derive a formula that allows you to estimate the new standard deviation based on a new sample size, $n$. That formula is $$S_{2} = S_{1} \times \sqrt{\frac{n_2 - (n_2/n_1)}{n_2 - 1} }.$$
Computation of new standard deviation using old standard deviation after change in dataset If you make the assumption that the preliminary data that you have represents all of the values within the population with the relative frequencies, then increasing the sample size as a multiple of $n
14,995
RMSProp and Adam vs SGD
After researching a few articles online and Keras documentation it is suggested that the RMSProp optimizer is recommended for recurrent neural networks.https://github.com/keras-team/keras/blob/master/keras/optimizers.py#L209 Stochastic Gradient Descent seems to take advantage of its learning rate and momentum between each batch to optimize the model’s weights based on the information of the loss function in my case is 'categorical_crossentropy'. I suggest https://www.ruder.io/optimizing-gradient-descent/ for additional information about optimization algorithms.
RMSProp and Adam vs SGD
After researching a few articles online and Keras documentation it is suggested that the RMSProp optimizer is recommended for recurrent neural networks.https://github.com/keras-team/keras/blob/master/
RMSProp and Adam vs SGD After researching a few articles online and Keras documentation it is suggested that the RMSProp optimizer is recommended for recurrent neural networks.https://github.com/keras-team/keras/blob/master/keras/optimizers.py#L209 Stochastic Gradient Descent seems to take advantage of its learning rate and momentum between each batch to optimize the model’s weights based on the information of the loss function in my case is 'categorical_crossentropy'. I suggest https://www.ruder.io/optimizing-gradient-descent/ for additional information about optimization algorithms.
RMSProp and Adam vs SGD After researching a few articles online and Keras documentation it is suggested that the RMSProp optimizer is recommended for recurrent neural networks.https://github.com/keras-team/keras/blob/master/
14,996
How to calculate average length of adherence to vegetarianism when we only have survey data about current vegetarians?
Let $f_X(x)$ denote the pdf of adherence length $X$ of vegetarianism in the population. Our objective is to estimate $EX=\int_0^\infty x f_X(x)\;dx$. Assuming that the probability of being included in the survey (the event $S$) is proportional to $X$, the pdf of adherence length $X$ among those included in the survey is $$ f_{X|S}(x) = \frac{xf_X(x)}{\int x f_X(x) dx}=\frac{xf_X(x)}{EX}. \tag{1} $$ At the time of being included in the survey, only a time $Z$ has passed. Conditional on $X$ and $S$, the reported time being a vegetarian is uniform with pdf $$ f_{Z|X=x,S}(z) = \frac1x, \quad \text{for } 0\le z\le x. \tag{2} $$ Elsewhere the density is zero. Hence, using the law of total probability, the overall distribution of time $Z$ passed as vegetarian among those included in the survey becomes \begin{align} f_{Z|S}(z) &= \int_0^\infty f_{Z|X=x,S}(z)f_{X|S}(x)dx \\&= \int_z^\infty \frac1x \frac{xf_X(x)}{EX}dx \\&= \frac{1-F_X(z)}{EX}, \tag{3} \end{align} where $F_X(z)$ is the cdf of $X$. Since $X$ is a positive variable $F_X(0)=P(X\le 0)=0$ and so $f_Z(0)=1/EX$. This suggests estimating $EX$ by perhaps first estimating $f_{Z|S}(z)$ non-parametrically from the observed data $z_1,z_2,\dots,z_n$. One option is kernel density estimation, using Silverman's reflection method around $z=0$ since the domain of $f_Z(z)$ has a lower bound at $z=0$. This method applied to simulated data is shown as the red curve in the figure below. Having obtained an estimate $\hat f_Z(0)$ of $f_Z(z)$ at $z=0$, an estimate of $EX$ is then given by $\widehat{EX}=1/\hat f_Z(0)$. This non-parametric method is not ideal however since it does not exploit the fact that $f_{Z|S}(z)$ is a non-increasing function. Also, if $f_X(0)=F_X'(0)>0$, $f_{Z|S}(0)$ may become severely underestimated and $EX$ overestimated. Finding an estimate of $EX$ in such situations without making more assumptions seems difficult, essentially because short adherence times present in this situation hardly show up in the observed data as a result of the biased sampling. Alternatively, one could make some distributional assumptions about $f_X(x)$ and fit a parametric model by maximising the likelihood $$ L(\theta)=\prod_{i=1}^n \frac{1-F_X(z_i;\theta)}{EX(\theta)} \tag{4} $$ numerically (blue curve in above figure). R code simulating data and implementing both methods: # Simulate lognormal duration length in population set.seed(1) n <- 1e+4 x <- rlnorm(n,mean=2,sd=.2) # Biased sampling y <- sample(x, size=n/10, prob=x, replace=TRUE) # Duration at time of sampling z <- runif(length(y),min=0, max=y) hist(z,prob=TRUE,main="") # Compute kernel density estimate with reflection aroudn z=0 to <- max(x) + 3 fhat <- density(z,from = -to, to=to) m <- length(fhat$y) fhat$y <- fhat$y[(m/2+1):m] + fhat$y[(m/2):1] fhat$x <- fhat$x[(m/2+1):m] lines(fhat,col="red") # Estimate of EX 1/fhat$y[1] #> [1] 7.032448 # True value (mean of above lognormal) exp(2+.2^2/2) #> [1] 7.538325 # Maximum likelihood nll <- function(theta, z) { - sum(plnorm(z, theta[1], theta[2], log.p=TRUE, lower.tail = FALSE)) + length(z)*(theta[1] + theta[2]^2/2) } fit <- optim(c(0,1),nll,z=z) fit$par #> [1] 1.9860464 0.2019859 EXhat <- exp(fit$par[1]+fit$par[2]^2/2) # MLE of EX EXhat #> [1] 7.436836 curve(plnorm(z, fit$par[1], fit$par[2], lower.tail=FALSE)/EXhat, xname="z", col="blue",add=TRUE)
How to calculate average length of adherence to vegetarianism when we only have survey data about cu
Let $f_X(x)$ denote the pdf of adherence length $X$ of vegetarianism in the population. Our objective is to estimate $EX=\int_0^\infty x f_X(x)\;dx$. Assuming that the probability of being included i
How to calculate average length of adherence to vegetarianism when we only have survey data about current vegetarians? Let $f_X(x)$ denote the pdf of adherence length $X$ of vegetarianism in the population. Our objective is to estimate $EX=\int_0^\infty x f_X(x)\;dx$. Assuming that the probability of being included in the survey (the event $S$) is proportional to $X$, the pdf of adherence length $X$ among those included in the survey is $$ f_{X|S}(x) = \frac{xf_X(x)}{\int x f_X(x) dx}=\frac{xf_X(x)}{EX}. \tag{1} $$ At the time of being included in the survey, only a time $Z$ has passed. Conditional on $X$ and $S$, the reported time being a vegetarian is uniform with pdf $$ f_{Z|X=x,S}(z) = \frac1x, \quad \text{for } 0\le z\le x. \tag{2} $$ Elsewhere the density is zero. Hence, using the law of total probability, the overall distribution of time $Z$ passed as vegetarian among those included in the survey becomes \begin{align} f_{Z|S}(z) &= \int_0^\infty f_{Z|X=x,S}(z)f_{X|S}(x)dx \\&= \int_z^\infty \frac1x \frac{xf_X(x)}{EX}dx \\&= \frac{1-F_X(z)}{EX}, \tag{3} \end{align} where $F_X(z)$ is the cdf of $X$. Since $X$ is a positive variable $F_X(0)=P(X\le 0)=0$ and so $f_Z(0)=1/EX$. This suggests estimating $EX$ by perhaps first estimating $f_{Z|S}(z)$ non-parametrically from the observed data $z_1,z_2,\dots,z_n$. One option is kernel density estimation, using Silverman's reflection method around $z=0$ since the domain of $f_Z(z)$ has a lower bound at $z=0$. This method applied to simulated data is shown as the red curve in the figure below. Having obtained an estimate $\hat f_Z(0)$ of $f_Z(z)$ at $z=0$, an estimate of $EX$ is then given by $\widehat{EX}=1/\hat f_Z(0)$. This non-parametric method is not ideal however since it does not exploit the fact that $f_{Z|S}(z)$ is a non-increasing function. Also, if $f_X(0)=F_X'(0)>0$, $f_{Z|S}(0)$ may become severely underestimated and $EX$ overestimated. Finding an estimate of $EX$ in such situations without making more assumptions seems difficult, essentially because short adherence times present in this situation hardly show up in the observed data as a result of the biased sampling. Alternatively, one could make some distributional assumptions about $f_X(x)$ and fit a parametric model by maximising the likelihood $$ L(\theta)=\prod_{i=1}^n \frac{1-F_X(z_i;\theta)}{EX(\theta)} \tag{4} $$ numerically (blue curve in above figure). R code simulating data and implementing both methods: # Simulate lognormal duration length in population set.seed(1) n <- 1e+4 x <- rlnorm(n,mean=2,sd=.2) # Biased sampling y <- sample(x, size=n/10, prob=x, replace=TRUE) # Duration at time of sampling z <- runif(length(y),min=0, max=y) hist(z,prob=TRUE,main="") # Compute kernel density estimate with reflection aroudn z=0 to <- max(x) + 3 fhat <- density(z,from = -to, to=to) m <- length(fhat$y) fhat$y <- fhat$y[(m/2+1):m] + fhat$y[(m/2):1] fhat$x <- fhat$x[(m/2+1):m] lines(fhat,col="red") # Estimate of EX 1/fhat$y[1] #> [1] 7.032448 # True value (mean of above lognormal) exp(2+.2^2/2) #> [1] 7.538325 # Maximum likelihood nll <- function(theta, z) { - sum(plnorm(z, theta[1], theta[2], log.p=TRUE, lower.tail = FALSE)) + length(z)*(theta[1] + theta[2]^2/2) } fit <- optim(c(0,1),nll,z=z) fit$par #> [1] 1.9860464 0.2019859 EXhat <- exp(fit$par[1]+fit$par[2]^2/2) # MLE of EX EXhat #> [1] 7.436836 curve(plnorm(z, fit$par[1], fit$par[2], lower.tail=FALSE)/EXhat, xname="z", col="blue",add=TRUE)
How to calculate average length of adherence to vegetarianism when we only have survey data about cu Let $f_X(x)$ denote the pdf of adherence length $X$ of vegetarianism in the population. Our objective is to estimate $EX=\int_0^\infty x f_X(x)\;dx$. Assuming that the probability of being included i
14,997
How to calculate average length of adherence to vegetarianism when we only have survey data about current vegetarians?
(I've dithered over adding this, as it appears @JarleTufto has already given a nice mathematical approach; However I'm not clever enough to understand his answer, and now I'm curious if it is exactly the same approach, or if the approach I describe below ever has its uses.) What I would do is guess an average length, and guess a few distributions around it, and then, for each, make a simulation of my population, and sample it regularly. You said to assume the total population of vegetarians is not changing, so each time my model has someone stopping, a brand new vegetarian is created. We need to run the model for a number of simulated years to make sure it has settled down, before we can start to sample. After that I think you can take samples every simulated month (*) until you have enough to form your 90% confidence interval. *: or whatever resolution works with your data. If people gave their answer to the nearest year, sampling every 6 months is good enough. Out of all your guesses, you choose the mean and distribution which (averaged over all the samples you took) gives you the closest result to what your real-life survey gave. I would iterate my guesses a few times, to narrow in on the best match. The best distribution may not be single-peaked. The ex-vegetarians I personally can think of stopped because of major lifestyle changes (typically marrying/living with a non-vegetarian, or moving country, or falling seriously ill and a doctor suggesting it might be diet); on the other side is the power of habit: the longer you've been a vegetarian the more likely you are to carry on being one. If your data had asked age and relationship status, we could throw that in the above simulation too.
How to calculate average length of adherence to vegetarianism when we only have survey data about cu
(I've dithered over adding this, as it appears @JarleTufto has already given a nice mathematical approach; However I'm not clever enough to understand his answer, and now I'm curious if it is exactly
How to calculate average length of adherence to vegetarianism when we only have survey data about current vegetarians? (I've dithered over adding this, as it appears @JarleTufto has already given a nice mathematical approach; However I'm not clever enough to understand his answer, and now I'm curious if it is exactly the same approach, or if the approach I describe below ever has its uses.) What I would do is guess an average length, and guess a few distributions around it, and then, for each, make a simulation of my population, and sample it regularly. You said to assume the total population of vegetarians is not changing, so each time my model has someone stopping, a brand new vegetarian is created. We need to run the model for a number of simulated years to make sure it has settled down, before we can start to sample. After that I think you can take samples every simulated month (*) until you have enough to form your 90% confidence interval. *: or whatever resolution works with your data. If people gave their answer to the nearest year, sampling every 6 months is good enough. Out of all your guesses, you choose the mean and distribution which (averaged over all the samples you took) gives you the closest result to what your real-life survey gave. I would iterate my guesses a few times, to narrow in on the best match. The best distribution may not be single-peaked. The ex-vegetarians I personally can think of stopped because of major lifestyle changes (typically marrying/living with a non-vegetarian, or moving country, or falling seriously ill and a doctor suggesting it might be diet); on the other side is the power of habit: the longer you've been a vegetarian the more likely you are to carry on being one. If your data had asked age and relationship status, we could throw that in the above simulation too.
How to calculate average length of adherence to vegetarianism when we only have survey data about cu (I've dithered over adding this, as it appears @JarleTufto has already given a nice mathematical approach; However I'm not clever enough to understand his answer, and now I'm curious if it is exactly
14,998
How will random effects with only 1 observation affect a generalized linear mixed model?
In general, you have an issue with identifiability. Linear models with a random effect assigned to a parameter with only one measurement can't distinguish between the random effect and the residual error. A typical linear mixed effect equation will look like: $E = \beta + \eta_i + \epsilon_j$ Where $\beta$ is the fixed effect, $\eta_i$ is the random effect for level $i$, and $\epsilon_j$ is the residual variability for the $j$th measurement. When you have only one observation of a level with a random effect, it is difficult to distinguish between $\eta$ and $\epsilon$. You will (typically) be fitting a variance or standard deviation to $\eta$ and $\epsilon$, so with only one measure per individual, you will be not be as certain that you have an accurate estimate for $SD(\eta)$ and $SD(\epsilon)$, but the estimate of the sum of the variances ($var(\eta) + var(\epsilon)$) should be relatively robust. On to the practical answer: If you have about 1/3 of your observations with a single observation per individual, you are probably OK overall. The rest of the population should provide a reasonable estimate for $SD(\eta)$ and $SD(\epsilon)$, and these individuals should be minor contributors overall. On the other hand, if you have all individuals at a specific fixed effect and random effect with a single measure (e.g. for your example, perhaps all of a population-- perhaps that means species for you), then you would trust the result less.
How will random effects with only 1 observation affect a generalized linear mixed model?
In general, you have an issue with identifiability. Linear models with a random effect assigned to a parameter with only one measurement can't distinguish between the random effect and the residual e
How will random effects with only 1 observation affect a generalized linear mixed model? In general, you have an issue with identifiability. Linear models with a random effect assigned to a parameter with only one measurement can't distinguish between the random effect and the residual error. A typical linear mixed effect equation will look like: $E = \beta + \eta_i + \epsilon_j$ Where $\beta$ is the fixed effect, $\eta_i$ is the random effect for level $i$, and $\epsilon_j$ is the residual variability for the $j$th measurement. When you have only one observation of a level with a random effect, it is difficult to distinguish between $\eta$ and $\epsilon$. You will (typically) be fitting a variance or standard deviation to $\eta$ and $\epsilon$, so with only one measure per individual, you will be not be as certain that you have an accurate estimate for $SD(\eta)$ and $SD(\epsilon)$, but the estimate of the sum of the variances ($var(\eta) + var(\epsilon)$) should be relatively robust. On to the practical answer: If you have about 1/3 of your observations with a single observation per individual, you are probably OK overall. The rest of the population should provide a reasonable estimate for $SD(\eta)$ and $SD(\epsilon)$, and these individuals should be minor contributors overall. On the other hand, if you have all individuals at a specific fixed effect and random effect with a single measure (e.g. for your example, perhaps all of a population-- perhaps that means species for you), then you would trust the result less.
How will random effects with only 1 observation affect a generalized linear mixed model? In general, you have an issue with identifiability. Linear models with a random effect assigned to a parameter with only one measurement can't distinguish between the random effect and the residual e
14,999
How will random effects with only 1 observation affect a generalized linear mixed model?
This example used poisson distribution, which defaults to link log, right? I'd expect the random effect, even if ALL groups had one observation, to estimate the variance in the log, whereas the residual error would then measure the error in the prediction including the random effect. Example, 10 observations, first without random effect: summary(pp <- glmmTMB(nvn~offset(log(vnhr)),data=foc10,family="poisson")) Family: poisson ( log ) Formula: nvn ~ offset(log(vnhr)) Data: foc10 AIC BIC logLik deviance df.resid 111.5 111.8 -54.7 109.5 9 Conditional model: Estimate Std. Error z value Pr(>|z|) (Intercept) -1.14680 0.09129 -12.56 <2e-16 *** and now with random effect > summary(pp <- glmmTMB(nvn~offset(log(vnhr))+(1|focal),data=foc10,family="poisson")) Family: poisson ( log ) Formula: nvn ~ offset(log(vnhr)) + (1 | focal) Data: foc10 AIC BIC logLik deviance df.resid 54.1 54.7 -25.0 50.1 8 [ notice much lower AIC ] Random effects: Conditional model: Groups Name Variance Std.Dev. focal (Intercept) 5.088 2.256 Number of obs: 10, groups: focal, 10 Conditional model: Estimate Std. Error z value Pr(>|z|) (Intercept) -2.692 1.166 -2.309 0.0209 * In any case, there are no convergence complaints. Whereas there are if I leave out the poisson.
How will random effects with only 1 observation affect a generalized linear mixed model?
This example used poisson distribution, which defaults to link log, right? I'd expect the random effect, even if ALL groups had one observation, to estimate the variance in the log, whereas the residu
How will random effects with only 1 observation affect a generalized linear mixed model? This example used poisson distribution, which defaults to link log, right? I'd expect the random effect, even if ALL groups had one observation, to estimate the variance in the log, whereas the residual error would then measure the error in the prediction including the random effect. Example, 10 observations, first without random effect: summary(pp <- glmmTMB(nvn~offset(log(vnhr)),data=foc10,family="poisson")) Family: poisson ( log ) Formula: nvn ~ offset(log(vnhr)) Data: foc10 AIC BIC logLik deviance df.resid 111.5 111.8 -54.7 109.5 9 Conditional model: Estimate Std. Error z value Pr(>|z|) (Intercept) -1.14680 0.09129 -12.56 <2e-16 *** and now with random effect > summary(pp <- glmmTMB(nvn~offset(log(vnhr))+(1|focal),data=foc10,family="poisson")) Family: poisson ( log ) Formula: nvn ~ offset(log(vnhr)) + (1 | focal) Data: foc10 AIC BIC logLik deviance df.resid 54.1 54.7 -25.0 50.1 8 [ notice much lower AIC ] Random effects: Conditional model: Groups Name Variance Std.Dev. focal (Intercept) 5.088 2.256 Number of obs: 10, groups: focal, 10 Conditional model: Estimate Std. Error z value Pr(>|z|) (Intercept) -2.692 1.166 -2.309 0.0209 * In any case, there are no convergence complaints. Whereas there are if I leave out the poisson.
How will random effects with only 1 observation affect a generalized linear mixed model? This example used poisson distribution, which defaults to link log, right? I'd expect the random effect, even if ALL groups had one observation, to estimate the variance in the log, whereas the residu
15,000
Modern Use Cases of Restricted Boltzmann Machines (RBM's)?
This is kind of an old question, but since it asks essentially asks for 'best practices', rather than what is actually technically possible (ie, doesnt need too much research focus), current best practices is something like: RBMs are not normally used currently linear models (linear regression, logistic regression) are used where possible otherwise deep feed-forward networks with layers such as fully-connected layers, convolutional layers, and throwing in some kind of regularization layers, such as dropout, and lately batch-normalization of course with activation layers in between, typically ReLU, but tanh and sigmoid are used too and probably some max-poolings (not always: average poolings and others are used too) For generative usages, common techniques include: GAN, and its zillions of variants, http://www.cs.toronto.edu/~dtarlow/pos14/talks/goodfellow.pdf auto-encoders, but recently they tend to be being replaced by: variational auto-encoders, VAE, https://arxiv.org/abs/1312.6114 generative CNNs, wavenet: https://deepmind.com/blog/wavenet-generative-model-raw-audio/ RNNs, eg seq2seq https://arxiv.org/pdf/1409.3215v3.pdf
Modern Use Cases of Restricted Boltzmann Machines (RBM's)?
This is kind of an old question, but since it asks essentially asks for 'best practices', rather than what is actually technically possible (ie, doesnt need too much research focus), current best prac
Modern Use Cases of Restricted Boltzmann Machines (RBM's)? This is kind of an old question, but since it asks essentially asks for 'best practices', rather than what is actually technically possible (ie, doesnt need too much research focus), current best practices is something like: RBMs are not normally used currently linear models (linear regression, logistic regression) are used where possible otherwise deep feed-forward networks with layers such as fully-connected layers, convolutional layers, and throwing in some kind of regularization layers, such as dropout, and lately batch-normalization of course with activation layers in between, typically ReLU, but tanh and sigmoid are used too and probably some max-poolings (not always: average poolings and others are used too) For generative usages, common techniques include: GAN, and its zillions of variants, http://www.cs.toronto.edu/~dtarlow/pos14/talks/goodfellow.pdf auto-encoders, but recently they tend to be being replaced by: variational auto-encoders, VAE, https://arxiv.org/abs/1312.6114 generative CNNs, wavenet: https://deepmind.com/blog/wavenet-generative-model-raw-audio/ RNNs, eg seq2seq https://arxiv.org/pdf/1409.3215v3.pdf
Modern Use Cases of Restricted Boltzmann Machines (RBM's)? This is kind of an old question, but since it asks essentially asks for 'best practices', rather than what is actually technically possible (ie, doesnt need too much research focus), current best prac