idx
int64
1
56k
question
stringlengths
15
155
answer
stringlengths
2
29.2k
question_cut
stringlengths
15
100
answer_cut
stringlengths
2
200
conversation
stringlengths
47
29.3k
conversation_cut
stringlengths
47
301
28,601
How to best handle subscores in a meta-analysis?
I agree it's a tricky situation. These are just a few thoughts. Whether to average d effect sizes: If you're not interested in subscales, then my first choice would be to take the average effect size for the subscales in a given study. That assumes that all subscales are equally relevant to your research question. If some scales are more relevant, then I might just use those subscales. If you are interested in differences between subscales, then it makes sense to include the effect size for each subscale coded for type. Standard error of d effect sizes: Presumably you are using a formula to calculate the standard error of d based on the value of d and the group sample sizes. Adapting this formula, we get $$se(d) = \sqrt{\left( \frac{n_1 + n_2}{n_1 n_2} + \frac{d^2}{2(n_1+n_2-2)}\right) \left(\frac{n_1 + n_2}{n_1+n_2-2} \right)}, $$ where $n_1$ and $n_2$ are the sample sizes of the two groups being compared and $d$ is Cohen's $d$. I imagine you could apply such a formula to calculate the standard error to the average d value for the subscales.
How to best handle subscores in a meta-analysis?
I agree it's a tricky situation. These are just a few thoughts. Whether to average d effect sizes: If you're not interested in subscales, then my first choice would be to take the average effect size
How to best handle subscores in a meta-analysis? I agree it's a tricky situation. These are just a few thoughts. Whether to average d effect sizes: If you're not interested in subscales, then my first choice would be to take the average effect size for the subscales in a given study. That assumes that all subscales are equally relevant to your research question. If some scales are more relevant, then I might just use those subscales. If you are interested in differences between subscales, then it makes sense to include the effect size for each subscale coded for type. Standard error of d effect sizes: Presumably you are using a formula to calculate the standard error of d based on the value of d and the group sample sizes. Adapting this formula, we get $$se(d) = \sqrt{\left( \frac{n_1 + n_2}{n_1 n_2} + \frac{d^2}{2(n_1+n_2-2)}\right) \left(\frac{n_1 + n_2}{n_1+n_2-2} \right)}, $$ where $n_1$ and $n_2$ are the sample sizes of the two groups being compared and $d$ is Cohen's $d$. I imagine you could apply such a formula to calculate the standard error to the average d value for the subscales.
How to best handle subscores in a meta-analysis? I agree it's a tricky situation. These are just a few thoughts. Whether to average d effect sizes: If you're not interested in subscales, then my first choice would be to take the average effect size
28,602
How to compare two regression slopes for one predictor on two different outcomes?
Okay, let's look at your situation. You have basically two regressions (APD = antero-posterior diameter, NOL = naso-occipital length, HL = humeral length): $APD=\beta_{0,1} + \beta_{1,1}\cdot NOL$ $HL=\beta_{0,2} + \beta_{1,2}\cdot NOL$ To test the hypothesis $\beta_{1,1}=\beta_{1,2}$, you can do the following: Create a new dependent variable ($Y_{new}$) by just appending APD to HL Create a new independent variable by appending NOL to itself ($X_{new}$) (i.e. duplicating NOL) Create a dummy variable ($D$) that is 1 if the data came from the second dataset (with HL) and 0 if the data came from the first dataset (APD). Calculate the regression with $Y_{new}$ as dependent variable, and the main effects and the interaction between $X_{new}$ and the dummy variable $D$ as explanatory variables. EDIT @Jake Westfall pointed out that the residual standard error could be different for the two regressions for each DV. Jake provided the answer which is to fit a generalized least squares model (GLS) which allows the residual standard error to differ between the two regressions. Let's look at an example with made-up data (in R): # Create artificial data library(nlme) # needed for the generalized least squares set.seed(1500) NOL <- rnorm(10000,100,12) APD <- 10 + 15*NOL+ rnorm(10000,0,2) HL <- - 2 - 5*NOL+ rnorm(10000,0,3) mod1 <- lm(APD~NOL) mod1 Coefficients: (Intercept) NOL 10.11 15.00 mod2 <- lm(HL~NOL) mod2 Coefficients: (Intercept) NOL -1.96 -5.00 # Combine the dependent variables and duplicate the independent variable y.new <- c(APD, HL) x.new <- c(NOL, NOL) # Create a dummy variable that is 0 if the data are from the first data set (APD) and 1 if they are from the second dataset (HL) dummy.var <- c(rep(0, length(APD)), rep(1, length(HL))) # Generalized least squares model allowing for differend residual SDs for each regression (strata of dummy.var) gls.mod3 <- gls(y.new~x.new*dummy.var, weights=varIdent(form=~1|dummy.var)) Variance function: Structure: Different standard deviations per stratum Formula: ~1 | dummy.var Parameter estimates: 0 1 1.000000 1.481274 Coefficients: Value Std.Error t-value p-value (Intercept) 10.10886 0.17049120 59.293 0 x.new 14.99877 0.00169164 8866.430 0 dummy.var -12.06858 0.30470618 -39.607 0 x.new:dummy.var -19.99917 0.00302333 -6614.939 0 Note: The intercept and the slope for $X_{new}$ are exactly the same as in the first regression (mod1). The coefficient of dummy.var denotes the difference between the intercept of the two regressions. Further: the residual standard deviation of the second regression was estimated larger than the SD of the first (about 1.5 times larger). This is exactly what we have specified in the generation of the data (2 vs. 3). We're nearly there: The coefficient of the interaction term (x.new:dummy.var) tests the equality of the slopes. Here the slope of the second regression (mod2) is about $\beta_{x.new} - \beta_{x.new\times dummy.var}$ or about $15-20=-5$. The difference of $20$ is exactly what we've specified when we generated the data. If you work in Stata, there is a nice explanation here. Warning: This does only work if the antero-posterior diameter and naso-occipital length (the two dependent variables) are independent. Otherwise it can get very complicated. EDIT These two posts on the site deal with the same question: First and second.
How to compare two regression slopes for one predictor on two different outcomes?
Okay, let's look at your situation. You have basically two regressions (APD = antero-posterior diameter, NOL = naso-occipital length, HL = humeral length): $APD=\beta_{0,1} + \beta_{1,1}\cdot NOL$ $H
How to compare two regression slopes for one predictor on two different outcomes? Okay, let's look at your situation. You have basically two regressions (APD = antero-posterior diameter, NOL = naso-occipital length, HL = humeral length): $APD=\beta_{0,1} + \beta_{1,1}\cdot NOL$ $HL=\beta_{0,2} + \beta_{1,2}\cdot NOL$ To test the hypothesis $\beta_{1,1}=\beta_{1,2}$, you can do the following: Create a new dependent variable ($Y_{new}$) by just appending APD to HL Create a new independent variable by appending NOL to itself ($X_{new}$) (i.e. duplicating NOL) Create a dummy variable ($D$) that is 1 if the data came from the second dataset (with HL) and 0 if the data came from the first dataset (APD). Calculate the regression with $Y_{new}$ as dependent variable, and the main effects and the interaction between $X_{new}$ and the dummy variable $D$ as explanatory variables. EDIT @Jake Westfall pointed out that the residual standard error could be different for the two regressions for each DV. Jake provided the answer which is to fit a generalized least squares model (GLS) which allows the residual standard error to differ between the two regressions. Let's look at an example with made-up data (in R): # Create artificial data library(nlme) # needed for the generalized least squares set.seed(1500) NOL <- rnorm(10000,100,12) APD <- 10 + 15*NOL+ rnorm(10000,0,2) HL <- - 2 - 5*NOL+ rnorm(10000,0,3) mod1 <- lm(APD~NOL) mod1 Coefficients: (Intercept) NOL 10.11 15.00 mod2 <- lm(HL~NOL) mod2 Coefficients: (Intercept) NOL -1.96 -5.00 # Combine the dependent variables and duplicate the independent variable y.new <- c(APD, HL) x.new <- c(NOL, NOL) # Create a dummy variable that is 0 if the data are from the first data set (APD) and 1 if they are from the second dataset (HL) dummy.var <- c(rep(0, length(APD)), rep(1, length(HL))) # Generalized least squares model allowing for differend residual SDs for each regression (strata of dummy.var) gls.mod3 <- gls(y.new~x.new*dummy.var, weights=varIdent(form=~1|dummy.var)) Variance function: Structure: Different standard deviations per stratum Formula: ~1 | dummy.var Parameter estimates: 0 1 1.000000 1.481274 Coefficients: Value Std.Error t-value p-value (Intercept) 10.10886 0.17049120 59.293 0 x.new 14.99877 0.00169164 8866.430 0 dummy.var -12.06858 0.30470618 -39.607 0 x.new:dummy.var -19.99917 0.00302333 -6614.939 0 Note: The intercept and the slope for $X_{new}$ are exactly the same as in the first regression (mod1). The coefficient of dummy.var denotes the difference between the intercept of the two regressions. Further: the residual standard deviation of the second regression was estimated larger than the SD of the first (about 1.5 times larger). This is exactly what we have specified in the generation of the data (2 vs. 3). We're nearly there: The coefficient of the interaction term (x.new:dummy.var) tests the equality of the slopes. Here the slope of the second regression (mod2) is about $\beta_{x.new} - \beta_{x.new\times dummy.var}$ or about $15-20=-5$. The difference of $20$ is exactly what we've specified when we generated the data. If you work in Stata, there is a nice explanation here. Warning: This does only work if the antero-posterior diameter and naso-occipital length (the two dependent variables) are independent. Otherwise it can get very complicated. EDIT These two posts on the site deal with the same question: First and second.
How to compare two regression slopes for one predictor on two different outcomes? Okay, let's look at your situation. You have basically two regressions (APD = antero-posterior diameter, NOL = naso-occipital length, HL = humeral length): $APD=\beta_{0,1} + \beta_{1,1}\cdot NOL$ $H
28,603
Implementation of Dirichlet cdf?
Remember that, if $Y_i$ are independent $\mathrm{Gamma}(a_i,b)$, for $i=1,\dots,k$, then $$ (X_1,\dots,X_k) = \left(\frac{Y_1}{\sum_{j=1}^k Y_j}, \dots, \frac{Y_k}{\sum_{j=1}^k Y_j} \right) \sim \mathrm{Dirichlet}(a_1,\dots,a_k) \, .$$ The proof can be found on page 594 of Luc Devroye's book. Therefore, one possibility is to compute a Monte Carlo approximation of $$ F_{X_1,\dots,X_k}(t_1,\dots,t_k)=P\left\{X_1\leq t_1,\dots, X_k\leq t_k\right\} \, , $$ starting with gammas. In R, try this: pdirichlet <- function(a, t) { N <- 10000 rdirichlet <- function(a) { y <- rgamma(length(a), a, 1); y / sum(y) } x <- replicate(N, rdirichlet(a), simplify = FALSE) sum(sapply(x, function(x) prod(x <= t))) / N } I didn't check the code. Use it carefully. If you find any bugs, please tell us.
Implementation of Dirichlet cdf?
Remember that, if $Y_i$ are independent $\mathrm{Gamma}(a_i,b)$, for $i=1,\dots,k$, then $$ (X_1,\dots,X_k) = \left(\frac{Y_1}{\sum_{j=1}^k Y_j}, \dots, \frac{Y_k}{\sum_{j=1}^k Y_j} \right) \sim \math
Implementation of Dirichlet cdf? Remember that, if $Y_i$ are independent $\mathrm{Gamma}(a_i,b)$, for $i=1,\dots,k$, then $$ (X_1,\dots,X_k) = \left(\frac{Y_1}{\sum_{j=1}^k Y_j}, \dots, \frac{Y_k}{\sum_{j=1}^k Y_j} \right) \sim \mathrm{Dirichlet}(a_1,\dots,a_k) \, .$$ The proof can be found on page 594 of Luc Devroye's book. Therefore, one possibility is to compute a Monte Carlo approximation of $$ F_{X_1,\dots,X_k}(t_1,\dots,t_k)=P\left\{X_1\leq t_1,\dots, X_k\leq t_k\right\} \, , $$ starting with gammas. In R, try this: pdirichlet <- function(a, t) { N <- 10000 rdirichlet <- function(a) { y <- rgamma(length(a), a, 1); y / sum(y) } x <- replicate(N, rdirichlet(a), simplify = FALSE) sum(sapply(x, function(x) prod(x <= t))) / N } I didn't check the code. Use it carefully. If you find any bugs, please tell us.
Implementation of Dirichlet cdf? Remember that, if $Y_i$ are independent $\mathrm{Gamma}(a_i,b)$, for $i=1,\dots,k$, then $$ (X_1,\dots,X_k) = \left(\frac{Y_1}{\sum_{j=1}^k Y_j}, \dots, \frac{Y_k}{\sum_{j=1}^k Y_j} \right) \sim \math
28,604
Implementation of Dirichlet cdf?
Any library? Mathematica has it. Here's the code for an example plot of a Dirichlet CDF from the documentation: Plot3D[CDF[DirichletDistribution[{1, 3, 2}], {x, y}], {x, 0, 1}, {y, 0, 1}]
Implementation of Dirichlet cdf?
Any library? Mathematica has it. Here's the code for an example plot of a Dirichlet CDF from the documentation: Plot3D[CDF[DirichletDistribution[{1, 3, 2}], {x, y}], {x, 0, 1}, {y, 0, 1}]
Implementation of Dirichlet cdf? Any library? Mathematica has it. Here's the code for an example plot of a Dirichlet CDF from the documentation: Plot3D[CDF[DirichletDistribution[{1, 3, 2}], {x, y}], {x, 0, 1}, {y, 0, 1}]
Implementation of Dirichlet cdf? Any library? Mathematica has it. Here's the code for an example plot of a Dirichlet CDF from the documentation: Plot3D[CDF[DirichletDistribution[{1, 3, 2}], {x, y}], {x, 0, 1}, {y, 0, 1}]
28,605
Meaning of p-value of logistic regression model variables
Basically, it looks like you are having a multicollinearity problem. There is a lot of material available about this, starting on this website or on wikipedia. Briefly, the two predictors appear to be genuinely related to your outcome but they are also probably highly correlated with each other (note that with more than two variables, it's still possible to have multicollinearity issues without strong bivariate correlations). This does of course make a lot of sense: All emails clicked within 24 hours have also been clicked within 7 days (by definition) and most emails have probably not been clicked at all (not in 24 hours and not in 7 days). One way this shows in the output you presented is through the incredibly large standard errors/CI for the relevant coefficients (judging by the fact you are using bigglm and that even tiny coefficients are highly significant, it seems your sample size should be more than enough to get good estimates). Other things you can do to detect this type of problems: Look at pairwise correlations, remove only one of the suspect variables (as suggested by @Nick Sabbe), test significance for both variables jointly. More generally, high p-values do not mean that the effect is small or random but only that there is no evidence that the coefficient is different from 0. It can also be very large, you just don't know (either because the sample size is too small or because there is some other issue with the model).
Meaning of p-value of logistic regression model variables
Basically, it looks like you are having a multicollinearity problem. There is a lot of material available about this, starting on this website or on wikipedia. Briefly, the two predictors appear to be
Meaning of p-value of logistic regression model variables Basically, it looks like you are having a multicollinearity problem. There is a lot of material available about this, starting on this website or on wikipedia. Briefly, the two predictors appear to be genuinely related to your outcome but they are also probably highly correlated with each other (note that with more than two variables, it's still possible to have multicollinearity issues without strong bivariate correlations). This does of course make a lot of sense: All emails clicked within 24 hours have also been clicked within 7 days (by definition) and most emails have probably not been clicked at all (not in 24 hours and not in 7 days). One way this shows in the output you presented is through the incredibly large standard errors/CI for the relevant coefficients (judging by the fact you are using bigglm and that even tiny coefficients are highly significant, it seems your sample size should be more than enough to get good estimates). Other things you can do to detect this type of problems: Look at pairwise correlations, remove only one of the suspect variables (as suggested by @Nick Sabbe), test significance for both variables jointly. More generally, high p-values do not mean that the effect is small or random but only that there is no evidence that the coefficient is different from 0. It can also be very large, you just don't know (either because the sample size is too small or because there is some other issue with the model).
Meaning of p-value of logistic regression model variables Basically, it looks like you are having a multicollinearity problem. There is a lot of material available about this, starting on this website or on wikipedia. Briefly, the two predictors appear to be
28,606
MLE/Likelihood of lognormally distributed interval
It sounds like you might not be computing the likelihood correctly. When all you know about a value $x$ is that It is obtained independently from a distribution $F_\theta$ and It lies between $a$ and $b \gt a$ inclusive (where $b$ and $a$ are independent of $x$), then (by definition) its likelihood is $${\Pr}_{F_\theta}(a \le x \le b) = F_\theta(b) - F_\theta(a).$$ The likelihood of a set of independent observations therefore is the product of such expressions, one per observation. The log-likelihood, as usual, will be the sum of logarithms of those expressions. As an example, here is an R implementation where the values of $a$ are in the vector left, the values of $b$ in the vector right, and $F_\theta$ is Lognormal. (This is not a general-purpose solution; in particular, it assumes that $b \gt a$ and $b \ne a$ for all the data.) # # Lognormal log-likelihood for interval data. # lambda <- function(mu, sigma, left, right) { sum(log(pnorm(log(right), mu, sigma) - pnorm(log(left), mu, sigma))) } To find the maximum log likelihood we need a reasonable set of starting values for the log mean $\mu$ and log standard deviation $\sigma$. This estimate replaces each interval by the geometric mean of its endpoints: # # Create an initial estimate of lognormal parameters for interval data. # lambda.init <- function(left, right) { mid <- log(left * right)/2 c(mean(mid), sd(mid)) } Let's generate some random lognormally distributed data and bin them into intervals: set.seed(17) n <- 12 # Number of data z <- exp(rnorm(n, 6, .5)) # Mean = 6, SD = 0.5 left <- 100 * floor(z/100) # Bin into multiples of 100 right <- left + 100 The fitting can be performed by a general-purpose multivariate optimizer. (This one is a minimizer by default, so it must be applied to the negative of the log-likelihood.) fit <- optim(lambda.init(left,right), fn=function(theta) -lambda(theta[1], theta[2], left, right)) fit$par 6.1188785 0.3957045 The estimate of $\mu$ is $6.12$, not far from the intended value of $6$, and the estimate of $\sigma$ is $0.40$, not far from the intended value of $0.5$: not bad for just $12$ values. To see how good the fit is, let's plot the empirical cumulative distribution function and the fitted distribution function. To construct the ECDF, I just interpolate linearly through each interval: # # ECDF of the data. # F <- function(x) (1 + mean((abs(x - left) - abs(x - right)) / (right - left)))/2 y <- sapply(x <- seq(min(left) * 0.8, max(right) / 0.8, 1), F) plot(x, y, type="l", lwd=2, lty=2, ylab="Cumulative probability") curve(pnorm(log(x), fit$par[1], fit$par[2]), from=min(x), to=max(x), col="Red", lwd=2, add=TRUE) Because the vertical deviations are consistently small and vary both up and down, it looks like a good fit.
MLE/Likelihood of lognormally distributed interval
It sounds like you might not be computing the likelihood correctly. When all you know about a value $x$ is that It is obtained independently from a distribution $F_\theta$ and It lies between $a$ an
MLE/Likelihood of lognormally distributed interval It sounds like you might not be computing the likelihood correctly. When all you know about a value $x$ is that It is obtained independently from a distribution $F_\theta$ and It lies between $a$ and $b \gt a$ inclusive (where $b$ and $a$ are independent of $x$), then (by definition) its likelihood is $${\Pr}_{F_\theta}(a \le x \le b) = F_\theta(b) - F_\theta(a).$$ The likelihood of a set of independent observations therefore is the product of such expressions, one per observation. The log-likelihood, as usual, will be the sum of logarithms of those expressions. As an example, here is an R implementation where the values of $a$ are in the vector left, the values of $b$ in the vector right, and $F_\theta$ is Lognormal. (This is not a general-purpose solution; in particular, it assumes that $b \gt a$ and $b \ne a$ for all the data.) # # Lognormal log-likelihood for interval data. # lambda <- function(mu, sigma, left, right) { sum(log(pnorm(log(right), mu, sigma) - pnorm(log(left), mu, sigma))) } To find the maximum log likelihood we need a reasonable set of starting values for the log mean $\mu$ and log standard deviation $\sigma$. This estimate replaces each interval by the geometric mean of its endpoints: # # Create an initial estimate of lognormal parameters for interval data. # lambda.init <- function(left, right) { mid <- log(left * right)/2 c(mean(mid), sd(mid)) } Let's generate some random lognormally distributed data and bin them into intervals: set.seed(17) n <- 12 # Number of data z <- exp(rnorm(n, 6, .5)) # Mean = 6, SD = 0.5 left <- 100 * floor(z/100) # Bin into multiples of 100 right <- left + 100 The fitting can be performed by a general-purpose multivariate optimizer. (This one is a minimizer by default, so it must be applied to the negative of the log-likelihood.) fit <- optim(lambda.init(left,right), fn=function(theta) -lambda(theta[1], theta[2], left, right)) fit$par 6.1188785 0.3957045 The estimate of $\mu$ is $6.12$, not far from the intended value of $6$, and the estimate of $\sigma$ is $0.40$, not far from the intended value of $0.5$: not bad for just $12$ values. To see how good the fit is, let's plot the empirical cumulative distribution function and the fitted distribution function. To construct the ECDF, I just interpolate linearly through each interval: # # ECDF of the data. # F <- function(x) (1 + mean((abs(x - left) - abs(x - right)) / (right - left)))/2 y <- sapply(x <- seq(min(left) * 0.8, max(right) / 0.8, 1), F) plot(x, y, type="l", lwd=2, lty=2, ylab="Cumulative probability") curve(pnorm(log(x), fit$par[1], fit$par[2]), from=min(x), to=max(x), col="Red", lwd=2, add=TRUE) Because the vertical deviations are consistently small and vary both up and down, it looks like a good fit.
MLE/Likelihood of lognormally distributed interval It sounds like you might not be computing the likelihood correctly. When all you know about a value $x$ is that It is obtained independently from a distribution $F_\theta$ and It lies between $a$ an
28,607
Discrete variables in regression model?
The word "factor" should be used more carefully, because for some statisticians and some software packages "factor" can mean categorical variable (e.g. different types of treatments, sex, countries of origin, etc.) A "continuous factor" would sound like "corner of a circle" and confuse the heck out of the people. You may, in future, be able to more clearly express your idea if you just describe it as a "discrete independent variable." Both continuous (number so fine that you can't name the exact point) and discrete (consists of whole numbers) variables are considered as interval/ratio. They are treated the same way when used as an independent variable in linear regression analysis. The way to discern an interval/ratio variable is to ask if every unit increment in the variable indicates the same amount of increment in the context you wish you measure. For instance, the jump from 35 to 36 degrees is the same as the jump from 43 to 44; it's the same amount of temperature difference. Likewise, the jump from 100 to 101 subscribers is the same as the jump from 1009 to 1010 subscribers. As long as this is true, your regression coefficient of that independent variable will make sense, because you can legitimately interpret it as the slope of the regression line. General confusion appears when you mix in ordinal data, such as those 5-point "how satisfied are you?" questions. They are expressed in whole number, very easily to be confused with discrete data. However, each jump in the scale does not necessarily mean the same thing. E.g. a jump from "4: happy" to "5: very happy" is not necessarily the same as a jump from "1: very unhappy" to "2: unhappy." In that case, the variable should not be put into the regression as is, but treated differently (search "dummy variable in regression" to learn more.)
Discrete variables in regression model?
The word "factor" should be used more carefully, because for some statisticians and some software packages "factor" can mean categorical variable (e.g. different types of treatments, sex, countries of
Discrete variables in regression model? The word "factor" should be used more carefully, because for some statisticians and some software packages "factor" can mean categorical variable (e.g. different types of treatments, sex, countries of origin, etc.) A "continuous factor" would sound like "corner of a circle" and confuse the heck out of the people. You may, in future, be able to more clearly express your idea if you just describe it as a "discrete independent variable." Both continuous (number so fine that you can't name the exact point) and discrete (consists of whole numbers) variables are considered as interval/ratio. They are treated the same way when used as an independent variable in linear regression analysis. The way to discern an interval/ratio variable is to ask if every unit increment in the variable indicates the same amount of increment in the context you wish you measure. For instance, the jump from 35 to 36 degrees is the same as the jump from 43 to 44; it's the same amount of temperature difference. Likewise, the jump from 100 to 101 subscribers is the same as the jump from 1009 to 1010 subscribers. As long as this is true, your regression coefficient of that independent variable will make sense, because you can legitimately interpret it as the slope of the regression line. General confusion appears when you mix in ordinal data, such as those 5-point "how satisfied are you?" questions. They are expressed in whole number, very easily to be confused with discrete data. However, each jump in the scale does not necessarily mean the same thing. E.g. a jump from "4: happy" to "5: very happy" is not necessarily the same as a jump from "1: very unhappy" to "2: unhappy." In that case, the variable should not be put into the regression as is, but treated differently (search "dummy variable in regression" to learn more.)
Discrete variables in regression model? The word "factor" should be used more carefully, because for some statisticians and some software packages "factor" can mean categorical variable (e.g. different types of treatments, sex, countries of
28,608
Discrete variables in regression model?
To further understand the similarities between continuous/discrete interval and ratio variables, consider measurement precision. A continuous variable can only be measured to a certain level of precision, and as such, in reality, can only take a discrete set of values. (ie- if you are measuring with a tool of precision 0.1, the only values you will receive are 0.1,0.2,0.3, etc.)
Discrete variables in regression model?
To further understand the similarities between continuous/discrete interval and ratio variables, consider measurement precision. A continuous variable can only be measured to a certain level of precis
Discrete variables in regression model? To further understand the similarities between continuous/discrete interval and ratio variables, consider measurement precision. A continuous variable can only be measured to a certain level of precision, and as such, in reality, can only take a discrete set of values. (ie- if you are measuring with a tool of precision 0.1, the only values you will receive are 0.1,0.2,0.3, etc.)
Discrete variables in regression model? To further understand the similarities between continuous/discrete interval and ratio variables, consider measurement precision. A continuous variable can only be measured to a certain level of precis
28,609
What is the Fisher information for the truncated poisson distribution?
In the last line of your derivation, you substituted the expectation of the Poisson distribution, rather than the expectation of the truncated Poisson distribution. Fix that, and the correct result should follow.
What is the Fisher information for the truncated poisson distribution?
In the last line of your derivation, you substituted the expectation of the Poisson distribution, rather than the expectation of the truncated Poisson distribution. Fix that, and the correct result sh
What is the Fisher information for the truncated poisson distribution? In the last line of your derivation, you substituted the expectation of the Poisson distribution, rather than the expectation of the truncated Poisson distribution. Fix that, and the correct result should follow.
What is the Fisher information for the truncated poisson distribution? In the last line of your derivation, you substituted the expectation of the Poisson distribution, rather than the expectation of the truncated Poisson distribution. Fix that, and the correct result sh
28,610
Do low silhouette widths mean the data has little underlying structure?
The ASW is a measure of the coherence of a clustering solution. A high ASW value means that the clusters are homogeneous (all observations are close to cluster center), and that they are well separated. According to Kaufmann and Rousseuw (1990), a value below 0.25 means that the data are not structured. Between 0.25 and 0.5, the data might be structured, but it might also be an artifice. Please keep in mind that these values are indicative and should not be used as a decision threshold. These values are not theoretically defined (there are not based on some p-value) but are based on the experience of the authors. Hence, according to these low ASW values, your data seems to be quite unstructured. If the purpose of the cluster analysis is only descriptive, then you can argue that it reveals some (but only some) of the most salient patterns. However, I think that in your case, you should not draw any theoretical conclusions from your clustering. You can also try to have a look at the "per cluster" ASW values (this is given by the function wcClusterQuality). Maybe some of your clusters are well-defined and some may be "spurious" (ASW<0), resulting in a low overall ASW value. You can try to use bootstrap strategies, which should give you a better hint. In R, the function clusterboot in the package fpc can be used for this purpose (look at the help page). However, it does not work with weighted data. If your data are unweighted, I think it is worth to give it a try. Finally, you may want to have a closer look at your data and your categorization. Maybe, your categories are too instable or not well defined. However, it does not seem to be the case here. As you have said, "lack of clearly differentiated clusters is not the same thing as a lack of interesting variation". There are other methods to analyse the variability of your sequences such as discrepancy analysis. These methods allow you to study the links between sequences and explanatory factors. You may, for instance, try to build sequence regression trees (function "seqtree" in package TraMineR).
Do low silhouette widths mean the data has little underlying structure?
The ASW is a measure of the coherence of a clustering solution. A high ASW value means that the clusters are homogeneous (all observations are close to cluster center), and that they are well separate
Do low silhouette widths mean the data has little underlying structure? The ASW is a measure of the coherence of a clustering solution. A high ASW value means that the clusters are homogeneous (all observations are close to cluster center), and that they are well separated. According to Kaufmann and Rousseuw (1990), a value below 0.25 means that the data are not structured. Between 0.25 and 0.5, the data might be structured, but it might also be an artifice. Please keep in mind that these values are indicative and should not be used as a decision threshold. These values are not theoretically defined (there are not based on some p-value) but are based on the experience of the authors. Hence, according to these low ASW values, your data seems to be quite unstructured. If the purpose of the cluster analysis is only descriptive, then you can argue that it reveals some (but only some) of the most salient patterns. However, I think that in your case, you should not draw any theoretical conclusions from your clustering. You can also try to have a look at the "per cluster" ASW values (this is given by the function wcClusterQuality). Maybe some of your clusters are well-defined and some may be "spurious" (ASW<0), resulting in a low overall ASW value. You can try to use bootstrap strategies, which should give you a better hint. In R, the function clusterboot in the package fpc can be used for this purpose (look at the help page). However, it does not work with weighted data. If your data are unweighted, I think it is worth to give it a try. Finally, you may want to have a closer look at your data and your categorization. Maybe, your categories are too instable or not well defined. However, it does not seem to be the case here. As you have said, "lack of clearly differentiated clusters is not the same thing as a lack of interesting variation". There are other methods to analyse the variability of your sequences such as discrepancy analysis. These methods allow you to study the links between sequences and explanatory factors. You may, for instance, try to build sequence regression trees (function "seqtree" in package TraMineR).
Do low silhouette widths mean the data has little underlying structure? The ASW is a measure of the coherence of a clustering solution. A high ASW value means that the clusters are homogeneous (all observations are close to cluster center), and that they are well separate
28,611
Box Cox Transforms for regression
The MASS package that comes with your R installed already, has the boxcox() function that you can use: After reading in the data, do: library(MASS) boxcox(y ~ x) Then look at the graph this produces, which shows graphically a 95% confidence interval for the boxcox transformation parameter. But you do not really have enough data (n=10) to do this, the resulting confidence interval goes almost from -2 to 2!, with a maximum likelihood estimate of approximately 0 (a log-transform, as said before). If your real data have more observations, you should try this. As others have said, this transformation is really trying to stabilize variances. This is not really obvious from theory, what it does, is to try to maximize a normal-distribution based likelihood function, which assumes constant variance. One could think that maximizing a normal-based likelihood would try to normalize the distribution of the residuals, but in practice the main contribution to maximizing the likelihood comes from stabilizing the variances. This is maybe not so surprising, given that the likelihood we maximizes is based on a constant variance normal distribution family! I once wrote a slider-based demo in XLispStat, which demonstrated this clearly!
Box Cox Transforms for regression
The MASS package that comes with your R installed already, has the boxcox() function that you can use: After reading in the data, do: library(MASS) boxcox(y ~ x) Then look at the graph this
Box Cox Transforms for regression The MASS package that comes with your R installed already, has the boxcox() function that you can use: After reading in the data, do: library(MASS) boxcox(y ~ x) Then look at the graph this produces, which shows graphically a 95% confidence interval for the boxcox transformation parameter. But you do not really have enough data (n=10) to do this, the resulting confidence interval goes almost from -2 to 2!, with a maximum likelihood estimate of approximately 0 (a log-transform, as said before). If your real data have more observations, you should try this. As others have said, this transformation is really trying to stabilize variances. This is not really obvious from theory, what it does, is to try to maximize a normal-distribution based likelihood function, which assumes constant variance. One could think that maximizing a normal-based likelihood would try to normalize the distribution of the residuals, but in practice the main contribution to maximizing the likelihood comes from stabilizing the variances. This is maybe not so surprising, given that the likelihood we maximizes is based on a constant variance normal distribution family! I once wrote a slider-based demo in XLispStat, which demonstrated this clearly!
Box Cox Transforms for regression The MASS package that comes with your R installed already, has the boxcox() function that you can use: After reading in the data, do: library(MASS) boxcox(y ~ x) Then look at the graph this
28,612
Box Cox Transforms for regression
When you have a linear relationship, but unequal variances then you generally need to transform both x and y to get a linear relationship with equal variances (or just use weighted least squares regression on the untransformed variables). The AVAS procedure can be used to suggest possible transformations.
Box Cox Transforms for regression
When you have a linear relationship, but unequal variances then you generally need to transform both x and y to get a linear relationship with equal variances (or just use weighted least squares regre
Box Cox Transforms for regression When you have a linear relationship, but unequal variances then you generally need to transform both x and y to get a linear relationship with equal variances (or just use weighted least squares regression on the untransformed variables). The AVAS procedure can be used to suggest possible transformations.
Box Cox Transforms for regression When you have a linear relationship, but unequal variances then you generally need to transform both x and y to get a linear relationship with equal variances (or just use weighted least squares regre
28,613
Box Cox Transforms for regression
Well, in R you could try this: library(MASS) boxcox(y~x) plot(1/y^2~x) # since the profile likelihood has a maximum near 2 But it really depends on what you mean by 'better fit to the data'
Box Cox Transforms for regression
Well, in R you could try this: library(MASS) boxcox(y~x) plot(1/y^2~x) # since the profile likelihood has a maximum near 2 But it really depends on what you mean by 'better fit to the data'
Box Cox Transforms for regression Well, in R you could try this: library(MASS) boxcox(y~x) plot(1/y^2~x) # since the profile likelihood has a maximum near 2 But it really depends on what you mean by 'better fit to the data'
Box Cox Transforms for regression Well, in R you could try this: library(MASS) boxcox(y~x) plot(1/y^2~x) # since the profile likelihood has a maximum near 2 But it really depends on what you mean by 'better fit to the data'
28,614
How to handle online time series forecast?
First you need to make a time-embedding of your data. E.g. take as the first input [1, 12, 2, 3] and the corresponding output [5], and as the second input you take [12, 2, 3, 5] and the corresponding output [9]. (This is embedding with delay 4 but you can choose another value that fits better. ) Now you have a valid prediction problem. To these data you can apply Online Gaussian Processes. This is a machine learning method which does exactly what you describe, and it provides confidence intervals. If your model is non-stationary you can try the non-stationary extension, kernel recursive least-squares tracker. By the way, that paper includes Matlab code for stationary and nonstationary cases. These methods are reasonably fast: their computational complexity is quadratic in terms of the number of data you store in memory (which is typically a small, representative part of all data processed). For faster methods I recommend for instance kernel least mean squares method, but their accuracy is less.
How to handle online time series forecast?
First you need to make a time-embedding of your data. E.g. take as the first input [1, 12, 2, 3] and the corresponding output [5], and as the second input you take [12, 2, 3, 5] and the corresponding
How to handle online time series forecast? First you need to make a time-embedding of your data. E.g. take as the first input [1, 12, 2, 3] and the corresponding output [5], and as the second input you take [12, 2, 3, 5] and the corresponding output [9]. (This is embedding with delay 4 but you can choose another value that fits better. ) Now you have a valid prediction problem. To these data you can apply Online Gaussian Processes. This is a machine learning method which does exactly what you describe, and it provides confidence intervals. If your model is non-stationary you can try the non-stationary extension, kernel recursive least-squares tracker. By the way, that paper includes Matlab code for stationary and nonstationary cases. These methods are reasonably fast: their computational complexity is quadratic in terms of the number of data you store in memory (which is typically a small, representative part of all data processed). For faster methods I recommend for instance kernel least mean squares method, but their accuracy is less.
How to handle online time series forecast? First you need to make a time-embedding of your data. E.g. take as the first input [1, 12, 2, 3] and the corresponding output [5], and as the second input you take [12, 2, 3, 5] and the corresponding
28,615
How to handle online time series forecast?
In your real-time system are the observation times inhomogenous and the data non-stationary? If you want something simple and fast I suggest using the inhomogenous EMA type operators: Operators on Inhomogeneous Time Series They update the EMA ($\text{value}$) with each new observation according to, \begin{equation} \text{value} \: += \alpha \:(\text{newData} - \text{value}), \quad \alpha = 1 - \exp{(-\frac{\Delta t}{\tau})} \end{equation} with $\tau$ a smoothing/tuning parameter. It is a simple way to estimate an expectation. Also one can create a simple online median estimate via the update \begin{align} \text{sg} &= sgn(\text{newData} - \text{med})\\ \text{med} +&= \epsilon \: (\text{sg} - \text{med}) \end{align} In practice you want $\epsilon$ small (or decaying with more observations). Ideally $\epsilon$ should depend on how lopsided the updates are becoming; i.e. if $\text{med}$ actually equals the median then $\text{sg}$ should be uniform on $\{-1,1\}$. You can then extend this to a depth $d$ balanced binary tree type structure to get $2^{d+1}-1$ quantiles uniformly spaced. The combination of the above should give you a decent online distribution of your data. The tree is tricky to get right, I have implementations of both in C++ if you are interested. I use both in practice a lot (financial real-time tick data) and they have worked well.
How to handle online time series forecast?
In your real-time system are the observation times inhomogenous and the data non-stationary? If you want something simple and fast I suggest using the inhomogenous EMA type operators: Operators on Inh
How to handle online time series forecast? In your real-time system are the observation times inhomogenous and the data non-stationary? If you want something simple and fast I suggest using the inhomogenous EMA type operators: Operators on Inhomogeneous Time Series They update the EMA ($\text{value}$) with each new observation according to, \begin{equation} \text{value} \: += \alpha \:(\text{newData} - \text{value}), \quad \alpha = 1 - \exp{(-\frac{\Delta t}{\tau})} \end{equation} with $\tau$ a smoothing/tuning parameter. It is a simple way to estimate an expectation. Also one can create a simple online median estimate via the update \begin{align} \text{sg} &= sgn(\text{newData} - \text{med})\\ \text{med} +&= \epsilon \: (\text{sg} - \text{med}) \end{align} In practice you want $\epsilon$ small (or decaying with more observations). Ideally $\epsilon$ should depend on how lopsided the updates are becoming; i.e. if $\text{med}$ actually equals the median then $\text{sg}$ should be uniform on $\{-1,1\}$. You can then extend this to a depth $d$ balanced binary tree type structure to get $2^{d+1}-1$ quantiles uniformly spaced. The combination of the above should give you a decent online distribution of your data. The tree is tricky to get right, I have implementations of both in C++ if you are interested. I use both in practice a lot (financial real-time tick data) and they have worked well.
How to handle online time series forecast? In your real-time system are the observation times inhomogenous and the data non-stationary? If you want something simple and fast I suggest using the inhomogenous EMA type operators: Operators on Inh
28,616
How to handle online time series forecast?
The Kalman filter is a recursive algorithm. It takes the new observation and combines it with the previous prediction. It would be good to use but only if it is an appropriate model for your data. I am not sure how easy it is to update the prediction interval.
How to handle online time series forecast?
The Kalman filter is a recursive algorithm. It takes the new observation and combines it with the previous prediction. It would be good to use but only if it is an appropriate model for your data. I
How to handle online time series forecast? The Kalman filter is a recursive algorithm. It takes the new observation and combines it with the previous prediction. It would be good to use but only if it is an appropriate model for your data. I am not sure how easy it is to update the prediction interval.
How to handle online time series forecast? The Kalman filter is a recursive algorithm. It takes the new observation and combines it with the previous prediction. It would be good to use but only if it is an appropriate model for your data. I
28,617
How to handle online time series forecast?
I don't know if you tried this, but in R when you use the Arima function you can specify the model as an input. So, if initially you found an arima model let's say Arima(1,2,1) with respective smoothing components you can then fix the model in later iterations so it does not try to refit a model. If your data is stationary in that case, the predictions may be sufficiently good for you - and much faster. Hope this helps..
How to handle online time series forecast?
I don't know if you tried this, but in R when you use the Arima function you can specify the model as an input. So, if initially you found an arima model let's say Arima(1,2,1) with respective smoothi
How to handle online time series forecast? I don't know if you tried this, but in R when you use the Arima function you can specify the model as an input. So, if initially you found an arima model let's say Arima(1,2,1) with respective smoothing components you can then fix the model in later iterations so it does not try to refit a model. If your data is stationary in that case, the predictions may be sufficiently good for you - and much faster. Hope this helps..
How to handle online time series forecast? I don't know if you tried this, but in R when you use the Arima function you can specify the model as an input. So, if initially you found an arima model let's say Arima(1,2,1) with respective smoothi
28,618
MCMC to handle flat likelihood issues
I find it surprising that a flat likelihood produces convergence issues: it is usually the opposite case that causes problems! The usual first check for such situations is to make sure that your posterior is proper: if not it would explain for endless excursions in the "tails". If the posterior is indeed proper, you could use fatter tail proposals like a Cauchy distribution... And an adaptive algorithm à la Roberts and Rosenthal. If this still "does not work", I suggest considering a reparameterisation of the model, using for instance (i.e. if there is no other natural parametrisation) a logistic transform, $$ \varphi(x) = \exp(x)/\{1+\exp(x)\} $$ (with a possible scale parameter), which brings the parameter into the unit square. Regarding the earlier answers, Gibbs sampling sounds like a more likely solution than accept-reject, which requires finding a bound and scaling the t distribution towards the posterior, which did not seem feasible for the more robust Metropolis-Hastings sampler...
MCMC to handle flat likelihood issues
I find it surprising that a flat likelihood produces convergence issues: it is usually the opposite case that causes problems! The usual first check for such situations is to make sure that your poste
MCMC to handle flat likelihood issues I find it surprising that a flat likelihood produces convergence issues: it is usually the opposite case that causes problems! The usual first check for such situations is to make sure that your posterior is proper: if not it would explain for endless excursions in the "tails". If the posterior is indeed proper, you could use fatter tail proposals like a Cauchy distribution... And an adaptive algorithm à la Roberts and Rosenthal. If this still "does not work", I suggest considering a reparameterisation of the model, using for instance (i.e. if there is no other natural parametrisation) a logistic transform, $$ \varphi(x) = \exp(x)/\{1+\exp(x)\} $$ (with a possible scale parameter), which brings the parameter into the unit square. Regarding the earlier answers, Gibbs sampling sounds like a more likely solution than accept-reject, which requires finding a bound and scaling the t distribution towards the posterior, which did not seem feasible for the more robust Metropolis-Hastings sampler...
MCMC to handle flat likelihood issues I find it surprising that a flat likelihood produces convergence issues: it is usually the opposite case that causes problems! The usual first check for such situations is to make sure that your poste
28,619
MCMC to handle flat likelihood issues
Can you write down the distribution of your first parameter conditional on your second parameter and vice-versa? If so, Gibbs sampling would be a viable option. It's only a couple of lines of code and it can mix almost instantly in many cases.
MCMC to handle flat likelihood issues
Can you write down the distribution of your first parameter conditional on your second parameter and vice-versa? If so, Gibbs sampling would be a viable option. It's only a couple of lines of code a
MCMC to handle flat likelihood issues Can you write down the distribution of your first parameter conditional on your second parameter and vice-versa? If so, Gibbs sampling would be a viable option. It's only a couple of lines of code and it can mix almost instantly in many cases.
MCMC to handle flat likelihood issues Can you write down the distribution of your first parameter conditional on your second parameter and vice-versa? If so, Gibbs sampling would be a viable option. It's only a couple of lines of code a
28,620
MCMC to handle flat likelihood issues
EDIT: See the answer of @Xi'an and the discussion after it to see the issues with the following approach. If Metropolis-Hastings fails and your model is relatively simple, you could think of using the accept-reject algorithm with Student's $t$ distribution with a low degree of freedom (1-6) for the proposals. If you use R, you can easily simulate a Student's $t$ with rt(). If you do not have an easy way to generate $t$ variables with your software but you can simulate a $\Gamma$, then drawing the variance of a Gaussian from a $\Gamma$ at each step and simulating a Gaussian with that variance is equivalent.
MCMC to handle flat likelihood issues
EDIT: See the answer of @Xi'an and the discussion after it to see the issues with the following approach. If Metropolis-Hastings fails and your model is relatively simple, you could think of using the
MCMC to handle flat likelihood issues EDIT: See the answer of @Xi'an and the discussion after it to see the issues with the following approach. If Metropolis-Hastings fails and your model is relatively simple, you could think of using the accept-reject algorithm with Student's $t$ distribution with a low degree of freedom (1-6) for the proposals. If you use R, you can easily simulate a Student's $t$ with rt(). If you do not have an easy way to generate $t$ variables with your software but you can simulate a $\Gamma$, then drawing the variance of a Gaussian from a $\Gamma$ at each step and simulating a Gaussian with that variance is equivalent.
MCMC to handle flat likelihood issues EDIT: See the answer of @Xi'an and the discussion after it to see the issues with the following approach. If Metropolis-Hastings fails and your model is relatively simple, you could think of using the
28,621
Expected log value of noncentral exponential distribution
The desired integral can be wrestled into submission by brute-force manipulations; here, we instead try to give an alternative derivation with a slightly more probabilistic flavor. Let $X \sim \mathrm{Exp}(k,\lambda)$ be a noncentral exponential random variable with location parameter $k > 0$ and rate parameter $\lambda$. Then $X = Z + k$ where $Z \sim \mathrm{Exp}(\lambda)$. Note that $\log(X/k) \geq 0$ and so, using a standard fact for computing the expectation of nonnegative random variables, $$ \newcommand{\e}{\mathbb E}\newcommand{\rd}{\mathrm d}\renewcommand{\Pr}{\mathbb P} \e \log(X/k) = \int_0^\infty \Pr(\log(X/k) > z)\,\rd z = \int_0^\infty \Pr(Z > k(e^z - 1)) \,\rd z \>. $$ But, $\Pr(Z > k(e^z -1)) = \exp(-\lambda k(e^z - 1))$ on $z \geq 0$ since $Z \sim \mathrm{Exp}(\lambda)$ and so $$ \e \log(X/k) = e^{\lambda k} \int_0^\infty \exp(-\lambda k e^z) \, \rd z = e^{\lambda k} \int_{\lambda k}^\infty t^{-1} e^{-t} \,\rd t \>, $$ where the last equality follows from the substitution $t = \lambda k e^z$, noting that $\rd z = \rd t / t$. The integral on the right-hand size of the last display is just $\Gamma(0,\lambda k)$ by definition and so $$ \e \log X = e^{\lambda k} \Gamma(0,\lambda k) + \log k \>, $$ as confirmed by @Procrastinator's Mathematica computation in the comments to the question. NB: The equivalent notation $\mathrm E_1(x)$ is also often used in place of $\Gamma(0,x)$.
Expected log value of noncentral exponential distribution
The desired integral can be wrestled into submission by brute-force manipulations; here, we instead try to give an alternative derivation with a slightly more probabilistic flavor. Let $X \sim \mathrm
Expected log value of noncentral exponential distribution The desired integral can be wrestled into submission by brute-force manipulations; here, we instead try to give an alternative derivation with a slightly more probabilistic flavor. Let $X \sim \mathrm{Exp}(k,\lambda)$ be a noncentral exponential random variable with location parameter $k > 0$ and rate parameter $\lambda$. Then $X = Z + k$ where $Z \sim \mathrm{Exp}(\lambda)$. Note that $\log(X/k) \geq 0$ and so, using a standard fact for computing the expectation of nonnegative random variables, $$ \newcommand{\e}{\mathbb E}\newcommand{\rd}{\mathrm d}\renewcommand{\Pr}{\mathbb P} \e \log(X/k) = \int_0^\infty \Pr(\log(X/k) > z)\,\rd z = \int_0^\infty \Pr(Z > k(e^z - 1)) \,\rd z \>. $$ But, $\Pr(Z > k(e^z -1)) = \exp(-\lambda k(e^z - 1))$ on $z \geq 0$ since $Z \sim \mathrm{Exp}(\lambda)$ and so $$ \e \log(X/k) = e^{\lambda k} \int_0^\infty \exp(-\lambda k e^z) \, \rd z = e^{\lambda k} \int_{\lambda k}^\infty t^{-1} e^{-t} \,\rd t \>, $$ where the last equality follows from the substitution $t = \lambda k e^z$, noting that $\rd z = \rd t / t$. The integral on the right-hand size of the last display is just $\Gamma(0,\lambda k)$ by definition and so $$ \e \log X = e^{\lambda k} \Gamma(0,\lambda k) + \log k \>, $$ as confirmed by @Procrastinator's Mathematica computation in the comments to the question. NB: The equivalent notation $\mathrm E_1(x)$ is also often used in place of $\Gamma(0,x)$.
Expected log value of noncentral exponential distribution The desired integral can be wrestled into submission by brute-force manipulations; here, we instead try to give an alternative derivation with a slightly more probabilistic flavor. Let $X \sim \mathrm
28,622
SVD of a data matrix (PCA) after smoothing
Why your first thoughts led you astray: When you take the SVD of a matrix, $U$ and $V$ are unitary (orthogonal). So, while it is true that $SA = SU \Sigma V^{T}$, that is not (generally) the SVD of $SA$. Only if $S$ is unitary (which in the case of a smoothing matrix, it's not) would it be true that $U' = SU$. Is there any elegant, symbolic way of relating the two SVDs? I can't find one. However, your smoothing matrix is a Toeplitz matrix. It's possible that such matrices have some special properties that might make for a more fruitful analysis. If you figure something out, please share with the rest of us. The case of extreme smoothing: One way to think about smoothing is a continuum from no smoothing to the extreme where we smooth each column to its mean value. Now, in that extreme case, the matrix would have a rank of 1, and there would only be one non-zero singular value. Let's look at the SVD: $ \left[ \begin{matrix} \uparrow & \uparrow & & \uparrow \\ \mu_1 & \mu_2 & ... & \mu_m \\ \downarrow & \downarrow & & \downarrow \end{matrix} \right] = \left[ \begin{matrix} \boldsymbol{\mu} \\ \boldsymbol{\mu} \\ ... \\ \end{matrix} \right] = \mathbf{1} \boldsymbol{\mu}^T = \dfrac{\mathbf{1}}{\sqrt{n}} \left[ \|\boldsymbol{\mu}\| \sqrt{n} \right] \dfrac{\boldsymbol{\mu}^T}{\|\boldsymbol{\mu}\|} $ The last equation represents the truncated SVD. Note that the left and right vectors are of length 1. You can expand $\frac{\mathbf{1}}{\sqrt{n}}$ into an orthogonal matrix. Similarly for $\frac{\boldsymbol{\mu}}{\|\boldsymbol{\mu}\|}$. Then just zero-pad the middle matrix, and you've got the full SVD. Intermediate smoothing Presumably you're not going to do such extreme smoothing. So, what does this mean for you? As we broaden the smoothing, the spectrum gradually squishes down to a single value. For instance, in my simulations*: As suggested by the derivation above, $U'_1$ will approach the normed 1-vector, and $V'_1$ will approach the normed mean-vector. But what about the other vectors? As their corresponding singular values shrink, the other $U'_i$'s and $V'_i$'s will vary ever more wildly until they're just arbitrary choices for bases of the subspaces orthogonal to $U'_1$ and $V'_1$. That is to say, the'll just become noise. If you need some intuition for why they're "just noise", consider that $SA$ is a weighted sum of dyads: $\displaystyle \sum \sigma_i U'_i V'^T_i $. We could completely change the directions of $U'_i$ and $V'_i$, and it will only affect the entries of $SA$ by less than $\sigma_i$. Another visualization Here's another way to look at column smoothing. Picture each row in the matrix as a point in $m$-space. As we smooth the columns, each point will get closer to the previous and next point. As a whole, the point cloud shrinks down†: Hope this helps! [ * ]: I defined a family of increasingly broad smoothers. Roughly speaking, I took the kernel [1/4, 1/2, 1/4], convolved it $z$ times, clipped it to $d$ dimensions, and normalized so it summed to 1. Then I graphed the progressive smoothing of a random orthogonal and a random normal matrix. [ † ]: Smoothers generated in the same way. $A$ is constructed as a series of points in $2$-space that look interesting.
SVD of a data matrix (PCA) after smoothing
Why your first thoughts led you astray: When you take the SVD of a matrix, $U$ and $V$ are unitary (orthogonal). So, while it is true that $SA = SU \Sigma V^{T}$, that is not (generally) the SVD of $S
SVD of a data matrix (PCA) after smoothing Why your first thoughts led you astray: When you take the SVD of a matrix, $U$ and $V$ are unitary (orthogonal). So, while it is true that $SA = SU \Sigma V^{T}$, that is not (generally) the SVD of $SA$. Only if $S$ is unitary (which in the case of a smoothing matrix, it's not) would it be true that $U' = SU$. Is there any elegant, symbolic way of relating the two SVDs? I can't find one. However, your smoothing matrix is a Toeplitz matrix. It's possible that such matrices have some special properties that might make for a more fruitful analysis. If you figure something out, please share with the rest of us. The case of extreme smoothing: One way to think about smoothing is a continuum from no smoothing to the extreme where we smooth each column to its mean value. Now, in that extreme case, the matrix would have a rank of 1, and there would only be one non-zero singular value. Let's look at the SVD: $ \left[ \begin{matrix} \uparrow & \uparrow & & \uparrow \\ \mu_1 & \mu_2 & ... & \mu_m \\ \downarrow & \downarrow & & \downarrow \end{matrix} \right] = \left[ \begin{matrix} \boldsymbol{\mu} \\ \boldsymbol{\mu} \\ ... \\ \end{matrix} \right] = \mathbf{1} \boldsymbol{\mu}^T = \dfrac{\mathbf{1}}{\sqrt{n}} \left[ \|\boldsymbol{\mu}\| \sqrt{n} \right] \dfrac{\boldsymbol{\mu}^T}{\|\boldsymbol{\mu}\|} $ The last equation represents the truncated SVD. Note that the left and right vectors are of length 1. You can expand $\frac{\mathbf{1}}{\sqrt{n}}$ into an orthogonal matrix. Similarly for $\frac{\boldsymbol{\mu}}{\|\boldsymbol{\mu}\|}$. Then just zero-pad the middle matrix, and you've got the full SVD. Intermediate smoothing Presumably you're not going to do such extreme smoothing. So, what does this mean for you? As we broaden the smoothing, the spectrum gradually squishes down to a single value. For instance, in my simulations*: As suggested by the derivation above, $U'_1$ will approach the normed 1-vector, and $V'_1$ will approach the normed mean-vector. But what about the other vectors? As their corresponding singular values shrink, the other $U'_i$'s and $V'_i$'s will vary ever more wildly until they're just arbitrary choices for bases of the subspaces orthogonal to $U'_1$ and $V'_1$. That is to say, the'll just become noise. If you need some intuition for why they're "just noise", consider that $SA$ is a weighted sum of dyads: $\displaystyle \sum \sigma_i U'_i V'^T_i $. We could completely change the directions of $U'_i$ and $V'_i$, and it will only affect the entries of $SA$ by less than $\sigma_i$. Another visualization Here's another way to look at column smoothing. Picture each row in the matrix as a point in $m$-space. As we smooth the columns, each point will get closer to the previous and next point. As a whole, the point cloud shrinks down†: Hope this helps! [ * ]: I defined a family of increasingly broad smoothers. Roughly speaking, I took the kernel [1/4, 1/2, 1/4], convolved it $z$ times, clipped it to $d$ dimensions, and normalized so it summed to 1. Then I graphed the progressive smoothing of a random orthogonal and a random normal matrix. [ † ]: Smoothers generated in the same way. $A$ is constructed as a series of points in $2$-space that look interesting.
SVD of a data matrix (PCA) after smoothing Why your first thoughts led you astray: When you take the SVD of a matrix, $U$ and $V$ are unitary (orthogonal). So, while it is true that $SA = SU \Sigma V^{T}$, that is not (generally) the SVD of $S
28,623
Support vector regression on skewed/high kurtosis data
You can use skewed or heavy-tailed Lambert W distributions to transform your data to something more well-behaved (disclaimer: I am the author of both papers and the LambertW R package). The advantage over the Box-Cox transformation is that they do not have any positivity restriction, the optimal parameters of the transformation can be estimated (MLE) from the data, and you can also forget the transformation and model your data as a Lambert W x F distribution directly. The LambertW R package provides several estimators, transformations, methods, etc. I especially recommend a look at Gaussianize() IGMM() MLE_LambertW() The skewed Lambert W x F distribution is a general framework to make a skewed version of any distribution F. Conversely you can then make your skewed data again symmetric; the distribution of this symmetrized data basically determines what kind of Lambert W x F you have; if the data is just a bit asymmetric, then you might have a skewed Lambert W x Gaussian; if your data is additionally heavy-tailed maybe you can try a skewed Lambert W x t. Heavy-tailed Lambert W x F are a generalization of Tukey's h distribution, and they provide an inverse-transform to make data Gaussian (also from asymmetric). In the paper I demonstrate that even a Cauchy can be Gaussianized to a level that you - and also several Normality tests - can't distinguish it from a Normal sample.
Support vector regression on skewed/high kurtosis data
You can use skewed or heavy-tailed Lambert W distributions to transform your data to something more well-behaved (disclaimer: I am the author of both papers and the LambertW R package). The advantage
Support vector regression on skewed/high kurtosis data You can use skewed or heavy-tailed Lambert W distributions to transform your data to something more well-behaved (disclaimer: I am the author of both papers and the LambertW R package). The advantage over the Box-Cox transformation is that they do not have any positivity restriction, the optimal parameters of the transformation can be estimated (MLE) from the data, and you can also forget the transformation and model your data as a Lambert W x F distribution directly. The LambertW R package provides several estimators, transformations, methods, etc. I especially recommend a look at Gaussianize() IGMM() MLE_LambertW() The skewed Lambert W x F distribution is a general framework to make a skewed version of any distribution F. Conversely you can then make your skewed data again symmetric; the distribution of this symmetrized data basically determines what kind of Lambert W x F you have; if the data is just a bit asymmetric, then you might have a skewed Lambert W x Gaussian; if your data is additionally heavy-tailed maybe you can try a skewed Lambert W x t. Heavy-tailed Lambert W x F are a generalization of Tukey's h distribution, and they provide an inverse-transform to make data Gaussian (also from asymmetric). In the paper I demonstrate that even a Cauchy can be Gaussianized to a level that you - and also several Normality tests - can't distinguish it from a Normal sample.
Support vector regression on skewed/high kurtosis data You can use skewed or heavy-tailed Lambert W distributions to transform your data to something more well-behaved (disclaimer: I am the author of both papers and the LambertW R package). The advantage
28,624
Support vector regression on skewed/high kurtosis data
One way to deal with negative values is to shift variables to the positive range (say to greater or equal to 0.1), apply Box-Cox transform (or just log() for a quick test), and then standardize. The standardization can be important for SVR since SVR relies on quadratic penalty applied to all coefficients uniformly (so SVR is not scale invariant and can benefit from variable standardization). Make sure to check the resulting variable distributions - they should not be skewed much (ideally they should look Gaussian) Another technique one could try is to apply "spatial sign" transformation to the input vectors x <- x / norm(x) as per “Spatial sign preprocessing: a simple way to impart moderate robustness to multivariate estimators”. J. Chem. Inf. Model (2006) vol. 46 (3) pp. 1402–1409 I did not have much luck with this technique though but the mileage may vary.
Support vector regression on skewed/high kurtosis data
One way to deal with negative values is to shift variables to the positive range (say to greater or equal to 0.1), apply Box-Cox transform (or just log() for a quick test), and then standardize. The s
Support vector regression on skewed/high kurtosis data One way to deal with negative values is to shift variables to the positive range (say to greater or equal to 0.1), apply Box-Cox transform (or just log() for a quick test), and then standardize. The standardization can be important for SVR since SVR relies on quadratic penalty applied to all coefficients uniformly (so SVR is not scale invariant and can benefit from variable standardization). Make sure to check the resulting variable distributions - they should not be skewed much (ideally they should look Gaussian) Another technique one could try is to apply "spatial sign" transformation to the input vectors x <- x / norm(x) as per “Spatial sign preprocessing: a simple way to impart moderate robustness to multivariate estimators”. J. Chem. Inf. Model (2006) vol. 46 (3) pp. 1402–1409 I did not have much luck with this technique though but the mileage may vary.
Support vector regression on skewed/high kurtosis data One way to deal with negative values is to shift variables to the positive range (say to greater or equal to 0.1), apply Box-Cox transform (or just log() for a quick test), and then standardize. The s
28,625
Support vector regression on skewed/high kurtosis data
One way to approach the solution would be building two models: one for the values which are in line with the distribution and other for the outliers. My suggestion in this regard would be to create a binary response variable (0,1) with 0 being the value if the datapoint is within the bounds of your distribution and 1 if it lies outside. So for the cases of the outliers which you want to keep in your data, you will be having 1 in your target variable and the rest as 0. Now run a logistic regression to predict the probabilities of the outliers and you can multiply the average value for the group of outliers with the individual probabilities to get the predictions. For the rest of the data, you can run your SVM to predict the values. Because the values are outliers, they will have low probabilities associated with it and even if you take mean of the outliers which will be skewed, the expected value of the outliers will be pulled down by their attached low probabilities and there by making it a more reasonable prediction. Had met with a similar scenario while predicting claims amount for an Insurance service provider. I had used the above-mentioned technique to increase the performance of my model drastically. Another way could be taking log transformation of your target variable which is possible if you have only positive value in your target variable. But make sure if you are taking a log transformation of your target variable, while predicting the variable you need to include the error component as well. So, $\log(Y) = a + B'X + \epsilon$ is your model equation for e.g then, $Y = \exp(a+B'X+\epsilon)$ You can take a look into the following link for log-transformation: http://www.vims.edu/people/newman_mc/pubs/Newman1993.pdf
Support vector regression on skewed/high kurtosis data
One way to approach the solution would be building two models: one for the values which are in line with the distribution and other for the outliers. My suggestion in this regard would be to create a
Support vector regression on skewed/high kurtosis data One way to approach the solution would be building two models: one for the values which are in line with the distribution and other for the outliers. My suggestion in this regard would be to create a binary response variable (0,1) with 0 being the value if the datapoint is within the bounds of your distribution and 1 if it lies outside. So for the cases of the outliers which you want to keep in your data, you will be having 1 in your target variable and the rest as 0. Now run a logistic regression to predict the probabilities of the outliers and you can multiply the average value for the group of outliers with the individual probabilities to get the predictions. For the rest of the data, you can run your SVM to predict the values. Because the values are outliers, they will have low probabilities associated with it and even if you take mean of the outliers which will be skewed, the expected value of the outliers will be pulled down by their attached low probabilities and there by making it a more reasonable prediction. Had met with a similar scenario while predicting claims amount for an Insurance service provider. I had used the above-mentioned technique to increase the performance of my model drastically. Another way could be taking log transformation of your target variable which is possible if you have only positive value in your target variable. But make sure if you are taking a log transformation of your target variable, while predicting the variable you need to include the error component as well. So, $\log(Y) = a + B'X + \epsilon$ is your model equation for e.g then, $Y = \exp(a+B'X+\epsilon)$ You can take a look into the following link for log-transformation: http://www.vims.edu/people/newman_mc/pubs/Newman1993.pdf
Support vector regression on skewed/high kurtosis data One way to approach the solution would be building two models: one for the values which are in line with the distribution and other for the outliers. My suggestion in this regard would be to create a
28,626
Estimate the population variance from a set of means
Let $X_i$ be the mean of $N_i$ independent draws from some unknown distribution $F$ having mean $\mu$ and standard deviation $\sigma$. Altogether these values represent $N=N_1+N_2+\cdots+N_k$ draws. It follows from these assumptions that each $X_i$ has expectation $\mu$ and variance $\sigma^2/N_i$. Part of the question proposes estimating $\mu$ from these data as $$\hat{\mu} = \frac{1}{N}\sum_{i=1}^k N_i X_i.$$ We can verify that this is a good estimate. First, it is unbiased: $$E[\hat{\mu}] = E\left[\frac{1}{N}\sum_{i=1}^k N_i X_i\right] = \frac{1}{N}\sum_{i=1}^k N_i \mu = \mu.$$ Second, its estimation variance is low. To compute this we find the second moment: $$\begin{align} E\left[\hat{\mu}^2\right] &= E\left[\frac{1}{N^2}\sum_{i,j}N_i N_j X_i X_j\right]\\ &= \mu^2 + \sigma^2/N. \end{align}$$ Subtracting the square of the first moment shows that the sampling variance of $\hat{\mu}$ equals $\sigma^2/N$. This is as low as an unbiased linear estimator can possibly get, because it equals the sampling variance of the mean of the $N$ (unknown) values from which the $X_i$ were formed; that sampling variance is known to be minimum among all unbiased linear estimators; and any linear combination of the $X_i$ is a fortiori a linear combination of the $N$ underlying values. To address the other parts of the question, let us seek an unbiased estimator of the variance $\sigma^2$ in the form of a weighted sample variance. Write the weights as $\omega_i$. Computing in a similar vein we obtain $$\begin{align} E\left[\widehat{\sigma^2}\right] &= E\left[\sum_i \omega_i(X_i-\hat{\mu})^2\right] \\ &= \sum_i \omega_i E\left[X_i^2 - \frac{2}{N}\sum_j N_j X_i X_j + (\hat{\mu})^2\right]\\ &= \sum_i \omega_i \left((\mu^2 + \sigma^2 / N_i)\left(1 - 2\frac{N_i}{N}\right) - \frac{2}{N}\sum_{j\ne i} N_j \mu^2 + (\mu^2 + \sigma^2/N)\right)\\ &= \sigma^2 \sum_i \omega_i\left(\frac{1}{N_i} - \frac{1}{N}\right). \end{align}$$ A natural choice (inspired by ANOVA calculations) is $$\omega_i = \frac{N_i}{k-1}.\tag{*}$$ For indeed, $$E\left[\widehat{\sigma^2}\right] = \sigma^2 \sum_i^k \frac{N_i}{k-1}\left(\frac{1}{N_i} - \frac{1}{N}\right) = \sigma^2 \frac{1}{k-1}\sum_i^k \left(1 - \frac{N_i}{N}\right) = \sigma^2\frac{k-\frac{N}{N}}{k-1} = \sigma^2.$$ This at least makes $\widehat{\sigma^2}$ unbiased. With more than $k=2$ groups, there are many other choices of weights that give unbiased estimators. When the group sizes are equal, it's easy to show that this choice gives a minimum-variance unbiased estimator. In general, though, it appears that the MVUE depends on the first four moments of $F$. (I may have done the algebra wrong, but I'm getting some complicated results for the general case.) Regardless, it appears that the weights provided here will not be far from optimal. As a concrete example, suppose that each of $X_1$, $X_2$, and $X_3$ is the average of $N_i=4$ draws. Then $N=12$, $k=3$, and the weights as given in formula $(*)$ are all given by $\omega_i = \frac{4}{3-1}=2$. Consequently we should estimate $$\widehat{\sigma^2} = 2((X_1-\hat{\mu})^2 + (X_2-\hat{\mu})^2 + (X_3-\hat{\mu})^2)$$ and, of course, $$\hat{\mu} = \frac{1}{12}(4X_1 + 4X_2 + 4X_3) = (X_1+X_2+X_3)/3.$$
Estimate the population variance from a set of means
Let $X_i$ be the mean of $N_i$ independent draws from some unknown distribution $F$ having mean $\mu$ and standard deviation $\sigma$. Altogether these values represent $N=N_1+N_2+\cdots+N_k$ draws.
Estimate the population variance from a set of means Let $X_i$ be the mean of $N_i$ independent draws from some unknown distribution $F$ having mean $\mu$ and standard deviation $\sigma$. Altogether these values represent $N=N_1+N_2+\cdots+N_k$ draws. It follows from these assumptions that each $X_i$ has expectation $\mu$ and variance $\sigma^2/N_i$. Part of the question proposes estimating $\mu$ from these data as $$\hat{\mu} = \frac{1}{N}\sum_{i=1}^k N_i X_i.$$ We can verify that this is a good estimate. First, it is unbiased: $$E[\hat{\mu}] = E\left[\frac{1}{N}\sum_{i=1}^k N_i X_i\right] = \frac{1}{N}\sum_{i=1}^k N_i \mu = \mu.$$ Second, its estimation variance is low. To compute this we find the second moment: $$\begin{align} E\left[\hat{\mu}^2\right] &= E\left[\frac{1}{N^2}\sum_{i,j}N_i N_j X_i X_j\right]\\ &= \mu^2 + \sigma^2/N. \end{align}$$ Subtracting the square of the first moment shows that the sampling variance of $\hat{\mu}$ equals $\sigma^2/N$. This is as low as an unbiased linear estimator can possibly get, because it equals the sampling variance of the mean of the $N$ (unknown) values from which the $X_i$ were formed; that sampling variance is known to be minimum among all unbiased linear estimators; and any linear combination of the $X_i$ is a fortiori a linear combination of the $N$ underlying values. To address the other parts of the question, let us seek an unbiased estimator of the variance $\sigma^2$ in the form of a weighted sample variance. Write the weights as $\omega_i$. Computing in a similar vein we obtain $$\begin{align} E\left[\widehat{\sigma^2}\right] &= E\left[\sum_i \omega_i(X_i-\hat{\mu})^2\right] \\ &= \sum_i \omega_i E\left[X_i^2 - \frac{2}{N}\sum_j N_j X_i X_j + (\hat{\mu})^2\right]\\ &= \sum_i \omega_i \left((\mu^2 + \sigma^2 / N_i)\left(1 - 2\frac{N_i}{N}\right) - \frac{2}{N}\sum_{j\ne i} N_j \mu^2 + (\mu^2 + \sigma^2/N)\right)\\ &= \sigma^2 \sum_i \omega_i\left(\frac{1}{N_i} - \frac{1}{N}\right). \end{align}$$ A natural choice (inspired by ANOVA calculations) is $$\omega_i = \frac{N_i}{k-1}.\tag{*}$$ For indeed, $$E\left[\widehat{\sigma^2}\right] = \sigma^2 \sum_i^k \frac{N_i}{k-1}\left(\frac{1}{N_i} - \frac{1}{N}\right) = \sigma^2 \frac{1}{k-1}\sum_i^k \left(1 - \frac{N_i}{N}\right) = \sigma^2\frac{k-\frac{N}{N}}{k-1} = \sigma^2.$$ This at least makes $\widehat{\sigma^2}$ unbiased. With more than $k=2$ groups, there are many other choices of weights that give unbiased estimators. When the group sizes are equal, it's easy to show that this choice gives a minimum-variance unbiased estimator. In general, though, it appears that the MVUE depends on the first four moments of $F$. (I may have done the algebra wrong, but I'm getting some complicated results for the general case.) Regardless, it appears that the weights provided here will not be far from optimal. As a concrete example, suppose that each of $X_1$, $X_2$, and $X_3$ is the average of $N_i=4$ draws. Then $N=12$, $k=3$, and the weights as given in formula $(*)$ are all given by $\omega_i = \frac{4}{3-1}=2$. Consequently we should estimate $$\widehat{\sigma^2} = 2((X_1-\hat{\mu})^2 + (X_2-\hat{\mu})^2 + (X_3-\hat{\mu})^2)$$ and, of course, $$\hat{\mu} = \frac{1}{12}(4X_1 + 4X_2 + 4X_3) = (X_1+X_2+X_3)/3.$$
Estimate the population variance from a set of means Let $X_i$ be the mean of $N_i$ independent draws from some unknown distribution $F$ having mean $\mu$ and standard deviation $\sigma$. Altogether these values represent $N=N_1+N_2+\cdots+N_k$ draws.
28,627
Difference between marginal and conditional models
Yes, the interpretations are quite similar to "regular models", and the major distinction between them is whether you are comparing observations within the same cluster, or across all the clusters. In a typical conditional model - also known as a conditionally-specified model, or a mixed model - the coefficients have cluster-specific interpretations. The coefficients of a covariate is a measure of difference in mean response, in the same cluster, at observations for which the specific covariates differ by one unit and all the other covariates are identical. Depending on the link function, the "measure of difference" can be a difference, or a log-ratio, or a log odds-ratio. An exception is the intercept, which doesn't describe a difference, but instead gives the mean response in observations for which all covariates and the random effect(s) are zero. In a marginal model, the coefficients have population-averaged interpretations. Excepting the intercept, the coefficients describe differences in mean response, but now across all observations (and hence across all clusters). The coefficient of a covariate is the difference in mean response (or log-ratio of means, etc) per unit difference in that covariate, in observations for which all other covariates are identical. Note that this definition is agnostic about whether the comparisons are in the same cluster or not.
Difference between marginal and conditional models
Yes, the interpretations are quite similar to "regular models", and the major distinction between them is whether you are comparing observations within the same cluster, or across all the clusters. In
Difference between marginal and conditional models Yes, the interpretations are quite similar to "regular models", and the major distinction between them is whether you are comparing observations within the same cluster, or across all the clusters. In a typical conditional model - also known as a conditionally-specified model, or a mixed model - the coefficients have cluster-specific interpretations. The coefficients of a covariate is a measure of difference in mean response, in the same cluster, at observations for which the specific covariates differ by one unit and all the other covariates are identical. Depending on the link function, the "measure of difference" can be a difference, or a log-ratio, or a log odds-ratio. An exception is the intercept, which doesn't describe a difference, but instead gives the mean response in observations for which all covariates and the random effect(s) are zero. In a marginal model, the coefficients have population-averaged interpretations. Excepting the intercept, the coefficients describe differences in mean response, but now across all observations (and hence across all clusters). The coefficient of a covariate is the difference in mean response (or log-ratio of means, etc) per unit difference in that covariate, in observations for which all other covariates are identical. Note that this definition is agnostic about whether the comparisons are in the same cluster or not.
Difference between marginal and conditional models Yes, the interpretations are quite similar to "regular models", and the major distinction between them is whether you are comparing observations within the same cluster, or across all the clusters. In
28,628
Online material to learn time series analysis
As per my comment I am not certain what you are looking for, but when I am fitting time series after a bit of a hiatus from them I tend to grab my copy of Time Series Analysis and Its Applications for more theory questions and I look at a few different sites online (also do some googling to see if there are any sweet new ones): http://cran.r-project.org/web/views/TimeSeries.html The CRAN taskview on time series gives you a good look at just how many things you can do http://www.stat.pitt.edu/stoffer/tsa2/R_time_series_quick_fix.htm Is a nice walk through of some time series analysis in R. I personally do much of my statistical learning through example (which generally means following guides like this in R), so this guide is a favorite of mine. http://www.duke.edu/~rnau/411arim.htm This link is a decent look at ARIMA outside of R, it walks you through what different models mean. Finally, you can always check out wikipedia if you are just looking for statements for formulas. These are just the ones I have book marked, so maybe some other folks will contribute their favorites. As I said in comments, if you expand on what you are looking for more specifically you can probably get better links from me or one of the folks that follow time series closer than I do.
Online material to learn time series analysis
As per my comment I am not certain what you are looking for, but when I am fitting time series after a bit of a hiatus from them I tend to grab my copy of Time Series Analysis and Its Applications for
Online material to learn time series analysis As per my comment I am not certain what you are looking for, but when I am fitting time series after a bit of a hiatus from them I tend to grab my copy of Time Series Analysis and Its Applications for more theory questions and I look at a few different sites online (also do some googling to see if there are any sweet new ones): http://cran.r-project.org/web/views/TimeSeries.html The CRAN taskview on time series gives you a good look at just how many things you can do http://www.stat.pitt.edu/stoffer/tsa2/R_time_series_quick_fix.htm Is a nice walk through of some time series analysis in R. I personally do much of my statistical learning through example (which generally means following guides like this in R), so this guide is a favorite of mine. http://www.duke.edu/~rnau/411arim.htm This link is a decent look at ARIMA outside of R, it walks you through what different models mean. Finally, you can always check out wikipedia if you are just looking for statements for formulas. These are just the ones I have book marked, so maybe some other folks will contribute their favorites. As I said in comments, if you expand on what you are looking for more specifically you can probably get better links from me or one of the folks that follow time series closer than I do.
Online material to learn time series analysis As per my comment I am not certain what you are looking for, but when I am fitting time series after a bit of a hiatus from them I tend to grab my copy of Time Series Analysis and Its Applications for
28,629
Online material to learn time series analysis
Personally, I think this webpage is a fantastic resource for time series analysis, particularly since it provides R code.
Online material to learn time series analysis
Personally, I think this webpage is a fantastic resource for time series analysis, particularly since it provides R code.
Online material to learn time series analysis Personally, I think this webpage is a fantastic resource for time series analysis, particularly since it provides R code.
Online material to learn time series analysis Personally, I think this webpage is a fantastic resource for time series analysis, particularly since it provides R code.
28,630
Online material to learn time series analysis
There are some good, free, online resources: The Little Book of R for Time Series, by Avril Coghlan (also available in print, reasonably cheap) - I haven't read through this all, but it looks like it's well written, has some good examples, and starts basically from scratch (ie. easy to get into). Chapter 15, Statistics with R, by Vincent Zoonekynd - Decent intro, but probably slightly more advanced. I find that there's too much (poorly commented) code, and not enough explanation thereof.
Online material to learn time series analysis
There are some good, free, online resources: The Little Book of R for Time Series, by Avril Coghlan (also available in print, reasonably cheap) - I haven't read through this all, but it looks like it
Online material to learn time series analysis There are some good, free, online resources: The Little Book of R for Time Series, by Avril Coghlan (also available in print, reasonably cheap) - I haven't read through this all, but it looks like it's well written, has some good examples, and starts basically from scratch (ie. easy to get into). Chapter 15, Statistics with R, by Vincent Zoonekynd - Decent intro, but probably slightly more advanced. I find that there's too much (poorly commented) code, and not enough explanation thereof.
Online material to learn time series analysis There are some good, free, online resources: The Little Book of R for Time Series, by Avril Coghlan (also available in print, reasonably cheap) - I haven't read through this all, but it looks like it
28,631
How to simulate multivariate outcomes in R?
Simulate multivariate normal values with mvtnorm::rmvnorm. It doesn't seem to work quite like the univariate random number generators, which allow you to specify vectors of parameters, but this limitation is straightforward to work around. For example, consider the model $$E(y_1,y_2,y_3) = (-1+x, 2x, 1-3x)$$ where $\mathbf{y}$ has a multivariate normal distribution and $\text{Var}(y_i)=1$, $\text{Cov}(y_1, y_2) = \text{Cov}(y_2, y_3) = 0.5$, and $\text{Cov}(y_1,y_3)=0$. Let's specify this covariance matrix in R: sigma <- matrix(c(1, 0.5, 0, 0.5, 1, 0.5, 0, 0.5, 1 ), 3, 3) To experiment, let's generate some data for this model by letting $x$ vary from $1$ through $10$, with three replications each time. We have to include constant terms, too: data <- cbind(rep(1,10*3), rep(1:10,3)) The model determines the means: beta <- matrix(c(-1,1, 0,2, 1,-3), 2, 3) means <- data %*% beta The workaround for generating multiple multivariate results is to use apply: library(mvtnorm) # Contains rmvnorm sample <- t(apply(means, 1, function(m) rmvnorm(1, mean=m, sigma=sigma)))
How to simulate multivariate outcomes in R?
Simulate multivariate normal values with mvtnorm::rmvnorm. It doesn't seem to work quite like the univariate random number generators, which allow you to specify vectors of parameters, but this limit
How to simulate multivariate outcomes in R? Simulate multivariate normal values with mvtnorm::rmvnorm. It doesn't seem to work quite like the univariate random number generators, which allow you to specify vectors of parameters, but this limitation is straightforward to work around. For example, consider the model $$E(y_1,y_2,y_3) = (-1+x, 2x, 1-3x)$$ where $\mathbf{y}$ has a multivariate normal distribution and $\text{Var}(y_i)=1$, $\text{Cov}(y_1, y_2) = \text{Cov}(y_2, y_3) = 0.5$, and $\text{Cov}(y_1,y_3)=0$. Let's specify this covariance matrix in R: sigma <- matrix(c(1, 0.5, 0, 0.5, 1, 0.5, 0, 0.5, 1 ), 3, 3) To experiment, let's generate some data for this model by letting $x$ vary from $1$ through $10$, with three replications each time. We have to include constant terms, too: data <- cbind(rep(1,10*3), rep(1:10,3)) The model determines the means: beta <- matrix(c(-1,1, 0,2, 1,-3), 2, 3) means <- data %*% beta The workaround for generating multiple multivariate results is to use apply: library(mvtnorm) # Contains rmvnorm sample <- t(apply(means, 1, function(m) rmvnorm(1, mean=m, sigma=sigma)))
How to simulate multivariate outcomes in R? Simulate multivariate normal values with mvtnorm::rmvnorm. It doesn't seem to work quite like the univariate random number generators, which allow you to specify vectors of parameters, but this limit
28,632
How to simulate multivariate outcomes in R?
Bayesian networks (BNs) are commonly used in the context you describe. As a generative model, a BN would allow you to represent the statistical dependencies between your domain variables, which in your case can be subgrouped as 1) pre-treatment, 2) treatment, and 3) post-treatment variables. You can train your model on your existing patient data, and then enter evidence (fill in observed values) for a specific patient to investigate how the observed values affect other variables (including those you labelled as outcome, i.e. post-treatment.) One neat trick is that you can actually asses the effect of different treatment types on your outcome variables. This is called an intervention. If interested, we have a relevant paper here.
How to simulate multivariate outcomes in R?
Bayesian networks (BNs) are commonly used in the context you describe. As a generative model, a BN would allow you to represent the statistical dependencies between your domain variables, which in you
How to simulate multivariate outcomes in R? Bayesian networks (BNs) are commonly used in the context you describe. As a generative model, a BN would allow you to represent the statistical dependencies between your domain variables, which in your case can be subgrouped as 1) pre-treatment, 2) treatment, and 3) post-treatment variables. You can train your model on your existing patient data, and then enter evidence (fill in observed values) for a specific patient to investigate how the observed values affect other variables (including those you labelled as outcome, i.e. post-treatment.) One neat trick is that you can actually asses the effect of different treatment types on your outcome variables. This is called an intervention. If interested, we have a relevant paper here.
How to simulate multivariate outcomes in R? Bayesian networks (BNs) are commonly used in the context you describe. As a generative model, a BN would allow you to represent the statistical dependencies between your domain variables, which in you
28,633
Confidence interval for the difference of two means using boot package in R
If you look at your totalBoot$t you will see that all the returned values are identical. The secret is that you have not defined your statistic function (meanDiff) to actual resample the data. The help page for boot says When sim = "parametric", the first argument to statistic must be the data. ... In all other cases statistic must take at least two arguments. The first argument passed will always be the original data. The second will be a vector of indices, frequencies or weights which define the bootstrap sample. If you redefine your meanDiff as meanDiff = function(dataFrame, indexVector) { m1 = mean(subset(dataFrame[indexVector, 1], dataFrame[indexVector, 2] == "initial")) m2 = mean(subset(dataFrame[indexVector, 1], dataFrame[indexVector, 2] == "final")) m = m1 - m2 return(m) } It should work. Or (not that it matters) I prefer: meanDiff =function(x, w){ y <- tapply(x[w,1], x[w,2], mean) y[1]-y[2]}
Confidence interval for the difference of two means using boot package in R
If you look at your totalBoot$t you will see that all the returned values are identical. The secret is that you have not defined your statistic function (meanDiff) to actual resample the data. The h
Confidence interval for the difference of two means using boot package in R If you look at your totalBoot$t you will see that all the returned values are identical. The secret is that you have not defined your statistic function (meanDiff) to actual resample the data. The help page for boot says When sim = "parametric", the first argument to statistic must be the data. ... In all other cases statistic must take at least two arguments. The first argument passed will always be the original data. The second will be a vector of indices, frequencies or weights which define the bootstrap sample. If you redefine your meanDiff as meanDiff = function(dataFrame, indexVector) { m1 = mean(subset(dataFrame[indexVector, 1], dataFrame[indexVector, 2] == "initial")) m2 = mean(subset(dataFrame[indexVector, 1], dataFrame[indexVector, 2] == "final")) m = m1 - m2 return(m) } It should work. Or (not that it matters) I prefer: meanDiff =function(x, w){ y <- tapply(x[w,1], x[w,2], mean) y[1]-y[2]}
Confidence interval for the difference of two means using boot package in R If you look at your totalBoot$t you will see that all the returned values are identical. The secret is that you have not defined your statistic function (meanDiff) to actual resample the data. The h
28,634
Confidence interval for chi-square
The very limited information you have is certainly a severe constraint! However, things aren't entirely hopeless. Under the same assumptions that lead to the asymptotic $\chi^2$ distribution for the test statistic of the goodness-of-fit test of the same name, the test statistic under the alternative hypothesis has, asymptotically, a noncentral $\chi^2$ distribution. If we assume the two stimuli are a) significant, and b) have the same effect, the associated test statistics will have the same asymptotic noncentral $\chi^2$ distribution. We can use this to construct a test - basically, by estimating the noncentrality parameter $\lambda$ and seeing whether the test statistics are far in the tails of the noncentral $\chi^2(18, \hat{\lambda}) $ distribution. (That's not to say this test will have much power, though.) We can estimate the noncentrality parameter given the two test statistics by taking their average and subtracting the degrees of freedom (a methods of moments estimator), giving an estimate of 44, or by maximum likelihood: x <- c(45, 79) n <- 18 ll <- function(ncp, n, x) sum(dchisq(x, n, ncp, log=TRUE)) foo <- optimize(ll, c(30,60), n=n, x=x, maximum=TRUE) > foo$maximum [1] 43.67619 Good agreement between our two estimates, not actually surprising given two data points and the 18 degrees of freedom. Now to calculate a p-value: > pchisq(x, n, foo$maximum) [1] 0.1190264 0.8798421 So our p-value is 0.12, not sufficient to reject the null hypothesis that the two stimuli are the same. Does this test actually have (roughly) a 5% reject rate when the noncentrality parameters are the same? Does it have any power? We'll attempt to answer these questions by constructing a power curve as follows. First, we fix the average $\lambda$ at the estimated value of 43.68. The alternative distributions for the two test statistics will be noncentral $\chi^2$ with 18 degrees of freedom and noncentrality parameters $(\lambda-\delta, \lambda+\delta)$ for $\delta = 1, 2, \dots, 15$. We'll simulate 10000 draws from these two distributions for each $\delta$ and see how often our test rejects at, say, the 90% and 95% level of confidence. nreject05 <- nreject10 <- rep(0,16) delta <- 0:15 lambda <- foo$maximum for (d in delta) { for (i in 1:10000) { x <- rchisq(2, n, ncp=c(lambda+d,lambda-d)) lhat <- optimize(ll, c(5,95), n=n, x=x, maximum=TRUE)$maximum pval <- pchisq(min(x), n, lhat) nreject05[d+1] <- nreject05[d+1] + (pval < 0.05) nreject10[d+1] <- nreject10[d+1] + (pval < 0.10) } } preject05 <- nreject05 / 10000 preject10 <- nreject10 / 10000 plot(preject05~delta, type='l', lty=1, lwd=2, ylim = c(0, 0.4), xlab = "1/2 difference between NCPs", ylab = "Simulated rejection rates", main = "") lines(preject10~delta, type='l', lty=2, lwd=2) legend("topleft",legend=c(expression(paste(alpha, " = 0.05")), expression(paste(alpha, " = 0.10"))), lty=c(1,2), lwd=2) which gives the following: Looking at the true null hypothesis points (x-axis value = 0), we see that the test is conservative, in that it doesn't appear to reject as often as the level would indicate, but not overwhelmingly so. As we expected, it doesn't have much power, but it's better than nothing. I wonder if there are better tests out there, given the very limited amount of information you have available.
Confidence interval for chi-square
The very limited information you have is certainly a severe constraint! However, things aren't entirely hopeless. Under the same assumptions that lead to the asymptotic $\chi^2$ distribution for the
Confidence interval for chi-square The very limited information you have is certainly a severe constraint! However, things aren't entirely hopeless. Under the same assumptions that lead to the asymptotic $\chi^2$ distribution for the test statistic of the goodness-of-fit test of the same name, the test statistic under the alternative hypothesis has, asymptotically, a noncentral $\chi^2$ distribution. If we assume the two stimuli are a) significant, and b) have the same effect, the associated test statistics will have the same asymptotic noncentral $\chi^2$ distribution. We can use this to construct a test - basically, by estimating the noncentrality parameter $\lambda$ and seeing whether the test statistics are far in the tails of the noncentral $\chi^2(18, \hat{\lambda}) $ distribution. (That's not to say this test will have much power, though.) We can estimate the noncentrality parameter given the two test statistics by taking their average and subtracting the degrees of freedom (a methods of moments estimator), giving an estimate of 44, or by maximum likelihood: x <- c(45, 79) n <- 18 ll <- function(ncp, n, x) sum(dchisq(x, n, ncp, log=TRUE)) foo <- optimize(ll, c(30,60), n=n, x=x, maximum=TRUE) > foo$maximum [1] 43.67619 Good agreement between our two estimates, not actually surprising given two data points and the 18 degrees of freedom. Now to calculate a p-value: > pchisq(x, n, foo$maximum) [1] 0.1190264 0.8798421 So our p-value is 0.12, not sufficient to reject the null hypothesis that the two stimuli are the same. Does this test actually have (roughly) a 5% reject rate when the noncentrality parameters are the same? Does it have any power? We'll attempt to answer these questions by constructing a power curve as follows. First, we fix the average $\lambda$ at the estimated value of 43.68. The alternative distributions for the two test statistics will be noncentral $\chi^2$ with 18 degrees of freedom and noncentrality parameters $(\lambda-\delta, \lambda+\delta)$ for $\delta = 1, 2, \dots, 15$. We'll simulate 10000 draws from these two distributions for each $\delta$ and see how often our test rejects at, say, the 90% and 95% level of confidence. nreject05 <- nreject10 <- rep(0,16) delta <- 0:15 lambda <- foo$maximum for (d in delta) { for (i in 1:10000) { x <- rchisq(2, n, ncp=c(lambda+d,lambda-d)) lhat <- optimize(ll, c(5,95), n=n, x=x, maximum=TRUE)$maximum pval <- pchisq(min(x), n, lhat) nreject05[d+1] <- nreject05[d+1] + (pval < 0.05) nreject10[d+1] <- nreject10[d+1] + (pval < 0.10) } } preject05 <- nreject05 / 10000 preject10 <- nreject10 / 10000 plot(preject05~delta, type='l', lty=1, lwd=2, ylim = c(0, 0.4), xlab = "1/2 difference between NCPs", ylab = "Simulated rejection rates", main = "") lines(preject10~delta, type='l', lty=2, lwd=2) legend("topleft",legend=c(expression(paste(alpha, " = 0.05")), expression(paste(alpha, " = 0.10"))), lty=c(1,2), lwd=2) which gives the following: Looking at the true null hypothesis points (x-axis value = 0), we see that the test is conservative, in that it doesn't appear to reject as often as the level would indicate, but not overwhelmingly so. As we expected, it doesn't have much power, but it's better than nothing. I wonder if there are better tests out there, given the very limited amount of information you have available.
Confidence interval for chi-square The very limited information you have is certainly a severe constraint! However, things aren't entirely hopeless. Under the same assumptions that lead to the asymptotic $\chi^2$ distribution for the
28,635
Confidence interval for chi-square
You could get the Cramer's V, which is interpretable as a correlation, convert it to a Fisher's Z, and then the confidence interval of that is straightforward (SE = 1/sqrt(n-3): Z ± se * 1.96). After you get the ends of the CI you can convert them back to r. Have you considered putting all of your counts into a contingency table with a further dimension of experiment?
Confidence interval for chi-square
You could get the Cramer's V, which is interpretable as a correlation, convert it to a Fisher's Z, and then the confidence interval of that is straightforward (SE = 1/sqrt(n-3): Z ± se * 1.96). After
Confidence interval for chi-square You could get the Cramer's V, which is interpretable as a correlation, convert it to a Fisher's Z, and then the confidence interval of that is straightforward (SE = 1/sqrt(n-3): Z ± se * 1.96). After you get the ends of the CI you can convert them back to r. Have you considered putting all of your counts into a contingency table with a further dimension of experiment?
Confidence interval for chi-square You could get the Cramer's V, which is interpretable as a correlation, convert it to a Fisher's Z, and then the confidence interval of that is straightforward (SE = 1/sqrt(n-3): Z ± se * 1.96). After
28,636
Repeated measures structural equation modeling
I think you want a latent growth curve model. While I have only used LISREL for this, the lavaan package documentation indicates it can be used to fit this type of model. I don't know of any books that specialise in this subject, the book I am working from for SEM covers a range of methods. Perhaps someone else can answer that aspect of your question.
Repeated measures structural equation modeling
I think you want a latent growth curve model. While I have only used LISREL for this, the lavaan package documentation indicates it can be used to fit this type of model. I don't know of any books tha
Repeated measures structural equation modeling I think you want a latent growth curve model. While I have only used LISREL for this, the lavaan package documentation indicates it can be used to fit this type of model. I don't know of any books that specialise in this subject, the book I am working from for SEM covers a range of methods. Perhaps someone else can answer that aspect of your question.
Repeated measures structural equation modeling I think you want a latent growth curve model. While I have only used LISREL for this, the lavaan package documentation indicates it can be used to fit this type of model. I don't know of any books tha
28,637
Repeated measures structural equation modeling
No, there is no "Pinheiro and Bates". You can find a number of books titled like "SEM using AMOS/LISREL/Mplus", but I am not aware of any using R. The best book, mathematically speaking, on SEM is still Bollen (1989). It is written by a sociologist rather than a biostatistician (although a very good one!), and so is aimed at social scientists, and contains few references to software (and you don't want the software from quarter a century ago, anyway). Bollen has also co-authored a good paper recently on causality with Judea Pearl, see http://ftp.cs.ucla.edu/pub/stat_ser/r393.pdf. As far as I can tell, Mulaik (2009) should be good, too, but it is written by a psychologist for psychologists. I don't think sem package is flexible enough to run this kind of stuff. OpenMx can deal with ordinal data (and hence binary outcomes), but I don't think lavaan can do this. The software that you will conceptually find the easiest to deal with might be GLLAMM, a package written for Stata. Viewed one way, this is essentially a Stata incarnation of nlme. With an extra tweak (allowing the coefficients of the random effects vary according to values of other variables), it becomes a latent variable modeling package. This all is described in Skrondal and Rabe-Hesketh (2004)... which is a great book per se that you'd want to have even if you just do nlme.
Repeated measures structural equation modeling
No, there is no "Pinheiro and Bates". You can find a number of books titled like "SEM using AMOS/LISREL/Mplus", but I am not aware of any using R. The best book, mathematically speaking, on SEM is sti
Repeated measures structural equation modeling No, there is no "Pinheiro and Bates". You can find a number of books titled like "SEM using AMOS/LISREL/Mplus", but I am not aware of any using R. The best book, mathematically speaking, on SEM is still Bollen (1989). It is written by a sociologist rather than a biostatistician (although a very good one!), and so is aimed at social scientists, and contains few references to software (and you don't want the software from quarter a century ago, anyway). Bollen has also co-authored a good paper recently on causality with Judea Pearl, see http://ftp.cs.ucla.edu/pub/stat_ser/r393.pdf. As far as I can tell, Mulaik (2009) should be good, too, but it is written by a psychologist for psychologists. I don't think sem package is flexible enough to run this kind of stuff. OpenMx can deal with ordinal data (and hence binary outcomes), but I don't think lavaan can do this. The software that you will conceptually find the easiest to deal with might be GLLAMM, a package written for Stata. Viewed one way, this is essentially a Stata incarnation of nlme. With an extra tweak (allowing the coefficients of the random effects vary according to values of other variables), it becomes a latent variable modeling package. This all is described in Skrondal and Rabe-Hesketh (2004)... which is a great book per se that you'd want to have even if you just do nlme.
Repeated measures structural equation modeling No, there is no "Pinheiro and Bates". You can find a number of books titled like "SEM using AMOS/LISREL/Mplus", but I am not aware of any using R. The best book, mathematically speaking, on SEM is sti
28,638
Repeated measures structural equation modeling
As you seem comfortable with generalized linear mixed models, and you don't seem to imply that you're interested in latent variables, perhaps you might want to take a piecewise approach using lmer which you can then evaluate using a D-Sep test. See Shipley, B. (2009). Confirmatory path analysis in a generalized multilevel context. Ecology, Ecology, 90, 363–368. http://dx.doi.org/10.1890/08-1034.1 for an example. He also provides R code in the appendix for how to calculate the test of D-Separation. If you really want to get into latent variable modeling and SEM using maximum likelihood, check out http://lavaan.org - there's a great tutorial there that covers its capabilities as well as a section on latent growth curve models which may well be what you're after.
Repeated measures structural equation modeling
As you seem comfortable with generalized linear mixed models, and you don't seem to imply that you're interested in latent variables, perhaps you might want to take a piecewise approach using lmer whi
Repeated measures structural equation modeling As you seem comfortable with generalized linear mixed models, and you don't seem to imply that you're interested in latent variables, perhaps you might want to take a piecewise approach using lmer which you can then evaluate using a D-Sep test. See Shipley, B. (2009). Confirmatory path analysis in a generalized multilevel context. Ecology, Ecology, 90, 363–368. http://dx.doi.org/10.1890/08-1034.1 for an example. He also provides R code in the appendix for how to calculate the test of D-Separation. If you really want to get into latent variable modeling and SEM using maximum likelihood, check out http://lavaan.org - there's a great tutorial there that covers its capabilities as well as a section on latent growth curve models which may well be what you're after.
Repeated measures structural equation modeling As you seem comfortable with generalized linear mixed models, and you don't seem to imply that you're interested in latent variables, perhaps you might want to take a piecewise approach using lmer whi
28,639
Missing values in response variable in JAGS
Yes, it is really easy to use in BUGS or JAGS! It is actually a pleasure to use it! But do the observations with the missing outcomes also affect parameter estimates? Of course not. The parameters are only affected by the observed outcomes. The missing outcomes (NAs) will not affect anything, actually it is the other way: the missing outcomes will be derived from the parameters. Note that the missing outcomes will have its posterior distribution also. Then it is very easy to compute some derived quantities e.g. like a sum over indices of the outcome, and these derived quantities not only are handled for missing values, but also immediatelly have their posterior distribution. That's what is so sexy on BUGS & JAGS! Have fun!
Missing values in response variable in JAGS
Yes, it is really easy to use in BUGS or JAGS! It is actually a pleasure to use it! But do the observations with the missing outcomes also affect parameter estimates? Of course not. The parameters are
Missing values in response variable in JAGS Yes, it is really easy to use in BUGS or JAGS! It is actually a pleasure to use it! But do the observations with the missing outcomes also affect parameter estimates? Of course not. The parameters are only affected by the observed outcomes. The missing outcomes (NAs) will not affect anything, actually it is the other way: the missing outcomes will be derived from the parameters. Note that the missing outcomes will have its posterior distribution also. Then it is very easy to compute some derived quantities e.g. like a sum over indices of the outcome, and these derived quantities not only are handled for missing values, but also immediatelly have their posterior distribution. That's what is so sexy on BUGS & JAGS! Have fun!
Missing values in response variable in JAGS Yes, it is really easy to use in BUGS or JAGS! It is actually a pleasure to use it! But do the observations with the missing outcomes also affect parameter estimates? Of course not. The parameters are
28,640
Kolmogorov-Smirnov two-sample $p$-values
Under the null hypothesis, the asymptotic distribution of the two-sample Kolmogorov–Smirnov statistic is the Kolmogorov distribution, which has CDF $$\operatorname{Pr}(K\leq x)=\frac{\sqrt{2\pi}}{x}\sum_{i=1}^\infty e^{-(2i-1)^2\pi^2/(8x^2)} \>.$$ The $p$-values can be calculated from this CDF - see Section 4 and Section 2 of the Wikipedia page on the Kolmogorov–Smirnov test. You seem to be saying that a non-parametric test statistic shouldn't have a distribution - that's not the case - what makes this test non-parametric is that the distribution of the test statistic does not depend on what continuous probability distribution the original data come from. Note that the KS test has this property even for finite samples as shown by @cardinal in the comments.
Kolmogorov-Smirnov two-sample $p$-values
Under the null hypothesis, the asymptotic distribution of the two-sample Kolmogorov–Smirnov statistic is the Kolmogorov distribution, which has CDF $$\operatorname{Pr}(K\leq x)=\frac{\sqrt{2\pi}}{x}\
Kolmogorov-Smirnov two-sample $p$-values Under the null hypothesis, the asymptotic distribution of the two-sample Kolmogorov–Smirnov statistic is the Kolmogorov distribution, which has CDF $$\operatorname{Pr}(K\leq x)=\frac{\sqrt{2\pi}}{x}\sum_{i=1}^\infty e^{-(2i-1)^2\pi^2/(8x^2)} \>.$$ The $p$-values can be calculated from this CDF - see Section 4 and Section 2 of the Wikipedia page on the Kolmogorov–Smirnov test. You seem to be saying that a non-parametric test statistic shouldn't have a distribution - that's not the case - what makes this test non-parametric is that the distribution of the test statistic does not depend on what continuous probability distribution the original data come from. Note that the KS test has this property even for finite samples as shown by @cardinal in the comments.
Kolmogorov-Smirnov two-sample $p$-values Under the null hypothesis, the asymptotic distribution of the two-sample Kolmogorov–Smirnov statistic is the Kolmogorov distribution, which has CDF $$\operatorname{Pr}(K\leq x)=\frac{\sqrt{2\pi}}{x}\
28,641
Kolmogorov-Smirnov two-sample $p$-values
The p-value of,say 0.80, implies that 80% of samples of size n of samples from the population, will have a D statistic less than the one obtained from the test. This is calculated based on the D-statistic of KS test, which measures the maximum distance between the CDFs of theoretical and empirical distribution, for the given distribution against which the sample is evaluated. Note that only the value D*SQRT(sample size) has a kolmogrov distribution and not D itself. If you want to manually calculate p value given D value, you can refer the published tables available in the internet for kolomogrov distribution. This is also the value given in packages like R
Kolmogorov-Smirnov two-sample $p$-values
The p-value of,say 0.80, implies that 80% of samples of size n of samples from the population, will have a D statistic less than the one obtained from the test. This is calculated based on the D-stati
Kolmogorov-Smirnov two-sample $p$-values The p-value of,say 0.80, implies that 80% of samples of size n of samples from the population, will have a D statistic less than the one obtained from the test. This is calculated based on the D-statistic of KS test, which measures the maximum distance between the CDFs of theoretical and empirical distribution, for the given distribution against which the sample is evaluated. Note that only the value D*SQRT(sample size) has a kolmogrov distribution and not D itself. If you want to manually calculate p value given D value, you can refer the published tables available in the internet for kolomogrov distribution. This is also the value given in packages like R
Kolmogorov-Smirnov two-sample $p$-values The p-value of,say 0.80, implies that 80% of samples of size n of samples from the population, will have a D statistic less than the one obtained from the test. This is calculated based on the D-stati
28,642
Is a "split plot" ANOVA with two factors the same as two-way ANOVA with repeated measures in one factor?
The case with one between factor, and one repeated-measures factor is one particular example that leads to a split-plot design. In this case, each observational unit (e.g., a participant in an experiment) is observed multiple times. One participant is one "whole plot" (or block). There are N different participants, representing N levels of the blocking factor ID. Now, one group of whole-plots is treated according to level 1 of an experimental factor A (say, a control group), another group of blocks is treated according to level 2 of A (say, is administered a drug). Now, each whole block is split into multiple "sub-plots". Within each whole block, these sub-plots are treated according to the levels of a second experimental factor B. In your case, B is time, so each participant is observed under different levels of the influence of time, say before the treatment, shortly thereafter, and then again some time later. There are three factors: The blocking factor ID, the (between) factor A, and the (within) factor B. ID is a random factor, meaning that its levels are not controlled by the experimenter, but are the result of a random sampling process. The levels themselves are not interesting per se, and one wants to generalize the results beyond these particular levels (note that "random factor" is not super well defined, I think there's a blog entry by Gelman that I can't find at the moment). A and B however are experimental (fixed) factors in the proper sense, their levels are interesting per se, intentionally chosen, and repeatably realized by the experimenter. So this is a 3-factorial design with 1 one observation per cell ID $\times$ A $\times$ B. Importantly, there is a level of nesting, or confounding: Each level of the blocking factor is observed only in one condition of the between-factor A, so ID and A are not crossed. The confounding is that, conversely, each level of A only contains a subset of levels from the blocking factor, but not all of them. (B does, however). In agricultural terms (the origin of the design name), one whole plot is actually one area of land that is then subdivided into split-plots. In that case, the between factor A is one that is hard to manipulate - the classical example is irrigation, which cannot easily be applied in a different manner to small plots. In the same vein, giving different drugs to the same person at different times is often not feasible (if the person is cured after drug 1, then drug 2 cannot be tested anymore). The second experimental factor B, on the other hand, can easily be manipulated within one whole plot, the classical example being different fertilizers. As you can see, one whole plot need not be one person observed multiple times. It's just that each whole plot is a homogeneous entity that can be split into sub-plots that are equivalent in some respect. In the social sciences, it could also be one group of subjects that is roughly homogeneous with respect to a nuisance variable, say socio-economic-status, or severity of the illness. In this case, each person within such a homogeneous group is then a split-plot. As a further read, split-plot designs are explained here, or here.
Is a "split plot" ANOVA with two factors the same as two-way ANOVA with repeated measures in one fac
The case with one between factor, and one repeated-measures factor is one particular example that leads to a split-plot design. In this case, each observational unit (e.g., a participant in an experim
Is a "split plot" ANOVA with two factors the same as two-way ANOVA with repeated measures in one factor? The case with one between factor, and one repeated-measures factor is one particular example that leads to a split-plot design. In this case, each observational unit (e.g., a participant in an experiment) is observed multiple times. One participant is one "whole plot" (or block). There are N different participants, representing N levels of the blocking factor ID. Now, one group of whole-plots is treated according to level 1 of an experimental factor A (say, a control group), another group of blocks is treated according to level 2 of A (say, is administered a drug). Now, each whole block is split into multiple "sub-plots". Within each whole block, these sub-plots are treated according to the levels of a second experimental factor B. In your case, B is time, so each participant is observed under different levels of the influence of time, say before the treatment, shortly thereafter, and then again some time later. There are three factors: The blocking factor ID, the (between) factor A, and the (within) factor B. ID is a random factor, meaning that its levels are not controlled by the experimenter, but are the result of a random sampling process. The levels themselves are not interesting per se, and one wants to generalize the results beyond these particular levels (note that "random factor" is not super well defined, I think there's a blog entry by Gelman that I can't find at the moment). A and B however are experimental (fixed) factors in the proper sense, their levels are interesting per se, intentionally chosen, and repeatably realized by the experimenter. So this is a 3-factorial design with 1 one observation per cell ID $\times$ A $\times$ B. Importantly, there is a level of nesting, or confounding: Each level of the blocking factor is observed only in one condition of the between-factor A, so ID and A are not crossed. The confounding is that, conversely, each level of A only contains a subset of levels from the blocking factor, but not all of them. (B does, however). In agricultural terms (the origin of the design name), one whole plot is actually one area of land that is then subdivided into split-plots. In that case, the between factor A is one that is hard to manipulate - the classical example is irrigation, which cannot easily be applied in a different manner to small plots. In the same vein, giving different drugs to the same person at different times is often not feasible (if the person is cured after drug 1, then drug 2 cannot be tested anymore). The second experimental factor B, on the other hand, can easily be manipulated within one whole plot, the classical example being different fertilizers. As you can see, one whole plot need not be one person observed multiple times. It's just that each whole plot is a homogeneous entity that can be split into sub-plots that are equivalent in some respect. In the social sciences, it could also be one group of subjects that is roughly homogeneous with respect to a nuisance variable, say socio-economic-status, or severity of the illness. In this case, each person within such a homogeneous group is then a split-plot. As a further read, split-plot designs are explained here, or here.
Is a "split plot" ANOVA with two factors the same as two-way ANOVA with repeated measures in one fac The case with one between factor, and one repeated-measures factor is one particular example that leads to a split-plot design. In this case, each observational unit (e.g., a participant in an experim
28,643
Is a "split plot" ANOVA with two factors the same as two-way ANOVA with repeated measures in one factor?
ANOVA with one repeated-measures factor and one between-groups factor is identical to ANOVA with 3 factors - the formerly repeated-measures factor, the between-groups factor, and the subjects (respondents' ID) factor nested in the previous one. In SPSS, for instanse, three following commands are equivalent: (RM-ANOVA): GLM time1 time2 time3 /*3 RM-factor variables*/ BY group /*between-group factor*/ /WSFACTOR= time 3 /*name the RM-factor of 3 levels*/ /WSDESIGN= time /*within-subject design is it*/ /DESIGN= group /*between-subject design is group*/. (Split-plot ANOVA): GLM depvar /*dependent variable as concatenated of time1 time2 time3*/ BY time /*variable indicating RM-levels*/ group subject /RANDOM= subject /*respondent is a random factor*/ /DESIGN= group subject(group) /*subject nested in group*/ time time*group /*interaction*/. (Split-plot via mixed models): MIXED depvar BY time group subject /RANDOM= subject(group) /*respondent is a random factor nestes in group*/ /FIXED= group time group*time.
Is a "split plot" ANOVA with two factors the same as two-way ANOVA with repeated measures in one fac
ANOVA with one repeated-measures factor and one between-groups factor is identical to ANOVA with 3 factors - the formerly repeated-measures factor, the between-groups factor, and the subjects (respond
Is a "split plot" ANOVA with two factors the same as two-way ANOVA with repeated measures in one factor? ANOVA with one repeated-measures factor and one between-groups factor is identical to ANOVA with 3 factors - the formerly repeated-measures factor, the between-groups factor, and the subjects (respondents' ID) factor nested in the previous one. In SPSS, for instanse, three following commands are equivalent: (RM-ANOVA): GLM time1 time2 time3 /*3 RM-factor variables*/ BY group /*between-group factor*/ /WSFACTOR= time 3 /*name the RM-factor of 3 levels*/ /WSDESIGN= time /*within-subject design is it*/ /DESIGN= group /*between-subject design is group*/. (Split-plot ANOVA): GLM depvar /*dependent variable as concatenated of time1 time2 time3*/ BY time /*variable indicating RM-levels*/ group subject /RANDOM= subject /*respondent is a random factor*/ /DESIGN= group subject(group) /*subject nested in group*/ time time*group /*interaction*/. (Split-plot via mixed models): MIXED depvar BY time group subject /RANDOM= subject(group) /*respondent is a random factor nestes in group*/ /FIXED= group time group*time.
Is a "split plot" ANOVA with two factors the same as two-way ANOVA with repeated measures in one fac ANOVA with one repeated-measures factor and one between-groups factor is identical to ANOVA with 3 factors - the formerly repeated-measures factor, the between-groups factor, and the subjects (respond
28,644
Best algorithm for classifying time series motor data
My approach is to form an ARIMA Model for the data and then to employ various "change-point detection schemes" in order to provide early warning about unexpected "things". These schemes would include detecting the presence/onset of Pulses/Level Shifts/Local Time Trends i.e. changes in the mean of the errors over time detecting the presence/onset of changes in parameters over time detecting the presence/onset of changes in variance of residuals over time If you wish to actually post one of your series we could actually show you this kind of analysis which can "push out" the idea that things are changing or have changed significantly.
Best algorithm for classifying time series motor data
My approach is to form an ARIMA Model for the data and then to employ various "change-point detection schemes" in order to provide early warning about unexpected "things". These schemes would include
Best algorithm for classifying time series motor data My approach is to form an ARIMA Model for the data and then to employ various "change-point detection schemes" in order to provide early warning about unexpected "things". These schemes would include detecting the presence/onset of Pulses/Level Shifts/Local Time Trends i.e. changes in the mean of the errors over time detecting the presence/onset of changes in parameters over time detecting the presence/onset of changes in variance of residuals over time If you wish to actually post one of your series we could actually show you this kind of analysis which can "push out" the idea that things are changing or have changed significantly.
Best algorithm for classifying time series motor data My approach is to form an ARIMA Model for the data and then to employ various "change-point detection schemes" in order to provide early warning about unexpected "things". These schemes would include
28,645
Best algorithm for classifying time series motor data
I would suggest you this link that deals with time series classification: http://www.r-bloggers.com/time-series-analysis-and-mining-with-r/.
Best algorithm for classifying time series motor data
I would suggest you this link that deals with time series classification: http://www.r-bloggers.com/time-series-analysis-and-mining-with-r/.
Best algorithm for classifying time series motor data I would suggest you this link that deals with time series classification: http://www.r-bloggers.com/time-series-analysis-and-mining-with-r/.
Best algorithm for classifying time series motor data I would suggest you this link that deals with time series classification: http://www.r-bloggers.com/time-series-analysis-and-mining-with-r/.
28,646
Best algorithm for classifying time series motor data
Hidden Markov Model One of the best approaches to modeling time series data is a Hidden Markov Model (HMM). You can either make a single model of your know non-problem state, separate models of each of your known problem states or, if you have sufficient data, a single composite model of all of your known problem states. A good open source library is the Hidden Markov Model Toolbox for Matlab. http://www.cs.ubc.ca/~murphyk/Software/HMM/hmm.html Kalman Filter Another approach that is a little more involved is a Kalman Filter. This approach is especially useful if your data has a lot of noise. A good open source library is the Kalman Filter Toolbox for Matlab. http://www.cs.ubc.ca/~murphyk/Software/Kalman/kalman.html Bayesian Models Both of these approaches are considered Bayesian Models. A good open source library is the Bayes Net Toolbox for Matlab. http://code.google.com/p/bnt I hope this works for you.
Best algorithm for classifying time series motor data
Hidden Markov Model One of the best approaches to modeling time series data is a Hidden Markov Model (HMM). You can either make a single model of your know non-problem state, separate models of each o
Best algorithm for classifying time series motor data Hidden Markov Model One of the best approaches to modeling time series data is a Hidden Markov Model (HMM). You can either make a single model of your know non-problem state, separate models of each of your known problem states or, if you have sufficient data, a single composite model of all of your known problem states. A good open source library is the Hidden Markov Model Toolbox for Matlab. http://www.cs.ubc.ca/~murphyk/Software/HMM/hmm.html Kalman Filter Another approach that is a little more involved is a Kalman Filter. This approach is especially useful if your data has a lot of noise. A good open source library is the Kalman Filter Toolbox for Matlab. http://www.cs.ubc.ca/~murphyk/Software/Kalman/kalman.html Bayesian Models Both of these approaches are considered Bayesian Models. A good open source library is the Bayes Net Toolbox for Matlab. http://code.google.com/p/bnt I hope this works for you.
Best algorithm for classifying time series motor data Hidden Markov Model One of the best approaches to modeling time series data is a Hidden Markov Model (HMM). You can either make a single model of your know non-problem state, separate models of each o
28,647
How to compute the power of Wilcoxon test?
I don't know if there's an analytical solution to your question, but when all else fails, one can simulate the distribution you think the two samples come from many thousands of times using Monte Carlo methods. The percentage of those samples the Wilcoxon test correctly identifies as "different" is the power of the test. For example, if you generated 10,000 different simulated paired samples that match your actual data in terms of size and the distribution they came from, and 8,000 of them are correctly identified by the test as different, your power = 0.80.
How to compute the power of Wilcoxon test?
I don't know if there's an analytical solution to your question, but when all else fails, one can simulate the distribution you think the two samples come from many thousands of times using Monte Carl
How to compute the power of Wilcoxon test? I don't know if there's an analytical solution to your question, but when all else fails, one can simulate the distribution you think the two samples come from many thousands of times using Monte Carlo methods. The percentage of those samples the Wilcoxon test correctly identifies as "different" is the power of the test. For example, if you generated 10,000 different simulated paired samples that match your actual data in terms of size and the distribution they came from, and 8,000 of them are correctly identified by the test as different, your power = 0.80.
How to compute the power of Wilcoxon test? I don't know if there's an analytical solution to your question, but when all else fails, one can simulate the distribution you think the two samples come from many thousands of times using Monte Carl
28,648
How to compute the power of Wilcoxon test?
Suppose you have Ho: median <= 8 and Ha: median > 8 As par for the course, remove any values from your data equal to 8. Calculate the sample mean and sample standard deviation. Use the sample mean as your alternate mean for the power calculation. In my data, n=9 (df = 8) and I'm testing at alpha = 5%. The t critical value is 1.86. Also, the sample mean from my data is 12.7333333... and the sample standard deviation is 7.79527429. Calculate X1 = 1.86(7.97527429)/sqrt(9) + 8 = 12.94467006 Calculate t1 = 12.94467006 - 12.733333.... = 0.211336726 Then, power = P(t > 0.211336726) = 0.491 based on df = 8. I found this procedure here: https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Wilcoxon_Signed-Rank_Tests.pdf However, they are using a non-central t distribution which only complicates the matter.
How to compute the power of Wilcoxon test?
Suppose you have Ho: median <= 8 and Ha: median > 8 As par for the course, remove any values from your data equal to 8. Calculate the sample mean and sample standard deviation. Use the sample mean as
How to compute the power of Wilcoxon test? Suppose you have Ho: median <= 8 and Ha: median > 8 As par for the course, remove any values from your data equal to 8. Calculate the sample mean and sample standard deviation. Use the sample mean as your alternate mean for the power calculation. In my data, n=9 (df = 8) and I'm testing at alpha = 5%. The t critical value is 1.86. Also, the sample mean from my data is 12.7333333... and the sample standard deviation is 7.79527429. Calculate X1 = 1.86(7.97527429)/sqrt(9) + 8 = 12.94467006 Calculate t1 = 12.94467006 - 12.733333.... = 0.211336726 Then, power = P(t > 0.211336726) = 0.491 based on df = 8. I found this procedure here: https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Wilcoxon_Signed-Rank_Tests.pdf However, they are using a non-central t distribution which only complicates the matter.
How to compute the power of Wilcoxon test? Suppose you have Ho: median <= 8 and Ha: median > 8 As par for the course, remove any values from your data equal to 8. Calculate the sample mean and sample standard deviation. Use the sample mean as
28,649
Using Holt-Winters for forecasting in Python
I think the R forecast package you mentioned is a better fit for this problem than just using Holt-Winters. The two functions you are interested in are ets() and auto.arima(). ets() will fit an exponential smoothing model, including Holt-Winters and several other methods. It will choose parameters (alpha, beta, and gama) for a variety of models and then return the one with the lowest AIC (or BIC if you prefer). auto.arima() works similarly. However, as IrishStat pointed out, these kinds of models may not be appropriate for your analysis. In that case, try calculating some covariates, such as dummy variables for weekends, holidays, and their interactions. Once you've specified covariates that make sense, use auto.arima() to find a ARMAX model, and then forecast() to make predictions. You will probably end up with something much better than a simple Holt-Winters model in python with default parameters. You should also note that both ets() and auto.arima can fit seasonal models, but you need to format your data as a seasonal time series. Let me know if you need any help with that. You can read more about the forecast package here.
Using Holt-Winters for forecasting in Python
I think the R forecast package you mentioned is a better fit for this problem than just using Holt-Winters. The two functions you are interested in are ets() and auto.arima(). ets() will fit an expo
Using Holt-Winters for forecasting in Python I think the R forecast package you mentioned is a better fit for this problem than just using Holt-Winters. The two functions you are interested in are ets() and auto.arima(). ets() will fit an exponential smoothing model, including Holt-Winters and several other methods. It will choose parameters (alpha, beta, and gama) for a variety of models and then return the one with the lowest AIC (or BIC if you prefer). auto.arima() works similarly. However, as IrishStat pointed out, these kinds of models may not be appropriate for your analysis. In that case, try calculating some covariates, such as dummy variables for weekends, holidays, and their interactions. Once you've specified covariates that make sense, use auto.arima() to find a ARMAX model, and then forecast() to make predictions. You will probably end up with something much better than a simple Holt-Winters model in python with default parameters. You should also note that both ets() and auto.arima can fit seasonal models, but you need to format your data as a seasonal time series. Let me know if you need any help with that. You can read more about the forecast package here.
Using Holt-Winters for forecasting in Python I think the R forecast package you mentioned is a better fit for this problem than just using Holt-Winters. The two functions you are interested in are ets() and auto.arima(). ets() will fit an expo
28,650
Using Holt-Winters for forecasting in Python
The problem might be that Holt-Winters is a specific model form and may not be applicable to your data. The HW Model assumes among other things the following. a) one and only one trend b) no level shifts in the data i.e. no intercept changes 3) that seasonal parameters do not vary over time 4) no outliers 5) no autoregressive structure or adaptive model structure 6)model errors that have constant variance And of course 7) that the history causes the future i.e. no incorporation of price/promotions.events etc as helping variables From your description it appears to me that a mixed-frequency approach might be needed. I have seen time series problems where the hour-of-the-day effects and the day-of-the-week effects have significant interaction terms. You are trying to force your data into an inadequate i.e. not-generalized enough structure. Estimating parameters and choosing from a small set of models does not replace Model Identification. You might want to read a piece on the different approaches to Automatic Modeling at www.autobox.com/pdfs/catchword.pdf . In terms of a more general approach I would suggest that you consider an ARMAX model otherwise known as a Transfer Function which relaxes the afore-mentioned assumptions.
Using Holt-Winters for forecasting in Python
The problem might be that Holt-Winters is a specific model form and may not be applicable to your data. The HW Model assumes among other things the following. a) one and only one trend b) no level s
Using Holt-Winters for forecasting in Python The problem might be that Holt-Winters is a specific model form and may not be applicable to your data. The HW Model assumes among other things the following. a) one and only one trend b) no level shifts in the data i.e. no intercept changes 3) that seasonal parameters do not vary over time 4) no outliers 5) no autoregressive structure or adaptive model structure 6)model errors that have constant variance And of course 7) that the history causes the future i.e. no incorporation of price/promotions.events etc as helping variables From your description it appears to me that a mixed-frequency approach might be needed. I have seen time series problems where the hour-of-the-day effects and the day-of-the-week effects have significant interaction terms. You are trying to force your data into an inadequate i.e. not-generalized enough structure. Estimating parameters and choosing from a small set of models does not replace Model Identification. You might want to read a piece on the different approaches to Automatic Modeling at www.autobox.com/pdfs/catchword.pdf . In terms of a more general approach I would suggest that you consider an ARMAX model otherwise known as a Transfer Function which relaxes the afore-mentioned assumptions.
Using Holt-Winters for forecasting in Python The problem might be that Holt-Winters is a specific model form and may not be applicable to your data. The HW Model assumes among other things the following. a) one and only one trend b) no level s
28,651
Parallelizing the caret package using doSMP
Try computeFunction=function(onWhat,what,...){foreach(i=onWhat) %do% what(i,...)},
Parallelizing the caret package using doSMP
Try computeFunction=function(onWhat,what,...){foreach(i=onWhat) %do% what(i,...)},
Parallelizing the caret package using doSMP Try computeFunction=function(onWhat,what,...){foreach(i=onWhat) %do% what(i,...)},
Parallelizing the caret package using doSMP Try computeFunction=function(onWhat,what,...){foreach(i=onWhat) %do% what(i,...)},
28,652
Parallelizing the caret package using doSMP
Caret already does this internally for you as part of the train() function, see the bottom section of the caret webpage for starters.
Parallelizing the caret package using doSMP
Caret already does this internally for you as part of the train() function, see the bottom section of the caret webpage for starters.
Parallelizing the caret package using doSMP Caret already does this internally for you as part of the train() function, see the bottom section of the caret webpage for starters.
Parallelizing the caret package using doSMP Caret already does this internally for you as part of the train() function, see the bottom section of the caret webpage for starters.
28,653
Mahalanobis distance between two bivariate distributions with different covariances
There are many notions of distance between probability distributions. Which one to use depends on your goals. Total variation distance is a natural way of measuring overlap between distributions. If you are working with multivariate Normals, the Kullback-Leibler Divergence is mathematically convenient. Though it is not actually a distance (as it fails to be symmetric and fails to obey the triangle inequality), it upper bounds the total variation distance — see Pinsker’s Inequality.
Mahalanobis distance between two bivariate distributions with different covariances
There are many notions of distance between probability distributions. Which one to use depends on your goals. Total variation distance is a natural way of measuring overlap between distributions. If
Mahalanobis distance between two bivariate distributions with different covariances There are many notions of distance between probability distributions. Which one to use depends on your goals. Total variation distance is a natural way of measuring overlap between distributions. If you are working with multivariate Normals, the Kullback-Leibler Divergence is mathematically convenient. Though it is not actually a distance (as it fails to be symmetric and fails to obey the triangle inequality), it upper bounds the total variation distance — see Pinsker’s Inequality.
Mahalanobis distance between two bivariate distributions with different covariances There are many notions of distance between probability distributions. Which one to use depends on your goals. Total variation distance is a natural way of measuring overlap between distributions. If
28,654
Mahalanobis distance between two bivariate distributions with different covariances
Intro As @vqv mentionned Total variation and Kullback Leibler are two interesting distance. The first one is meaningfull because it can be directly related to first and second type errors in hypothesis testing. The problem with the Total variation distance is that it can be difficult to compute. The Kullback Leibler distance is easier to compute and I will come to that later. It is not symetric but can be made symetric (somehow a little bit artificially). Answer Something I mention here is that if $\mathcal{L}$ is the log likelihood ratio between your two gaussian measures $P_0,P_1$ (say that for $i=0,1$ $P_i$ has mean $\mu_i$ and covariance $C_i$) error measure that is also interseting (in the gaussian case I found it quite central actually) is $$ \|\mathcal{L}\|^2_{L_2(P_{1/2})} $$ for a well chosen $P_{1/2}$. In simple words: there might be different interesting "directions" rotations, that are obtained using your formula with one of the "interpolated" covariance matrices $\Sigma=C_{i,1/2}$ ($i=1,2,3,4$ or $5$) defined at the end of this post (the number $5$ is the one you propose in your comment to your question). since your two distributions have different covariances, it is not sufficiant to compare the means, you also need to compare the covariances. Let me explain you why this is my feeling, how you can compute this in the case of $C_1\neq C_0$ and how to choose $P_{1/2}$. Linear case If $C_1=C_0=\Sigma$. $$\sigma= \Delta \Sigma^{-1} \Delta=\|2\mathcal{L}\|^2_{L_2(P_{1/2})}$$ where $P_{1/2}$ is the "interpolate" between $P_1$ and $P_0$ (gaussian with covariance $\Sigma$ and mean $(\mu_1+\mu_0)/2$). Note that in this case, the Hellinger distance, the total variation distance can all be written using $\sigma$. How to compute $\mathcal{L}$ in the general case A natural question that arises from your question (and mine) is what is a natural "interpolate" between $P_1$ and $P_0$ when $C_1\neq C_0$. Here the word natural may be user specific but for example it may be related to the best interpolation to have a tight upper bound with another distance (e.g. $L_1$ distance here) Writting $$ \mathcal{L}= \phi (C^{-1/2}_i(x-\mu_i))-\phi (C^{-1/2}_j(x-\mu_j))-\frac{1}{2}\log \left ( C_iC_j^{-}\right ) $$ ($i=0,j=1$) may help to see where is the interpolation task, but : $$\mathcal{L}(x)=-\frac{1}{2}\langle A_{ij}(x-s_{ij}),x-s_{ij}\rangle_{\mathbb{R}^p}+\langle G_{ij},x-s_{ij}\rangle_{\mathbb{R}^p}-c_{ij}, \;[1]$$ with $$A_{ij}=C_i^{-}-C_j^{-},\;\; G_{ij}=S_{ij}m_{ij},\;\; S_{ij}=\frac{C_i^{-}+C_j^{-}}{2}, $$ $$ c_{ij}=\frac{1}{8}\langle A_{ij} m_{ij},m_{ij}\rangle_{\mathbb{R}^p}+\frac{1}{2}\log|\det(C_j^{-}C_i)| $$ and $$ m_{ij}=\mu_i-\mu_j \;\; and\;\; s_{ij}=\frac{\mu_i+\mu_j}{2}$$ is more relevant for computational purpose. For any gaussian $P_{1/2}$ with mean $s_{01}$ and covariance $C$ the calculation of $\|\mathcal{L}\|^2_{L_2(P_{1/2})}$ from Equation $1$ is a bit technical but faisible. You might also use it to compute the Kulback leibler distance. What interpolation should we choose (i.e. how to choose $P_{1/2}$) It is clearly understood from Equation $1$ that there are many different candidates for $P_{1/2}$ (interpolate) in the "quadratic" case. The two candidates I found "most natural" (subjective:) ) arise from defining for $t\in [0,1]$ a gaussian distribution $P_t$ with mean $t\mu_1+(1-t)\mu_0$: $P^1_t$ as the distribution of $$ \xi_t=t\xi_1+(1-t)\xi_0$$ (where $\xi_i$ is drawn from $P_i$ $i=0,1$) which has covariance $C_{t,1}=(tC_1^{1/2}+(1-t)C_0^{1/2})^2$). $P^2_t$ with inverse covariance $C_{t,2}^{-1}=tC_{1}^{-1}+(1-t)C_0^{-1}$ $P^3_t$ with covariance $C_{t,3}=tC_1+(1-t)C_0$ $P^4_t$ with inverse covariance $C_{t,4}^{-1}=(tC^{-1/2}_1+(1-t)C^{-1/2}_0)^{2}$ EDIT: The one you propose in a comment to your question could be $C_{t,5}=C_1^{t}C_0^{1-t}$, why not ... I have my favorite choice which is not the first one :) don't have much time to discuss that here. Maybe I'll edit this answer later...
Mahalanobis distance between two bivariate distributions with different covariances
Intro As @vqv mentionned Total variation and Kullback Leibler are two interesting distance. The first one is meaningfull because it can be directly related to first and second type errors in hypothesi
Mahalanobis distance between two bivariate distributions with different covariances Intro As @vqv mentionned Total variation and Kullback Leibler are two interesting distance. The first one is meaningfull because it can be directly related to first and second type errors in hypothesis testing. The problem with the Total variation distance is that it can be difficult to compute. The Kullback Leibler distance is easier to compute and I will come to that later. It is not symetric but can be made symetric (somehow a little bit artificially). Answer Something I mention here is that if $\mathcal{L}$ is the log likelihood ratio between your two gaussian measures $P_0,P_1$ (say that for $i=0,1$ $P_i$ has mean $\mu_i$ and covariance $C_i$) error measure that is also interseting (in the gaussian case I found it quite central actually) is $$ \|\mathcal{L}\|^2_{L_2(P_{1/2})} $$ for a well chosen $P_{1/2}$. In simple words: there might be different interesting "directions" rotations, that are obtained using your formula with one of the "interpolated" covariance matrices $\Sigma=C_{i,1/2}$ ($i=1,2,3,4$ or $5$) defined at the end of this post (the number $5$ is the one you propose in your comment to your question). since your two distributions have different covariances, it is not sufficiant to compare the means, you also need to compare the covariances. Let me explain you why this is my feeling, how you can compute this in the case of $C_1\neq C_0$ and how to choose $P_{1/2}$. Linear case If $C_1=C_0=\Sigma$. $$\sigma= \Delta \Sigma^{-1} \Delta=\|2\mathcal{L}\|^2_{L_2(P_{1/2})}$$ where $P_{1/2}$ is the "interpolate" between $P_1$ and $P_0$ (gaussian with covariance $\Sigma$ and mean $(\mu_1+\mu_0)/2$). Note that in this case, the Hellinger distance, the total variation distance can all be written using $\sigma$. How to compute $\mathcal{L}$ in the general case A natural question that arises from your question (and mine) is what is a natural "interpolate" between $P_1$ and $P_0$ when $C_1\neq C_0$. Here the word natural may be user specific but for example it may be related to the best interpolation to have a tight upper bound with another distance (e.g. $L_1$ distance here) Writting $$ \mathcal{L}= \phi (C^{-1/2}_i(x-\mu_i))-\phi (C^{-1/2}_j(x-\mu_j))-\frac{1}{2}\log \left ( C_iC_j^{-}\right ) $$ ($i=0,j=1$) may help to see where is the interpolation task, but : $$\mathcal{L}(x)=-\frac{1}{2}\langle A_{ij}(x-s_{ij}),x-s_{ij}\rangle_{\mathbb{R}^p}+\langle G_{ij},x-s_{ij}\rangle_{\mathbb{R}^p}-c_{ij}, \;[1]$$ with $$A_{ij}=C_i^{-}-C_j^{-},\;\; G_{ij}=S_{ij}m_{ij},\;\; S_{ij}=\frac{C_i^{-}+C_j^{-}}{2}, $$ $$ c_{ij}=\frac{1}{8}\langle A_{ij} m_{ij},m_{ij}\rangle_{\mathbb{R}^p}+\frac{1}{2}\log|\det(C_j^{-}C_i)| $$ and $$ m_{ij}=\mu_i-\mu_j \;\; and\;\; s_{ij}=\frac{\mu_i+\mu_j}{2}$$ is more relevant for computational purpose. For any gaussian $P_{1/2}$ with mean $s_{01}$ and covariance $C$ the calculation of $\|\mathcal{L}\|^2_{L_2(P_{1/2})}$ from Equation $1$ is a bit technical but faisible. You might also use it to compute the Kulback leibler distance. What interpolation should we choose (i.e. how to choose $P_{1/2}$) It is clearly understood from Equation $1$ that there are many different candidates for $P_{1/2}$ (interpolate) in the "quadratic" case. The two candidates I found "most natural" (subjective:) ) arise from defining for $t\in [0,1]$ a gaussian distribution $P_t$ with mean $t\mu_1+(1-t)\mu_0$: $P^1_t$ as the distribution of $$ \xi_t=t\xi_1+(1-t)\xi_0$$ (where $\xi_i$ is drawn from $P_i$ $i=0,1$) which has covariance $C_{t,1}=(tC_1^{1/2}+(1-t)C_0^{1/2})^2$). $P^2_t$ with inverse covariance $C_{t,2}^{-1}=tC_{1}^{-1}+(1-t)C_0^{-1}$ $P^3_t$ with covariance $C_{t,3}=tC_1+(1-t)C_0$ $P^4_t$ with inverse covariance $C_{t,4}^{-1}=(tC^{-1/2}_1+(1-t)C^{-1/2}_0)^{2}$ EDIT: The one you propose in a comment to your question could be $C_{t,5}=C_1^{t}C_0^{1-t}$, why not ... I have my favorite choice which is not the first one :) don't have much time to discuss that here. Maybe I'll edit this answer later...
Mahalanobis distance between two bivariate distributions with different covariances Intro As @vqv mentionned Total variation and Kullback Leibler are two interesting distance. The first one is meaningfull because it can be directly related to first and second type errors in hypothesi
28,655
Mahalanobis distance between two bivariate distributions with different covariances
This is old, but for others who are reading this, the covariance matrix reflects the rotation of the gaussian distributions and the mean reflects the translation or central position of the distribution. To evaluate the mahab distance, it is simply D= ( (m2-m1) * inv( (C1 + C2)/2 ) * (m2-m1)'). Now if you suspect that the two bivariate distributions are the same, but you suspect that they have been rotated, then compute the two pairs of eigenvectors and eigenvalues for each distribution. The eigenvectors point in the direction of the spread of the bivariate data along the major and minor axes and the eigenvalues denote the length of this spread. If the eigenvalues are same, then the two distributions are the same but rotated. Take acos of the dot product between the eigenvectors to get the angle of rotation.
Mahalanobis distance between two bivariate distributions with different covariances
This is old, but for others who are reading this, the covariance matrix reflects the rotation of the gaussian distributions and the mean reflects the translation or central position of the distributio
Mahalanobis distance between two bivariate distributions with different covariances This is old, but for others who are reading this, the covariance matrix reflects the rotation of the gaussian distributions and the mean reflects the translation or central position of the distribution. To evaluate the mahab distance, it is simply D= ( (m2-m1) * inv( (C1 + C2)/2 ) * (m2-m1)'). Now if you suspect that the two bivariate distributions are the same, but you suspect that they have been rotated, then compute the two pairs of eigenvectors and eigenvalues for each distribution. The eigenvectors point in the direction of the spread of the bivariate data along the major and minor axes and the eigenvalues denote the length of this spread. If the eigenvalues are same, then the two distributions are the same but rotated. Take acos of the dot product between the eigenvectors to get the angle of rotation.
Mahalanobis distance between two bivariate distributions with different covariances This is old, but for others who are reading this, the covariance matrix reflects the rotation of the gaussian distributions and the mean reflects the translation or central position of the distributio
28,656
Continuity correction for Pearson and McNemar's chi-square test
Another reason that continuity corrections for contingency tables have gone out of fashion is that they only make a noticeable difference when the cell counts are small, and modern computing power has made it feasible to calculate 'exact' p-values for such tables. Exact tests for 2×2 tables for R are provided by the exact2x2 package written by Michael Fay. There's an accompanying vignette about the exact McNemar's test and matching confidence intervals.
Continuity correction for Pearson and McNemar's chi-square test
Another reason that continuity corrections for contingency tables have gone out of fashion is that they only make a noticeable difference when the cell counts are small, and modern computing power has
Continuity correction for Pearson and McNemar's chi-square test Another reason that continuity corrections for contingency tables have gone out of fashion is that they only make a noticeable difference when the cell counts are small, and modern computing power has made it feasible to calculate 'exact' p-values for such tables. Exact tests for 2×2 tables for R are provided by the exact2x2 package written by Michael Fay. There's an accompanying vignette about the exact McNemar's test and matching confidence intervals.
Continuity correction for Pearson and McNemar's chi-square test Another reason that continuity corrections for contingency tables have gone out of fashion is that they only make a noticeable difference when the cell counts are small, and modern computing power has
28,657
How to compute the confidence intervals on regression coefficients in PLS?
Do you know this article: PLS-regression: a basic tool of chemometrics (PDF)? Deriving SE and CI for the PLS parameters is described in §3.11. I generally rely on Bootstrap for computing CIs, as suggested in e.g., Abdi, H. Partial least squares regression and projection on latent structure regression (PLS Regression). See also the plspm package, and its accompagnying texbook: PLS Path Modeling with R. I seem to remember there are theoretical solutions discussed in Tenenhaus M. (1998) La régression PLS: Théorie et pratique (Technip), but I cannot check for now as I don't have the book. For now, there are some useful R packages, like plsRglm. P.S. I just discovered Nicole Krämer's work, in reference to the plsdof R package.
How to compute the confidence intervals on regression coefficients in PLS?
Do you know this article: PLS-regression: a basic tool of chemometrics (PDF)? Deriving SE and CI for the PLS parameters is described in §3.11. I generally rely on Bootstrap for computing CIs, as sugge
How to compute the confidence intervals on regression coefficients in PLS? Do you know this article: PLS-regression: a basic tool of chemometrics (PDF)? Deriving SE and CI for the PLS parameters is described in §3.11. I generally rely on Bootstrap for computing CIs, as suggested in e.g., Abdi, H. Partial least squares regression and projection on latent structure regression (PLS Regression). See also the plspm package, and its accompagnying texbook: PLS Path Modeling with R. I seem to remember there are theoretical solutions discussed in Tenenhaus M. (1998) La régression PLS: Théorie et pratique (Technip), but I cannot check for now as I don't have the book. For now, there are some useful R packages, like plsRglm. P.S. I just discovered Nicole Krämer's work, in reference to the plsdof R package.
How to compute the confidence intervals on regression coefficients in PLS? Do you know this article: PLS-regression: a basic tool of chemometrics (PDF)? Deriving SE and CI for the PLS parameters is described in §3.11. I generally rely on Bootstrap for computing CIs, as sugge
28,658
How to compute the confidence intervals on regression coefficients in PLS?
I discovered a paper by Reiss, et. al., Partial least squares confidence interval calculation for industrial end-of-batch quality prediction, in which appears the quote: The PLS prediction should be accompanied by an online confidence interval to indicate the accuracy of the prediction. The formulation of the confidence interval for the PLS prediction is an area of study that has not concluded a “gold standard”. This paper contains a reference to the 'excellent survey of such work', Standard error of prediction for multiway PLS, by Faber and Bro, and a paper by Faber and Kowalski, Propagation of measurement errors for the validation of predictions obtained by principal component regression and partial least squares. I will summarize these results as they become available...
How to compute the confidence intervals on regression coefficients in PLS?
I discovered a paper by Reiss, et. al., Partial least squares confidence interval calculation for industrial end-of-batch quality prediction, in which appears the quote: The PLS prediction should be
How to compute the confidence intervals on regression coefficients in PLS? I discovered a paper by Reiss, et. al., Partial least squares confidence interval calculation for industrial end-of-batch quality prediction, in which appears the quote: The PLS prediction should be accompanied by an online confidence interval to indicate the accuracy of the prediction. The formulation of the confidence interval for the PLS prediction is an area of study that has not concluded a “gold standard”. This paper contains a reference to the 'excellent survey of such work', Standard error of prediction for multiway PLS, by Faber and Bro, and a paper by Faber and Kowalski, Propagation of measurement errors for the validation of predictions obtained by principal component regression and partial least squares. I will summarize these results as they become available...
How to compute the confidence intervals on regression coefficients in PLS? I discovered a paper by Reiss, et. al., Partial least squares confidence interval calculation for industrial end-of-batch quality prediction, in which appears the quote: The PLS prediction should be
28,659
Calculate ROC curve for data
I suggest ROC Graphs: Notes and Practical Considerations for Reasearchers by Tom Fawcett, really an excellent read. As far as I understand your question, you will find everything you need in this paper. Edit: Inspired by Adam I also want to recommend my favorite R-package for this task: ROCR.
Calculate ROC curve for data
I suggest ROC Graphs: Notes and Practical Considerations for Reasearchers by Tom Fawcett, really an excellent read. As far as I understand your question, you will find everything you need in this pape
Calculate ROC curve for data I suggest ROC Graphs: Notes and Practical Considerations for Reasearchers by Tom Fawcett, really an excellent read. As far as I understand your question, you will find everything you need in this paper. Edit: Inspired by Adam I also want to recommend my favorite R-package for this task: ROCR.
Calculate ROC curve for data I suggest ROC Graphs: Notes and Practical Considerations for Reasearchers by Tom Fawcett, really an excellent read. As far as I understand your question, you will find everything you need in this pape
28,660
Calculate ROC curve for data
Why do you want to make an ROC curve? Do you want to graph the curve for your dependent variables, or are you looking to use it as a test statistic in order to gauge the accuracy of your probability predictions (in which case you're looking for the AUC [area under the curve]). If you're familiar with R, the verification package in R has two functions that you will find useful: roc.plot(), which will allow you to plot your ROC curve, and roc.area() which will allow you to calculate the AUC.
Calculate ROC curve for data
Why do you want to make an ROC curve? Do you want to graph the curve for your dependent variables, or are you looking to use it as a test statistic in order to gauge the accuracy of your probability p
Calculate ROC curve for data Why do you want to make an ROC curve? Do you want to graph the curve for your dependent variables, or are you looking to use it as a test statistic in order to gauge the accuracy of your probability predictions (in which case you're looking for the AUC [area under the curve]). If you're familiar with R, the verification package in R has two functions that you will find useful: roc.plot(), which will allow you to plot your ROC curve, and roc.area() which will allow you to calculate the AUC.
Calculate ROC curve for data Why do you want to make an ROC curve? Do you want to graph the curve for your dependent variables, or are you looking to use it as a test statistic in order to gauge the accuracy of your probability p
28,661
Tips and tricks to get started with statistical modeling?
In Statistics, like in Data Mining, you start with data and a goal. In statistics there is a lot of focus on inference, that is, answering population-level questions using a sample. In data mining the focus is usually prediction: you create a model from your sample (training data) in order to predict test data. The process in statistics is then: Explore the data using summaries and graphs - depending on how data-driven the statistician, some will be more open-minded, looking at the data from all angles, while others (especially social scientists) will look at the data through the lens of the question of interest (e.g., plot especially the variables of interest and not others) Choose an appropriate statistical model family (e.g., linear regression for a continuous Y, logistic regression for a binary Y, or Poisson for count data), and perform model selection Estimate the final model Test model assumptions to make sure they are reasonably met (different from testing for predictive accuracy in data mining) Use the model for inference -- this is the main step that differs from data mining. The word "p-value" arrives here... Take a look at any basic stats textbook and you'll find a chapter on Exploratory Data Analysis followed by some distributions (that will help choose reasonable approximating models), then inference (confidence intervals and hypothesis tests) and regression models. I described to you the classic statistical process. However, I have many issues with it. The focus on inference has completely dominated the fields, while prediction (which is extremely important and useful) has been nearly neglected. Moreover, if you look at how social scientists use statistics for inference, you'll find that they use it quite differently! You can check out more about this here
Tips and tricks to get started with statistical modeling?
In Statistics, like in Data Mining, you start with data and a goal. In statistics there is a lot of focus on inference, that is, answering population-level questions using a sample. In data mining the
Tips and tricks to get started with statistical modeling? In Statistics, like in Data Mining, you start with data and a goal. In statistics there is a lot of focus on inference, that is, answering population-level questions using a sample. In data mining the focus is usually prediction: you create a model from your sample (training data) in order to predict test data. The process in statistics is then: Explore the data using summaries and graphs - depending on how data-driven the statistician, some will be more open-minded, looking at the data from all angles, while others (especially social scientists) will look at the data through the lens of the question of interest (e.g., plot especially the variables of interest and not others) Choose an appropriate statistical model family (e.g., linear regression for a continuous Y, logistic regression for a binary Y, or Poisson for count data), and perform model selection Estimate the final model Test model assumptions to make sure they are reasonably met (different from testing for predictive accuracy in data mining) Use the model for inference -- this is the main step that differs from data mining. The word "p-value" arrives here... Take a look at any basic stats textbook and you'll find a chapter on Exploratory Data Analysis followed by some distributions (that will help choose reasonable approximating models), then inference (confidence intervals and hypothesis tests) and regression models. I described to you the classic statistical process. However, I have many issues with it. The focus on inference has completely dominated the fields, while prediction (which is extremely important and useful) has been nearly neglected. Moreover, if you look at how social scientists use statistics for inference, you'll find that they use it quite differently! You can check out more about this here
Tips and tricks to get started with statistical modeling? In Statistics, like in Data Mining, you start with data and a goal. In statistics there is a lot of focus on inference, that is, answering population-level questions using a sample. In data mining the
28,662
Tips and tricks to get started with statistical modeling?
As far as books go, "The Elements of Statistical Learning" by Hastie, Tibshirani and Friedman is very good. The full book is available on the authors' web site; you may want to take a look to see if it is at all suitable for your needs.
Tips and tricks to get started with statistical modeling?
As far as books go, "The Elements of Statistical Learning" by Hastie, Tibshirani and Friedman is very good. The full book is available on the authors' web site; you may want to take a look to see if i
Tips and tricks to get started with statistical modeling? As far as books go, "The Elements of Statistical Learning" by Hastie, Tibshirani and Friedman is very good. The full book is available on the authors' web site; you may want to take a look to see if it is at all suitable for your needs.
Tips and tricks to get started with statistical modeling? As far as books go, "The Elements of Statistical Learning" by Hastie, Tibshirani and Friedman is very good. The full book is available on the authors' web site; you may want to take a look to see if i
28,663
Tips and tricks to get started with statistical modeling?
As for (on-line) references, I would recommend looking at Andrew Moore's tutorial slides on Statistical Data Mining. There are many textbooks on data mining and machine learning; maybe a good starting point is Principles of Data Mining, by Hand et al., and Introduction to Machine Learning, by Alpaydin.
Tips and tricks to get started with statistical modeling?
As for (on-line) references, I would recommend looking at Andrew Moore's tutorial slides on Statistical Data Mining. There are many textbooks on data mining and machine learning; maybe a good starting
Tips and tricks to get started with statistical modeling? As for (on-line) references, I would recommend looking at Andrew Moore's tutorial slides on Statistical Data Mining. There are many textbooks on data mining and machine learning; maybe a good starting point is Principles of Data Mining, by Hand et al., and Introduction to Machine Learning, by Alpaydin.
Tips and tricks to get started with statistical modeling? As for (on-line) references, I would recommend looking at Andrew Moore's tutorial slides on Statistical Data Mining. There are many textbooks on data mining and machine learning; maybe a good starting
28,664
Tips and tricks to get started with statistical modeling?
The best introductory Bayesian book I have found is Data Analysis - A Bayesian Tutorial. It is quite practical.
Tips and tricks to get started with statistical modeling?
The best introductory Bayesian book I have found is Data Analysis - A Bayesian Tutorial. It is quite practical.
Tips and tricks to get started with statistical modeling? The best introductory Bayesian book I have found is Data Analysis - A Bayesian Tutorial. It is quite practical.
Tips and tricks to get started with statistical modeling? The best introductory Bayesian book I have found is Data Analysis - A Bayesian Tutorial. It is quite practical.
28,665
Has anyone used the Marascuilo procedure for comparing multiple proportions?
Just a partial answer because I've never heard of this method. From what I read in the link you provided, it seems to be a single-step procedure (much like Bonferroni, except we rework the test statistics instead of the p-value) which is likely to be too conservative. In R, there is a function pairwise.prop.test() which allows any correction for multiple comparisons (single-step or step-down FWER methods or FDR-based), but it is quit what you already suggested (although Bonferroni is by far too conservative, but still very used in practice). A resampling approach, using permutation, might be interesting too. The coin R package provides a well-established testing framework in this respect, see §5 of Implementing a Class of Permutation Tests: The coin Package, but I never had to deal with permutation tests on categorical data in a post-hoc way. About the analysis of subdivided contingency tables, I generally consider specific associations as a guide to develop additional hypotheses (as for any unplanned comparisons), but this is another question. I generally just use visualization tools, like mosaicplot from Michael Friendly, Pearson's residuals, and if I seek to explain specific patterns of association I use log-linear models.
Has anyone used the Marascuilo procedure for comparing multiple proportions?
Just a partial answer because I've never heard of this method. From what I read in the link you provided, it seems to be a single-step procedure (much like Bonferroni, except we rework the test statis
Has anyone used the Marascuilo procedure for comparing multiple proportions? Just a partial answer because I've never heard of this method. From what I read in the link you provided, it seems to be a single-step procedure (much like Bonferroni, except we rework the test statistics instead of the p-value) which is likely to be too conservative. In R, there is a function pairwise.prop.test() which allows any correction for multiple comparisons (single-step or step-down FWER methods or FDR-based), but it is quit what you already suggested (although Bonferroni is by far too conservative, but still very used in practice). A resampling approach, using permutation, might be interesting too. The coin R package provides a well-established testing framework in this respect, see §5 of Implementing a Class of Permutation Tests: The coin Package, but I never had to deal with permutation tests on categorical data in a post-hoc way. About the analysis of subdivided contingency tables, I generally consider specific associations as a guide to develop additional hypotheses (as for any unplanned comparisons), but this is another question. I generally just use visualization tools, like mosaicplot from Michael Friendly, Pearson's residuals, and if I seek to explain specific patterns of association I use log-linear models.
Has anyone used the Marascuilo procedure for comparing multiple proportions? Just a partial answer because I've never heard of this method. From what I read in the link you provided, it seems to be a single-step procedure (much like Bonferroni, except we rework the test statis
28,666
Has anyone used the Marascuilo procedure for comparing multiple proportions?
I would like to see the Marascuilo procedure used more often. Quite frequently I see people calculating the chi-square on a subset of the main table ie two categories at the time but without actually doing the partitioning correctly. The reason why they do it this way as far as iI understood is that they can't bear grouping the categories as that will make the interpretation really hard. At the end of the day it depends of the audience as well coz if they don't know it they might just recommend the usual Bonferroni approach
Has anyone used the Marascuilo procedure for comparing multiple proportions?
I would like to see the Marascuilo procedure used more often. Quite frequently I see people calculating the chi-square on a subset of the main table ie two categories at the time but without actually
Has anyone used the Marascuilo procedure for comparing multiple proportions? I would like to see the Marascuilo procedure used more often. Quite frequently I see people calculating the chi-square on a subset of the main table ie two categories at the time but without actually doing the partitioning correctly. The reason why they do it this way as far as iI understood is that they can't bear grouping the categories as that will make the interpretation really hard. At the end of the day it depends of the audience as well coz if they don't know it they might just recommend the usual Bonferroni approach
Has anyone used the Marascuilo procedure for comparing multiple proportions? I would like to see the Marascuilo procedure used more often. Quite frequently I see people calculating the chi-square on a subset of the main table ie two categories at the time but without actually
28,667
How can I predict a continuous variable using only ordinal covariates?
A problem with treating ordinal variables as numeric/continuous is that it assumes, often incorrectly, that predictor categories are equidistant with respect to their effect on the response variable. So, a change from category 1 to category 2 has the equivalent effect on the response variable as a change from category 2 to 3, etc. Treating ordinal predictors as categorical/unordered can also be problematic for several reasons. Firstly, the information contained in the natural ordering of the predictor is lost. Secondly, because $n - 1$ coefficients are estimated for each predictor, where $n$ is the number of categories, the estimates can be noisy and the model prone to overfitting, especially when data are sparse within some categories. Monotonic effects A compromise position between these two extremes is to model ordinal predictors as having monotonic effects (assuming that predictor effects can be assumed to be truly monotonic and not, for instance, parabolic). In short, the method involves estimating a coefficient $b$, which expresses, similar to a typical regression coefficient, the expected average difference in the response variable between two adjacent categories of the ordinal predictor. In addition, a simplex vector $\zeta$ is estimated which describes the normalized distances between consecutive predictor categories, thus providing the shape of the monotonic effect. A software implementation is available in R package brms. The vignette provides detail and some useful extensions (monotonic interactions, random effects, etc). The original paper by Bürkner & Charpentier is also very good.
How can I predict a continuous variable using only ordinal covariates?
A problem with treating ordinal variables as numeric/continuous is that it assumes, often incorrectly, that predictor categories are equidistant with respect to their effect on the response variable.
How can I predict a continuous variable using only ordinal covariates? A problem with treating ordinal variables as numeric/continuous is that it assumes, often incorrectly, that predictor categories are equidistant with respect to their effect on the response variable. So, a change from category 1 to category 2 has the equivalent effect on the response variable as a change from category 2 to 3, etc. Treating ordinal predictors as categorical/unordered can also be problematic for several reasons. Firstly, the information contained in the natural ordering of the predictor is lost. Secondly, because $n - 1$ coefficients are estimated for each predictor, where $n$ is the number of categories, the estimates can be noisy and the model prone to overfitting, especially when data are sparse within some categories. Monotonic effects A compromise position between these two extremes is to model ordinal predictors as having monotonic effects (assuming that predictor effects can be assumed to be truly monotonic and not, for instance, parabolic). In short, the method involves estimating a coefficient $b$, which expresses, similar to a typical regression coefficient, the expected average difference in the response variable between two adjacent categories of the ordinal predictor. In addition, a simplex vector $\zeta$ is estimated which describes the normalized distances between consecutive predictor categories, thus providing the shape of the monotonic effect. A software implementation is available in R package brms. The vignette provides detail and some useful extensions (monotonic interactions, random effects, etc). The original paper by Bürkner & Charpentier is also very good.
How can I predict a continuous variable using only ordinal covariates? A problem with treating ordinal variables as numeric/continuous is that it assumes, often incorrectly, that predictor categories are equidistant with respect to their effect on the response variable.
28,668
How well do Covid-19 forecasts work?
First off, it's hard to assess whether there is a consensus in a rapidly evolving field. Any publication or result from one working group can (and will, and should) be criticized by other researchers. The fact that Ioannidis has made it a hobby to step on people's toes increases this effect (and makes for better theater, too). I personally take Ioannidis seriously. His 2005 starter toe-stepper was, statistically, not rocket science, but expressed a long-standing major problem in the application of statistics in a great, and admittedly grating, way. I don't know whether the replicability crisis in psychology would have gotten off the ground without him. However, he is not majorly specialized in forecasting as such. Then again, neither are the authors of the other paper you cite. So little clue here. (Also, the other paper you link tests their model against a no-change null model. That is definitely a useful benchmark, but there are also other simple benchmarks that would have been a little more convincing.) Note that there is an explicit answer to the Ioannidis paper by Taleb et al. (in press, IJF). Taleb does have more forecasting credentials, and his main point is how hard it is to evaluate forecasting performance in fat tailed situations - like pandemics. Add to that all the factors you note, like feedback loops between forecasts, political interventions, people's behavior, and it all gets very hard indeed. You may want to take a look at recent International Symposia on Forecasting. At the 2021 conference, there were multiple presentations about forecasting COVID-19 (and others about forecasting in the context of COVID-19). The abstracts sound like this: Laura Coroneo, "Testing the predictive accuracy of COVID-19 forecasts": First, at short-horizon (1-week ahead) no forecasting team outperforms a simple time-series benchmark. Second, at longer horizons (3 and 4-weeks ahead) forecasters are more successful and sometimes outperform the benchmark. Third, one of the best performing forecasts is the Ensemble forecast, that combines all available forecasts using uniform weights. In view of these results, collecting a wide range of forecasts and combining them in an ensemble forecast may be a safer approach for health authorities, rather than relying on a small number of forecasts. That ensembling improves forecasts is one of the few things forecasters agree on. Christos Emmanouilides, "Forecasting COVID-19: A large-scale comparison of alternative models": The study provides a substantial amount of evidence that forecasts from non-parametric regression models, estimated in about one-month-long rolling windows, are overall more accurate than point forecasts from other models. Recall Taleb's point about the difficulty in learning anything from point forecasts in the presence of fat tails. My personal takeaway is that there is so far little consensus about what kind of model works best, and that the more expert people are, the more they recognize that even posing and answering this question is extremely hard.
How well do Covid-19 forecasts work?
First off, it's hard to assess whether there is a consensus in a rapidly evolving field. Any publication or result from one working group can (and will, and should) be criticized by other researchers.
How well do Covid-19 forecasts work? First off, it's hard to assess whether there is a consensus in a rapidly evolving field. Any publication or result from one working group can (and will, and should) be criticized by other researchers. The fact that Ioannidis has made it a hobby to step on people's toes increases this effect (and makes for better theater, too). I personally take Ioannidis seriously. His 2005 starter toe-stepper was, statistically, not rocket science, but expressed a long-standing major problem in the application of statistics in a great, and admittedly grating, way. I don't know whether the replicability crisis in psychology would have gotten off the ground without him. However, he is not majorly specialized in forecasting as such. Then again, neither are the authors of the other paper you cite. So little clue here. (Also, the other paper you link tests their model against a no-change null model. That is definitely a useful benchmark, but there are also other simple benchmarks that would have been a little more convincing.) Note that there is an explicit answer to the Ioannidis paper by Taleb et al. (in press, IJF). Taleb does have more forecasting credentials, and his main point is how hard it is to evaluate forecasting performance in fat tailed situations - like pandemics. Add to that all the factors you note, like feedback loops between forecasts, political interventions, people's behavior, and it all gets very hard indeed. You may want to take a look at recent International Symposia on Forecasting. At the 2021 conference, there were multiple presentations about forecasting COVID-19 (and others about forecasting in the context of COVID-19). The abstracts sound like this: Laura Coroneo, "Testing the predictive accuracy of COVID-19 forecasts": First, at short-horizon (1-week ahead) no forecasting team outperforms a simple time-series benchmark. Second, at longer horizons (3 and 4-weeks ahead) forecasters are more successful and sometimes outperform the benchmark. Third, one of the best performing forecasts is the Ensemble forecast, that combines all available forecasts using uniform weights. In view of these results, collecting a wide range of forecasts and combining them in an ensemble forecast may be a safer approach for health authorities, rather than relying on a small number of forecasts. That ensembling improves forecasts is one of the few things forecasters agree on. Christos Emmanouilides, "Forecasting COVID-19: A large-scale comparison of alternative models": The study provides a substantial amount of evidence that forecasts from non-parametric regression models, estimated in about one-month-long rolling windows, are overall more accurate than point forecasts from other models. Recall Taleb's point about the difficulty in learning anything from point forecasts in the presence of fat tails. My personal takeaway is that there is so far little consensus about what kind of model works best, and that the more expert people are, the more they recognize that even posing and answering this question is extremely hard.
How well do Covid-19 forecasts work? First off, it's hard to assess whether there is a consensus in a rapidly evolving field. Any publication or result from one working group can (and will, and should) be criticized by other researchers.
28,669
Does Lasso make irrelevant the need for coefficient significance testing?
Summarizing information provided in comments: Lasso selects the optimal predictors to include in the model... No. LASSO selects a set of predictors that happens to work on a particular data set. There is no assurance that they are "optimal" in any broad sense. This is particularly the case when predictors associated with outcome are correlated. See this page and the pages there noted as "Linked" and "Related" for details. Try repeating LASSO on multiple bootstrapped samples of a data set, and see how frequently the same predictors are retained in the models. ... we don't need to do any of the typical significance testing that comes with OLS regression and logistic regression First, if you are mainly interested in prediction, then there is limited need to do significance testing. Given the risks of omitted-variable bias, there is little to be gained my omitting any predictors that might reasonably be associated with outcome unless you are at risk of overfitting the model. Just because you can't "prove" at p < 0.05 that some predictor is associated with outcome, that doesn't mean that it can't help improve predictions. Second, with proper care and understanding of what the p-values mean, inference is possible with LASSO. See this page for an introduction to the issues and further links.
Does Lasso make irrelevant the need for coefficient significance testing?
Summarizing information provided in comments: Lasso selects the optimal predictors to include in the model... No. LASSO selects a set of predictors that happens to work on a particular data set. The
Does Lasso make irrelevant the need for coefficient significance testing? Summarizing information provided in comments: Lasso selects the optimal predictors to include in the model... No. LASSO selects a set of predictors that happens to work on a particular data set. There is no assurance that they are "optimal" in any broad sense. This is particularly the case when predictors associated with outcome are correlated. See this page and the pages there noted as "Linked" and "Related" for details. Try repeating LASSO on multiple bootstrapped samples of a data set, and see how frequently the same predictors are retained in the models. ... we don't need to do any of the typical significance testing that comes with OLS regression and logistic regression First, if you are mainly interested in prediction, then there is limited need to do significance testing. Given the risks of omitted-variable bias, there is little to be gained my omitting any predictors that might reasonably be associated with outcome unless you are at risk of overfitting the model. Just because you can't "prove" at p < 0.05 that some predictor is associated with outcome, that doesn't mean that it can't help improve predictions. Second, with proper care and understanding of what the p-values mean, inference is possible with LASSO. See this page for an introduction to the issues and further links.
Does Lasso make irrelevant the need for coefficient significance testing? Summarizing information provided in comments: Lasso selects the optimal predictors to include in the model... No. LASSO selects a set of predictors that happens to work on a particular data set. The
28,670
Statistical Learning. Contradictions?
There’s no contradiction. The fact that something is easy to interpret has nothing to do with how accurate is it. The most interpretable model you could imagine is to predict constant, independently of the data. In such case, you would always be able to explain why your model made the prediction it made, but the predictions would be horrible. That said, it’s not the case that you need complicated, black-box models if you want accurate results and poorly performing models for interpretability. Here you can find nice, popular article by Cynthia Rudin and Joanna Radin, where they give example of interpretable models giving very good results and use it to discuss how performance vs interpretability is a false dichotomy. There’s also very interesting episode of Data Skeptic podcast on this subject hosting Cynthia Rudin. You may be interested also in the When is a biased estimator preferable to unbiased one? thread.
Statistical Learning. Contradictions?
There’s no contradiction. The fact that something is easy to interpret has nothing to do with how accurate is it. The most interpretable model you could imagine is to predict constant, independently o
Statistical Learning. Contradictions? There’s no contradiction. The fact that something is easy to interpret has nothing to do with how accurate is it. The most interpretable model you could imagine is to predict constant, independently of the data. In such case, you would always be able to explain why your model made the prediction it made, but the predictions would be horrible. That said, it’s not the case that you need complicated, black-box models if you want accurate results and poorly performing models for interpretability. Here you can find nice, popular article by Cynthia Rudin and Joanna Radin, where they give example of interpretable models giving very good results and use it to discuss how performance vs interpretability is a false dichotomy. There’s also very interesting episode of Data Skeptic podcast on this subject hosting Cynthia Rudin. You may be interested also in the When is a biased estimator preferable to unbiased one? thread.
Statistical Learning. Contradictions? There’s no contradiction. The fact that something is easy to interpret has nothing to do with how accurate is it. The most interpretable model you could imagine is to predict constant, independently o
28,671
Would you say this is a trade off between frequentist and Bayesian stats?
This is not the tradeoff between Bayesian and frequentist statistics. The likelihood function describes the probability (density) of the observations given particular parameter values. $$\mathcal{L(\theta | x)} = f(x\vert\theta)$$ It is reversing the dependent and independent parameters in the function, but it remains the same function. Likelihood vs probability This reversal occurs because often the behavior of the observations as a function of the parameters is known, but in practice we do not know the parameters and we know the observations. see the German tank problem for example Common problems in probability theory refer to the probability of observations $x_1, x_2, ... , x_n$ given a certain model and given the parameters (let's call them $\theta$) involved. For instance the probabilities for specific situations in card games or dice games are often very straightforward. However, in many practical situations we are dealing with an inverse situation (inferential statistics). That is: the observation $x_1, x_2, ... , x_k$ is given and now the model is unknown, or at least we do not know certain parameters $\theta$. The central limit theorem, or any simplification of the probability of the observations $x$ as a function of the parameters $\theta$, $f(x \vert \theta)$, applies to Bayesian and frequentist statistics in the same way. Both methods use the function $f(x \vert \theta)$ as starting point and the simplifications based on the CLT are applied to that function. See for instance this article 'Bayesian synthetic likelihood' by Price, Drovandi, Lee and Nott as an example where the CLT is applied in Bayesian statistics. The tradeoff The tradeoff between Bayesian and frequentist statistics is from Are there any examples where Bayesian credible intervals are obviously inferior to frequentist confidence intervals What is different? The confidence interval is restricted in the way that it draws the boundaries. The confidence interval places these boundaries by considering the conditional distribution $X_\theta$ and will cover $\alpha \%$ independent from what the true value of $\theta$ is (this independence is both the strength and weakness of the confidence interval). The credible interval makes an improvement by including information about the marginal distribution of $\theta$ and in this way it will be able to make smaller intervals without giving up on the average coverage which is still $\alpha \%$. (But it becomes less reliable/fails when the additional assumption, about the prior, is not true) The Bayesian and Frequentists methods condition their intervals on different scales. See for instance the differences in the conditional coverage for credible intervals (in the sense of highest posterior density interval) and confidence intervals In the image below (from the example in this answer/question) the expression of conditional probability/chance of containing the parameter conditional on the true parameter $\theta$ (left image) and conditional on the observation $x$ (right image). This relates to Why does a 95% Confidence Interval (CI) not imply a 95% chance of containing the mean? The confidence interval is constructed in such a way that it has the same probability of containing the parameter, independent from the true parameter value. The credible interval is constructed in such a way that it has the same probability of containing the parameter, independent from the observation. The trade-off is that the credible (Bayesian) interval allows making predictions with smaller intervals (which is advantageous, by contrast, imagine making the prediction that the parameter value is between $-\infty$ and $\infty$). But... the credible interval depends on prior information.
Would you say this is a trade off between frequentist and Bayesian stats?
This is not the tradeoff between Bayesian and frequentist statistics. The likelihood function describes the probability (density) of the observations given particular parameter values. $$\mathcal{L(\t
Would you say this is a trade off between frequentist and Bayesian stats? This is not the tradeoff between Bayesian and frequentist statistics. The likelihood function describes the probability (density) of the observations given particular parameter values. $$\mathcal{L(\theta | x)} = f(x\vert\theta)$$ It is reversing the dependent and independent parameters in the function, but it remains the same function. Likelihood vs probability This reversal occurs because often the behavior of the observations as a function of the parameters is known, but in practice we do not know the parameters and we know the observations. see the German tank problem for example Common problems in probability theory refer to the probability of observations $x_1, x_2, ... , x_n$ given a certain model and given the parameters (let's call them $\theta$) involved. For instance the probabilities for specific situations in card games or dice games are often very straightforward. However, in many practical situations we are dealing with an inverse situation (inferential statistics). That is: the observation $x_1, x_2, ... , x_k$ is given and now the model is unknown, or at least we do not know certain parameters $\theta$. The central limit theorem, or any simplification of the probability of the observations $x$ as a function of the parameters $\theta$, $f(x \vert \theta)$, applies to Bayesian and frequentist statistics in the same way. Both methods use the function $f(x \vert \theta)$ as starting point and the simplifications based on the CLT are applied to that function. See for instance this article 'Bayesian synthetic likelihood' by Price, Drovandi, Lee and Nott as an example where the CLT is applied in Bayesian statistics. The tradeoff The tradeoff between Bayesian and frequentist statistics is from Are there any examples where Bayesian credible intervals are obviously inferior to frequentist confidence intervals What is different? The confidence interval is restricted in the way that it draws the boundaries. The confidence interval places these boundaries by considering the conditional distribution $X_\theta$ and will cover $\alpha \%$ independent from what the true value of $\theta$ is (this independence is both the strength and weakness of the confidence interval). The credible interval makes an improvement by including information about the marginal distribution of $\theta$ and in this way it will be able to make smaller intervals without giving up on the average coverage which is still $\alpha \%$. (But it becomes less reliable/fails when the additional assumption, about the prior, is not true) The Bayesian and Frequentists methods condition their intervals on different scales. See for instance the differences in the conditional coverage for credible intervals (in the sense of highest posterior density interval) and confidence intervals In the image below (from the example in this answer/question) the expression of conditional probability/chance of containing the parameter conditional on the true parameter $\theta$ (left image) and conditional on the observation $x$ (right image). This relates to Why does a 95% Confidence Interval (CI) not imply a 95% chance of containing the mean? The confidence interval is constructed in such a way that it has the same probability of containing the parameter, independent from the true parameter value. The credible interval is constructed in such a way that it has the same probability of containing the parameter, independent from the observation. The trade-off is that the credible (Bayesian) interval allows making predictions with smaller intervals (which is advantageous, by contrast, imagine making the prediction that the parameter value is between $-\infty$ and $\infty$). But... the credible interval depends on prior information.
Would you say this is a trade off between frequentist and Bayesian stats? This is not the tradeoff between Bayesian and frequentist statistics. The likelihood function describes the probability (density) of the observations given particular parameter values. $$\mathcal{L(\t
28,672
Would you say this is a trade off between frequentist and Bayesian stats?
While that is not a direct answer to your question, it might also be interesting to note that the posterior will also behave like a normal distribution in large samples, a result that used to be relevant before MCMC methods became widely available. So, in the sense that asymptotics are always an approximation in the sense that we never have infinitely large samples in practice, the difference may not be that large as we obtain a normal shape in either case when sample size becomes large, and the issue is maybe rather how good that approximation is. Paraphrasing the discussion in Greenberg, Introduction to Bayesian econometrics: Writing the likelihood function of a simple random sample $y=(y_{1},\ldots ,y_{n})$ \begin{eqnarray*} L\left( \theta |y\right) &=&\prod_{i=1}^{n}f\left( y_{i}|\theta \right) \\ &=&\prod_{i=1}^{n}L\left( \theta |y_{i}\right) \end{eqnarray*} Log-likelihood: \begin{eqnarray*} l\left( \theta |y\right) &=& \ln L(\theta|y)\\ &=&\sum_{i=1}^{n}\ln L\left( \theta |y_{i}\right) \\ &=&\sum_{i=1}^{n}l\left( \theta |y_{i}\right) \\ &=&n\bar{l}\left( \theta |y\right) , \end{eqnarray*} where $\bar{l}\left( \theta |y\right) $ is the average contribution to the log-likelihood. Hence, \begin{eqnarray*} \pi \left( \theta |y\right) &\propto &\pi \left( \theta \right) L(\theta|y) \\ &=&\pi \left( \theta \right) \exp \left( n\bar{l}(\theta|y)\right) \end{eqnarray*} Now consider a Taylor series approximation of $l(\theta|y)$ around the maximum likelihood estimator $\hat{\theta}$ \begin{eqnarray*} l(\theta|y) &\approx &l(\hat{\theta}|y) \\ &&+\ l^{\prime}(\hat{\theta}|y)(\theta -\hat{\theta}) \\ &&+\ \frac{1}{2}l^{\prime\prime}(\hat{\theta}|y)(\theta -\hat{\theta})^{2}\\ &=& l(\hat{\theta}|y)-\frac{n}{2v}(\theta -\hat{\theta})^{2} \end{eqnarray*} with $$ v=\left[ -\frac{1}{n}\sum_{i=1}^{n}l^{\prime \prime }\left( \hat{\theta}|y_{i}\right) \right] ^{-1} $$ For large $n$ approximatively \begin{eqnarray*} \pi(\theta|y) &\propto &\pi(\theta) \exp(l(\theta|y)) \\ &\approx&\pi \left( \theta \right) \exp \left( l(\hat{\theta}|y)- \frac{n}{2v}(\theta -\hat{\theta})^{2}\right) \\ &\propto &\pi \left( \theta \right) \exp \left( -\frac{1}{2\left( v/n\right) }(\theta -\hat{\theta})^{2}\right) \end{eqnarray*} Here, we have dropped terms that do not depend on $\theta$ (such as the fixed value of the ML estimate). The exp-term is the (non-normalized) density of a normal distribution with expectation $\hat{\theta}$ and variance $v/n$. By "likelihood dominance" (by which I mean that the likelihood dominates the prior in large samples) we get kind of a Bayesian analogue to the asymptotic normality of an estimator.
Would you say this is a trade off between frequentist and Bayesian stats?
While that is not a direct answer to your question, it might also be interesting to note that the posterior will also behave like a normal distribution in large samples, a result that used to be relev
Would you say this is a trade off between frequentist and Bayesian stats? While that is not a direct answer to your question, it might also be interesting to note that the posterior will also behave like a normal distribution in large samples, a result that used to be relevant before MCMC methods became widely available. So, in the sense that asymptotics are always an approximation in the sense that we never have infinitely large samples in practice, the difference may not be that large as we obtain a normal shape in either case when sample size becomes large, and the issue is maybe rather how good that approximation is. Paraphrasing the discussion in Greenberg, Introduction to Bayesian econometrics: Writing the likelihood function of a simple random sample $y=(y_{1},\ldots ,y_{n})$ \begin{eqnarray*} L\left( \theta |y\right) &=&\prod_{i=1}^{n}f\left( y_{i}|\theta \right) \\ &=&\prod_{i=1}^{n}L\left( \theta |y_{i}\right) \end{eqnarray*} Log-likelihood: \begin{eqnarray*} l\left( \theta |y\right) &=& \ln L(\theta|y)\\ &=&\sum_{i=1}^{n}\ln L\left( \theta |y_{i}\right) \\ &=&\sum_{i=1}^{n}l\left( \theta |y_{i}\right) \\ &=&n\bar{l}\left( \theta |y\right) , \end{eqnarray*} where $\bar{l}\left( \theta |y\right) $ is the average contribution to the log-likelihood. Hence, \begin{eqnarray*} \pi \left( \theta |y\right) &\propto &\pi \left( \theta \right) L(\theta|y) \\ &=&\pi \left( \theta \right) \exp \left( n\bar{l}(\theta|y)\right) \end{eqnarray*} Now consider a Taylor series approximation of $l(\theta|y)$ around the maximum likelihood estimator $\hat{\theta}$ \begin{eqnarray*} l(\theta|y) &\approx &l(\hat{\theta}|y) \\ &&+\ l^{\prime}(\hat{\theta}|y)(\theta -\hat{\theta}) \\ &&+\ \frac{1}{2}l^{\prime\prime}(\hat{\theta}|y)(\theta -\hat{\theta})^{2}\\ &=& l(\hat{\theta}|y)-\frac{n}{2v}(\theta -\hat{\theta})^{2} \end{eqnarray*} with $$ v=\left[ -\frac{1}{n}\sum_{i=1}^{n}l^{\prime \prime }\left( \hat{\theta}|y_{i}\right) \right] ^{-1} $$ For large $n$ approximatively \begin{eqnarray*} \pi(\theta|y) &\propto &\pi(\theta) \exp(l(\theta|y)) \\ &\approx&\pi \left( \theta \right) \exp \left( l(\hat{\theta}|y)- \frac{n}{2v}(\theta -\hat{\theta})^{2}\right) \\ &\propto &\pi \left( \theta \right) \exp \left( -\frac{1}{2\left( v/n\right) }(\theta -\hat{\theta})^{2}\right) \end{eqnarray*} Here, we have dropped terms that do not depend on $\theta$ (such as the fixed value of the ML estimate). The exp-term is the (non-normalized) density of a normal distribution with expectation $\hat{\theta}$ and variance $v/n$. By "likelihood dominance" (by which I mean that the likelihood dominates the prior in large samples) we get kind of a Bayesian analogue to the asymptotic normality of an estimator.
Would you say this is a trade off between frequentist and Bayesian stats? While that is not a direct answer to your question, it might also be interesting to note that the posterior will also behave like a normal distribution in large samples, a result that used to be relev
28,673
Would you say this is a trade off between frequentist and Bayesian stats?
I see issues with your reasoning before even getting to the Bayesian setup. We absolutely do have to make assumptions when we use the central limit theorem! At the very least, we assume that the variance is finite. Perhaps we’re usually willing to make this assumption, but finite variance is not a given; it is an assumption. We shouldn’t have to rely on the central limit theorem to test a mean. That allows us to use z-tests and t-tests, but there are many other tests. Means aren’t always the values of interest, and if we want to test the variance, for instance, the central limit theorem is not as helpful since we aren’t testing the z-stat that the CLT says is asymptotically normal.
Would you say this is a trade off between frequentist and Bayesian stats?
I see issues with your reasoning before even getting to the Bayesian setup. We absolutely do have to make assumptions when we use the central limit theorem! At the very least, we assume that the vari
Would you say this is a trade off between frequentist and Bayesian stats? I see issues with your reasoning before even getting to the Bayesian setup. We absolutely do have to make assumptions when we use the central limit theorem! At the very least, we assume that the variance is finite. Perhaps we’re usually willing to make this assumption, but finite variance is not a given; it is an assumption. We shouldn’t have to rely on the central limit theorem to test a mean. That allows us to use z-tests and t-tests, but there are many other tests. Means aren’t always the values of interest, and if we want to test the variance, for instance, the central limit theorem is not as helpful since we aren’t testing the z-stat that the CLT says is asymptotically normal.
Would you say this is a trade off between frequentist and Bayesian stats? I see issues with your reasoning before even getting to the Bayesian setup. We absolutely do have to make assumptions when we use the central limit theorem! At the very least, we assume that the vari
28,674
Source for inter-ocular trauma test for significance
Joe Berkson coined the phrase. To my knowledge, it first shows up in 1963 in Edwards, Lindman, and Savage's "Bayesian Statistical Inference for Psychological Research" in Psychological Review, 70(3): The preceding paragraph illustrates a procedure that statisticians of all schools find important but elusive. It has been called the interocular traumatic test; you know what the data mean when the conclusion hits you between the eyes. They cite "personal communication" in July of 1958 with Joe Berkson for the idea. It may appear in literature sooner, but this 1963 paper is the earliest of which I'm aware.
Source for inter-ocular trauma test for significance
Joe Berkson coined the phrase. To my knowledge, it first shows up in 1963 in Edwards, Lindman, and Savage's "Bayesian Statistical Inference for Psychological Research" in Psychological Review, 70(3):
Source for inter-ocular trauma test for significance Joe Berkson coined the phrase. To my knowledge, it first shows up in 1963 in Edwards, Lindman, and Savage's "Bayesian Statistical Inference for Psychological Research" in Psychological Review, 70(3): The preceding paragraph illustrates a procedure that statisticians of all schools find important but elusive. It has been called the interocular traumatic test; you know what the data mean when the conclusion hits you between the eyes. They cite "personal communication" in July of 1958 with Joe Berkson for the idea. It may appear in literature sooner, but this 1963 paper is the earliest of which I'm aware.
Source for inter-ocular trauma test for significance Joe Berkson coined the phrase. To my knowledge, it first shows up in 1963 in Edwards, Lindman, and Savage's "Bayesian Statistical Inference for Psychological Research" in Psychological Review, 70(3):
28,675
In linear regression why does regularisation penalise the parameter values as well?
the parameter values just simply dependent on the data This is the key part of your question. This is where you are confused. Yes, the parameter values depend on the data. But the data are fixed when we fit a model. In other words, we fit a model conditional on the observations. It does not make sense to compare the complexity of different models that were fitted to different datasets. And in the context of a fixed dataset, a model $$ 2 + 5x + x^3$$ is indeed closer to the simplest possible model, namely the flat zero model, than $$ 433+ 342x + 323x^3,$$ and this holds regardless of the scale of your observations. Incidentally, the intercept ($2$ and $433$ in your example) is frequently not penalized, e.g., in most Lasso formulations, because we are usually good with letting it vary freely to capture the overall average of the observations. In other words, we shrink the model towards the average of the observations, not a complete zero model (where the zero would often be arbitrary). In this sense, a flat $2$ and a flat $433$ model would be considered equally complex.
In linear regression why does regularisation penalise the parameter values as well?
the parameter values just simply dependent on the data This is the key part of your question. This is where you are confused. Yes, the parameter values depend on the data. But the data are fixed when
In linear regression why does regularisation penalise the parameter values as well? the parameter values just simply dependent on the data This is the key part of your question. This is where you are confused. Yes, the parameter values depend on the data. But the data are fixed when we fit a model. In other words, we fit a model conditional on the observations. It does not make sense to compare the complexity of different models that were fitted to different datasets. And in the context of a fixed dataset, a model $$ 2 + 5x + x^3$$ is indeed closer to the simplest possible model, namely the flat zero model, than $$ 433+ 342x + 323x^3,$$ and this holds regardless of the scale of your observations. Incidentally, the intercept ($2$ and $433$ in your example) is frequently not penalized, e.g., in most Lasso formulations, because we are usually good with letting it vary freely to capture the overall average of the observations. In other words, we shrink the model towards the average of the observations, not a complete zero model (where the zero would often be arbitrary). In this sense, a flat $2$ and a flat $433$ model would be considered equally complex.
In linear regression why does regularisation penalise the parameter values as well? the parameter values just simply dependent on the data This is the key part of your question. This is where you are confused. Yes, the parameter values depend on the data. But the data are fixed when
28,676
Does Keras SGD optimizer implement batch, mini-batch, or stochastic gradient descent?
It works just as you suggest. batch_size parameter does exactly what you would expect: it sets the size of the batch: batch_size: Integer or None. Number of samples per gradient update. If unspecified, batch_size will default to 32. From programming point of view, Keras decouples the weight update formula parameters specific to each optimizer (learning rate, momentum, etc.) from the global training properties (batch size, training length, etc.) that are share between methods. It is matter of convenience—there is no point in having optimizers SGD, MBGD, BGD that all do the same thing just with different batch size.
Does Keras SGD optimizer implement batch, mini-batch, or stochastic gradient descent?
It works just as you suggest. batch_size parameter does exactly what you would expect: it sets the size of the batch: batch_size: Integer or None. Number of samples per gradient update. If unspecifi
Does Keras SGD optimizer implement batch, mini-batch, or stochastic gradient descent? It works just as you suggest. batch_size parameter does exactly what you would expect: it sets the size of the batch: batch_size: Integer or None. Number of samples per gradient update. If unspecified, batch_size will default to 32. From programming point of view, Keras decouples the weight update formula parameters specific to each optimizer (learning rate, momentum, etc.) from the global training properties (batch size, training length, etc.) that are share between methods. It is matter of convenience—there is no point in having optimizers SGD, MBGD, BGD that all do the same thing just with different batch size.
Does Keras SGD optimizer implement batch, mini-batch, or stochastic gradient descent? It works just as you suggest. batch_size parameter does exactly what you would expect: it sets the size of the batch: batch_size: Integer or None. Number of samples per gradient update. If unspecifi
28,677
Dealing with different definitions of the Ornstein-Uhlenbeck process
In order to have a stationary solution of the Stochastic Differential Equation (SDE), you have to start from a random initial value $u(0)$ at the fixed time $t=0$. This value must be drawn from the stationary distribution, here Gaussian. An alternative is to consider that the process $u(t)$ "has started in the remote past". Although $u(t)$ is not differentiable, it is appealing to write the SDE as $$ \frac{\text{d} u(t)}{\text{dt}} = - \theta u(t) + \eta(t), $$ where $\eta(t)$ is a Gaussian white noise with variance $\sigma^2$, leading to the following representation of $u(t)$ $$ u(t) = \int_{-\infty}^t e^{-\theta (t -s)} \, \eta(s) \,\text{d}s $$ which can be made more rigorous by replacing $\eta(s)\text{d}s$ by $\sigma \text{d}W(s)$. Using this representation, it is easy to derive the covariance of $u(t)$. For $r \geq 0$ $$ \text{E}[u(t) u(t+r)] = \sigma^2 \, \text{E} \left[\int_{-\infty}^t\int_{-\infty}^{t +r} e^{-\theta (t -s)} \, e^{-\theta (t + r -s')} \, \text{d}W(s) \text{d}W(s') \right], $$ and we can exchange the expectation and the integral(s), the expectation $\text{E}[\text{d}W(s) \text{d}W(s')]$ being $0$ for $s \neq s'$ and $\text{d}s$ when $s= s'$. Then by simple integration, we find $$ \text{E}[u(t) u(t+r)] = \frac{\sigma^2}{ \, 2 \theta} \, e^{-\theta r} \quad (r \geq 0). $$ Most of the literature dedicated to Itô's calculus assumes that $W(0) = 0$; This can be quite misleading for statistical problems where there is usually no special time "$t=0$" corresponding to a deterministic value of the process. Some adaptations are needed to cope with continuous time linear filters.
Dealing with different definitions of the Ornstein-Uhlenbeck process
In order to have a stationary solution of the Stochastic Differential Equation (SDE), you have to start from a random initial value $u(0)$ at the fixed time $t=0$. This value must be drawn from the st
Dealing with different definitions of the Ornstein-Uhlenbeck process In order to have a stationary solution of the Stochastic Differential Equation (SDE), you have to start from a random initial value $u(0)$ at the fixed time $t=0$. This value must be drawn from the stationary distribution, here Gaussian. An alternative is to consider that the process $u(t)$ "has started in the remote past". Although $u(t)$ is not differentiable, it is appealing to write the SDE as $$ \frac{\text{d} u(t)}{\text{dt}} = - \theta u(t) + \eta(t), $$ where $\eta(t)$ is a Gaussian white noise with variance $\sigma^2$, leading to the following representation of $u(t)$ $$ u(t) = \int_{-\infty}^t e^{-\theta (t -s)} \, \eta(s) \,\text{d}s $$ which can be made more rigorous by replacing $\eta(s)\text{d}s$ by $\sigma \text{d}W(s)$. Using this representation, it is easy to derive the covariance of $u(t)$. For $r \geq 0$ $$ \text{E}[u(t) u(t+r)] = \sigma^2 \, \text{E} \left[\int_{-\infty}^t\int_{-\infty}^{t +r} e^{-\theta (t -s)} \, e^{-\theta (t + r -s')} \, \text{d}W(s) \text{d}W(s') \right], $$ and we can exchange the expectation and the integral(s), the expectation $\text{E}[\text{d}W(s) \text{d}W(s')]$ being $0$ for $s \neq s'$ and $\text{d}s$ when $s= s'$. Then by simple integration, we find $$ \text{E}[u(t) u(t+r)] = \frac{\sigma^2}{ \, 2 \theta} \, e^{-\theta r} \quad (r \geq 0). $$ Most of the literature dedicated to Itô's calculus assumes that $W(0) = 0$; This can be quite misleading for statistical problems where there is usually no special time "$t=0$" corresponding to a deterministic value of the process. Some adaptations are needed to cope with continuous time linear filters.
Dealing with different definitions of the Ornstein-Uhlenbeck process In order to have a stationary solution of the Stochastic Differential Equation (SDE), you have to start from a random initial value $u(0)$ at the fixed time $t=0$. This value must be drawn from the st
28,678
Dealing with different definitions of the Ornstein-Uhlenbeck process
I initially believed that the mean parameter had a part to play as, in this link Rasmussen & Williams, 2006, Appendix B, equation B.27, the OU SDE is written as: $$ dX_t = - a_0 X(t)dt + b_0 dW_t $$ whereas the traditional equation is: $$ dX_t = \theta \mu dt - \theta X_tdt + \sigma dW_t $$ But this is not the case, the covariance is not dependant on the parameter $\mu$ as Billy pointed out. We'd expect the moments not to depend on location in a stationary process. The OU isn't stationary even when the parameter $\mu$ is 0, evident in Wikipedia's solution, given below. This in fact, tends to the RW solution: $$Cov(X_t, X_s) = \frac{\sigma^2}{2\theta} \left( e^{-\theta|t-s|} - e^{-\theta(t+s)} \right) \rightarrow \frac{\sigma^2}{2\theta} e^{-\theta|t-s|} $$ ... as t and/or s increase. So, as the process gets farther and farther from its initial condition, it tends to a stationary process. I can only speculate that they did not include the full non-stationary solution and provided the limiting case or perhaps the method of obtaining the covariance from the power spectrum assumes stationarity perhaps, I do not know. As for the proof of the the OU process being a GP, it's possible to solve the Fokker-Planck equation - you end up with the normal density (see the Wikipedia link). Hence, any at any finite set of points $\bf t$, $X$ will have a multivariate normal distribution, which is the definition of a GP.
Dealing with different definitions of the Ornstein-Uhlenbeck process
I initially believed that the mean parameter had a part to play as, in this link Rasmussen & Williams, 2006, Appendix B, equation B.27, the OU SDE is written as: $$ dX_t = - a_0 X(t)dt + b_0 dW_t $$ w
Dealing with different definitions of the Ornstein-Uhlenbeck process I initially believed that the mean parameter had a part to play as, in this link Rasmussen & Williams, 2006, Appendix B, equation B.27, the OU SDE is written as: $$ dX_t = - a_0 X(t)dt + b_0 dW_t $$ whereas the traditional equation is: $$ dX_t = \theta \mu dt - \theta X_tdt + \sigma dW_t $$ But this is not the case, the covariance is not dependant on the parameter $\mu$ as Billy pointed out. We'd expect the moments not to depend on location in a stationary process. The OU isn't stationary even when the parameter $\mu$ is 0, evident in Wikipedia's solution, given below. This in fact, tends to the RW solution: $$Cov(X_t, X_s) = \frac{\sigma^2}{2\theta} \left( e^{-\theta|t-s|} - e^{-\theta(t+s)} \right) \rightarrow \frac{\sigma^2}{2\theta} e^{-\theta|t-s|} $$ ... as t and/or s increase. So, as the process gets farther and farther from its initial condition, it tends to a stationary process. I can only speculate that they did not include the full non-stationary solution and provided the limiting case or perhaps the method of obtaining the covariance from the power spectrum assumes stationarity perhaps, I do not know. As for the proof of the the OU process being a GP, it's possible to solve the Fokker-Planck equation - you end up with the normal density (see the Wikipedia link). Hence, any at any finite set of points $\bf t$, $X$ will have a multivariate normal distribution, which is the definition of a GP.
Dealing with different definitions of the Ornstein-Uhlenbeck process I initially believed that the mean parameter had a part to play as, in this link Rasmussen & Williams, 2006, Appendix B, equation B.27, the OU SDE is written as: $$ dX_t = - a_0 X(t)dt + b_0 dW_t $$ w
28,679
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, crossed participants
Some plots to explore the data Below are eight, one for each number of surface contacts, x-y plots showing gloves versus no gloves. Each individuals is plotted with a dot. The mean and variance and covariance are indicated with a red dot and the ellipse (Mahalanobis distance corresponding to 97.5% of the population). You can see that the effects are only small in comparison to the spread of the population. The mean is higher for 'no gloves' and the mean changes a bit higher up for more surface contacts (which can be shown to be significant). But the effect is only little in size (overall a $\frac{1}{4}$ log reduction), and there are many individuals for who there is actually a higher bacteria count with the gloves. The small correlation shows that there is indeed a random effect from the individuals (if there wasn't an effect from the person then there should be no correlation between the paired gloves and no gloves). But it is only a small effect and an individual may have different random effects for 'gloves' and 'no gloves' (e.g. for all different contact point the individual may have consistently higher/lower counts for 'gloves' than 'no gloves'). Below plot are separate plots for each of the 35 individuals. The idea of this plot is to see whether the behavior is homogeneous and also to see what kind of function seems suitable. Note that the 'without gloves' is in red. In most of the cases the red line is higher, more bacteria for the cases 'without gloves'. I believe that a linear plot should be sufficient to capture the trends here. The disadvantage of the quadratic plot is that the coefficients are gonna be more difficult to interpret (you are not gonna see directly whether the slope is positive or negative because both the linear term and the quadratic term have an influence on this). But more importantly you see that the trends differ a lot among the different individuals and therefore it may be useful to add a random effect for not only the intercept, but also the slope of the individual. Model With the model below Each individual will get it's own curve fitted (random effects for linear coefficients). The model uses log-transformed data and fits with a regular (gaussian) linear model. In the comments amoeba mentioned that a log link is not relating to a lognormal distribution. But this is different. $y \sim N(\log(\mu),\sigma^2)$ is different from $\log(y) \sim N(\mu,\sigma^2)$ Weights are applied because the data is heteroskedastic. The variation is more narrow towards the higher numbers. This is probably because the bacteria count has some ceiling and the variation is mostly due to failing transmission from the surface to the finger (= related to lower counts). See also in the 35 plots. There are mainly a few individuals for which the variation is much higher than the others. (we see also bigger tails, overdispersion, in the qq-plots) No intercept term is used and a 'contrast' term is added. This is done to make the coefficients easier to interpret. . K <- read.csv("~/Downloads/K.txt", sep="") data <- K[K$Surface == 'P',] Contactsnumber <- data$NumberContacts Contactscontrast <- data$NumberContacts * (1-2*(data$Gloves == 'U')) data <- cbind(data, Contactsnumber, Contactscontrast) m <- lmer(log10CFU ~ 0 + Gloves + Contactsnumber + Contactscontrast + (0 + Gloves + Contactsnumber + Contactscontrast|Participant) , data=data, weights = data$log10CFU) This gives > summary(m) Linear mixed model fit by REML ['lmerMod'] Formula: log10CFU ~ 0 + Gloves + Contactsnumber + Contactscontrast + (0 + Gloves + Contactsnumber + Contactscontrast | Participant) Data: data Weights: data$log10CFU REML criterion at convergence: 180.8 Scaled residuals: Min 1Q Median 3Q Max -3.0972 -0.5141 0.0500 0.5448 5.1193 Random effects: Groups Name Variance Std.Dev. Corr Participant GlovesG 0.1242953 0.35256 GlovesU 0.0542441 0.23290 0.03 Contactsnumber 0.0007191 0.02682 -0.60 -0.13 Contactscontrast 0.0009701 0.03115 -0.70 0.49 0.51 Residual 0.2496486 0.49965 Number of obs: 560, groups: Participant, 35 Fixed effects: Estimate Std. Error t value GlovesG 4.203829 0.067646 62.14 GlovesU 4.363972 0.050226 86.89 Contactsnumber 0.043916 0.006308 6.96 Contactscontrast -0.007464 0.006854 -1.09 code to obtain plots chemometrics::drawMahal function # editted from chemometrics::drawMahal drawelipse <- function (x, center, covariance, quantile = c(0.975, 0.75, 0.5, 0.25), m = 1000, lwdcrit = 1, ...) { me <- center covm <- covariance cov.svd <- svd(covm, nv = 0) r <- cov.svd[["u"]] %*% diag(sqrt(cov.svd[["d"]])) alphamd <- sqrt(qchisq(quantile, 2)) lalpha <- length(alphamd) for (j in 1:lalpha) { e1md <- cos(c(0:m)/m * 2 * pi) * alphamd[j] e2md <- sin(c(0:m)/m * 2 * pi) * alphamd[j] emd <- cbind(e1md, e2md) ttmd <- t(r %*% t(emd)) + rep(1, m + 1) %o% me # if (j == 1) { # xmax <- max(c(x[, 1], ttmd[, 1])) # xmin <- min(c(x[, 1], ttmd[, 1])) # ymax <- max(c(x[, 2], ttmd[, 2])) # ymin <- min(c(x[, 2], ttmd[, 2])) # plot(x, xlim = c(xmin, xmax), ylim = c(ymin, ymax), # ...) # } } sdx <- sd(x[, 1]) sdy <- sd(x[, 2]) for (j in 2:lalpha) { e1md <- cos(c(0:m)/m * 2 * pi) * alphamd[j] e2md <- sin(c(0:m)/m * 2 * pi) * alphamd[j] emd <- cbind(e1md, e2md) ttmd <- t(r %*% t(emd)) + rep(1, m + 1) %o% me # lines(ttmd[, 1], ttmd[, 2], type = "l", col = 2) lines(ttmd[, 1], ttmd[, 2], type = "l", col = 1, lty=2) # } j <- 1 e1md <- cos(c(0:m)/m * 2 * pi) * alphamd[j] e2md <- sin(c(0:m)/m * 2 * pi) * alphamd[j] emd <- cbind(e1md, e2md) ttmd <- t(r %*% t(emd)) + rep(1, m + 1) %o% me # lines(ttmd[, 1], ttmd[, 2], type = "l", col = 1, lwd = lwdcrit) invisible() } 5 x 7 plot #### getting data K <- read.csv("~/Downloads/K.txt", sep="") ### plotting 35 individuals par(mar=c(2.6,2.6,2.1,1.1)) layout(matrix(1:35,5)) for (i in 1:35) { # selecting data with gloves for i-th participant sel <- c(1:624)[(K$Participant==i) & (K$Surface == 'P') & (K$Gloves == 'G')] # plot data plot(K$NumberContacts[sel],log(K$CFU,10)[sel], col=1, xlab="",ylab="",ylim=c(3,6)) # model and plot fit m <- lm(log(K$CFU[sel],10) ~ K$NumberContacts[sel]) lines(K$NumberContacts[sel],predict(m), col=1) # selecting data without gloves for i-th participant sel <- c(1:624)[(K$Participant==i) & (K$Surface == 'P') & (K$Gloves == 'U')] # plot data points(K$NumberContacts[sel],log(K$CFU,10)[sel], col=2) # model and plot fit m <- lm(log(K$CFU[sel],10) ~ K$NumberContacts[sel]) lines(K$NumberContacts[sel],predict(m), col=2) title(paste0("participant ",i)) } 2 x 4 plot #### plotting 8 treatments (number of contacts) par(mar=c(5.1,4.1,4.1,2.1)) layout(matrix(1:8,2,byrow=1)) for (i in c(1:8)) { # plot canvas plot(c(3,6),c(3,6), xlim = c(3,6), ylim = c(3,6), type="l", lty=2, xlab='gloves', ylab='no gloves') # select points and plot sel1 <- c(1:624)[(K$NumberContacts==i) & (K$Surface == 'P') & (K$Gloves == 'G')] sel2 <- c(1:624)[(K$NumberContacts==i) & (K$Surface == 'P') & (K$Gloves == 'U')] points(K$log10CFU[sel1],K$log10CFU[sel2]) title(paste0("contact ",i)) # plot mean points(mean(K$log10CFU[sel1]),mean(K$log10CFU[sel2]),pch=21,col=1,bg=2) # plot elipse for mahalanobis distance dd <- cbind(K$log10CFU[sel1],K$log10CFU[sel2]) drawelipse(dd,center=apply(dd,2,mean), covariance=cov(dd), quantile=0.975,col="blue", xlim = c(3,6), ylim = c(3,6), type="l", lty=2, xlab='gloves', ylab='no gloves') }
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, c
Some plots to explore the data Below are eight, one for each number of surface contacts, x-y plots showing gloves versus no gloves. Each individuals is plotted with a dot. The mean and variance and c
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, crossed participants Some plots to explore the data Below are eight, one for each number of surface contacts, x-y plots showing gloves versus no gloves. Each individuals is plotted with a dot. The mean and variance and covariance are indicated with a red dot and the ellipse (Mahalanobis distance corresponding to 97.5% of the population). You can see that the effects are only small in comparison to the spread of the population. The mean is higher for 'no gloves' and the mean changes a bit higher up for more surface contacts (which can be shown to be significant). But the effect is only little in size (overall a $\frac{1}{4}$ log reduction), and there are many individuals for who there is actually a higher bacteria count with the gloves. The small correlation shows that there is indeed a random effect from the individuals (if there wasn't an effect from the person then there should be no correlation between the paired gloves and no gloves). But it is only a small effect and an individual may have different random effects for 'gloves' and 'no gloves' (e.g. for all different contact point the individual may have consistently higher/lower counts for 'gloves' than 'no gloves'). Below plot are separate plots for each of the 35 individuals. The idea of this plot is to see whether the behavior is homogeneous and also to see what kind of function seems suitable. Note that the 'without gloves' is in red. In most of the cases the red line is higher, more bacteria for the cases 'without gloves'. I believe that a linear plot should be sufficient to capture the trends here. The disadvantage of the quadratic plot is that the coefficients are gonna be more difficult to interpret (you are not gonna see directly whether the slope is positive or negative because both the linear term and the quadratic term have an influence on this). But more importantly you see that the trends differ a lot among the different individuals and therefore it may be useful to add a random effect for not only the intercept, but also the slope of the individual. Model With the model below Each individual will get it's own curve fitted (random effects for linear coefficients). The model uses log-transformed data and fits with a regular (gaussian) linear model. In the comments amoeba mentioned that a log link is not relating to a lognormal distribution. But this is different. $y \sim N(\log(\mu),\sigma^2)$ is different from $\log(y) \sim N(\mu,\sigma^2)$ Weights are applied because the data is heteroskedastic. The variation is more narrow towards the higher numbers. This is probably because the bacteria count has some ceiling and the variation is mostly due to failing transmission from the surface to the finger (= related to lower counts). See also in the 35 plots. There are mainly a few individuals for which the variation is much higher than the others. (we see also bigger tails, overdispersion, in the qq-plots) No intercept term is used and a 'contrast' term is added. This is done to make the coefficients easier to interpret. . K <- read.csv("~/Downloads/K.txt", sep="") data <- K[K$Surface == 'P',] Contactsnumber <- data$NumberContacts Contactscontrast <- data$NumberContacts * (1-2*(data$Gloves == 'U')) data <- cbind(data, Contactsnumber, Contactscontrast) m <- lmer(log10CFU ~ 0 + Gloves + Contactsnumber + Contactscontrast + (0 + Gloves + Contactsnumber + Contactscontrast|Participant) , data=data, weights = data$log10CFU) This gives > summary(m) Linear mixed model fit by REML ['lmerMod'] Formula: log10CFU ~ 0 + Gloves + Contactsnumber + Contactscontrast + (0 + Gloves + Contactsnumber + Contactscontrast | Participant) Data: data Weights: data$log10CFU REML criterion at convergence: 180.8 Scaled residuals: Min 1Q Median 3Q Max -3.0972 -0.5141 0.0500 0.5448 5.1193 Random effects: Groups Name Variance Std.Dev. Corr Participant GlovesG 0.1242953 0.35256 GlovesU 0.0542441 0.23290 0.03 Contactsnumber 0.0007191 0.02682 -0.60 -0.13 Contactscontrast 0.0009701 0.03115 -0.70 0.49 0.51 Residual 0.2496486 0.49965 Number of obs: 560, groups: Participant, 35 Fixed effects: Estimate Std. Error t value GlovesG 4.203829 0.067646 62.14 GlovesU 4.363972 0.050226 86.89 Contactsnumber 0.043916 0.006308 6.96 Contactscontrast -0.007464 0.006854 -1.09 code to obtain plots chemometrics::drawMahal function # editted from chemometrics::drawMahal drawelipse <- function (x, center, covariance, quantile = c(0.975, 0.75, 0.5, 0.25), m = 1000, lwdcrit = 1, ...) { me <- center covm <- covariance cov.svd <- svd(covm, nv = 0) r <- cov.svd[["u"]] %*% diag(sqrt(cov.svd[["d"]])) alphamd <- sqrt(qchisq(quantile, 2)) lalpha <- length(alphamd) for (j in 1:lalpha) { e1md <- cos(c(0:m)/m * 2 * pi) * alphamd[j] e2md <- sin(c(0:m)/m * 2 * pi) * alphamd[j] emd <- cbind(e1md, e2md) ttmd <- t(r %*% t(emd)) + rep(1, m + 1) %o% me # if (j == 1) { # xmax <- max(c(x[, 1], ttmd[, 1])) # xmin <- min(c(x[, 1], ttmd[, 1])) # ymax <- max(c(x[, 2], ttmd[, 2])) # ymin <- min(c(x[, 2], ttmd[, 2])) # plot(x, xlim = c(xmin, xmax), ylim = c(ymin, ymax), # ...) # } } sdx <- sd(x[, 1]) sdy <- sd(x[, 2]) for (j in 2:lalpha) { e1md <- cos(c(0:m)/m * 2 * pi) * alphamd[j] e2md <- sin(c(0:m)/m * 2 * pi) * alphamd[j] emd <- cbind(e1md, e2md) ttmd <- t(r %*% t(emd)) + rep(1, m + 1) %o% me # lines(ttmd[, 1], ttmd[, 2], type = "l", col = 2) lines(ttmd[, 1], ttmd[, 2], type = "l", col = 1, lty=2) # } j <- 1 e1md <- cos(c(0:m)/m * 2 * pi) * alphamd[j] e2md <- sin(c(0:m)/m * 2 * pi) * alphamd[j] emd <- cbind(e1md, e2md) ttmd <- t(r %*% t(emd)) + rep(1, m + 1) %o% me # lines(ttmd[, 1], ttmd[, 2], type = "l", col = 1, lwd = lwdcrit) invisible() } 5 x 7 plot #### getting data K <- read.csv("~/Downloads/K.txt", sep="") ### plotting 35 individuals par(mar=c(2.6,2.6,2.1,1.1)) layout(matrix(1:35,5)) for (i in 1:35) { # selecting data with gloves for i-th participant sel <- c(1:624)[(K$Participant==i) & (K$Surface == 'P') & (K$Gloves == 'G')] # plot data plot(K$NumberContacts[sel],log(K$CFU,10)[sel], col=1, xlab="",ylab="",ylim=c(3,6)) # model and plot fit m <- lm(log(K$CFU[sel],10) ~ K$NumberContacts[sel]) lines(K$NumberContacts[sel],predict(m), col=1) # selecting data without gloves for i-th participant sel <- c(1:624)[(K$Participant==i) & (K$Surface == 'P') & (K$Gloves == 'U')] # plot data points(K$NumberContacts[sel],log(K$CFU,10)[sel], col=2) # model and plot fit m <- lm(log(K$CFU[sel],10) ~ K$NumberContacts[sel]) lines(K$NumberContacts[sel],predict(m), col=2) title(paste0("participant ",i)) } 2 x 4 plot #### plotting 8 treatments (number of contacts) par(mar=c(5.1,4.1,4.1,2.1)) layout(matrix(1:8,2,byrow=1)) for (i in c(1:8)) { # plot canvas plot(c(3,6),c(3,6), xlim = c(3,6), ylim = c(3,6), type="l", lty=2, xlab='gloves', ylab='no gloves') # select points and plot sel1 <- c(1:624)[(K$NumberContacts==i) & (K$Surface == 'P') & (K$Gloves == 'G')] sel2 <- c(1:624)[(K$NumberContacts==i) & (K$Surface == 'P') & (K$Gloves == 'U')] points(K$log10CFU[sel1],K$log10CFU[sel2]) title(paste0("contact ",i)) # plot mean points(mean(K$log10CFU[sel1]),mean(K$log10CFU[sel2]),pch=21,col=1,bg=2) # plot elipse for mahalanobis distance dd <- cbind(K$log10CFU[sel1],K$log10CFU[sel2]) drawelipse(dd,center=apply(dd,2,mean), covariance=cov(dd), quantile=0.975,col="blue", xlim = c(3,6), ylim = c(3,6), type="l", lty=2, xlab='gloves', ylab='no gloves') }
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, c Some plots to explore the data Below are eight, one for each number of surface contacts, x-y plots showing gloves versus no gloves. Each individuals is plotted with a dot. The mean and variance and c
28,680
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, crossed participants
Firstly, good work on your graph; it gives a clear representation of the data, so you can already see the kind of pattern in the data based on the number of contacts and the use or absence of gloves.$^\dagger$ Looking at this graph, I would think you will get good results with a basic log-polynomial model, with random effects for the participants. The model you have chosen looks reasonable, but you might also consider adding a quadratic term for the number of contacts. As to whether to use MASS:glmmPQL or lme4:glmer for your model, my understanding is that both these functions will fit the same model (so long as you set the model equation, distribution and link function the same) but they use different estimation methods to find the fit. I could be mistaken, but my understanding from the documentation is that glmmPQL uses penalised quasi-likelihood as described in Wolfinger and O'Connell (1993), whereas glmer uses Gauss-Hermite quadrature. If you are worried about it you can fit your model with both methods and check that they give the same coefficient estimates and that way you will have greater confidence that the fitting algorithm has converged to the true MLEs of the coefficients. Should NumberContacts be a categorical factor? This variable has a natural ordering that appears from your plots to have a smooth relationship with the response variable, so you could reasonably treat it as a numeric variable. If you were to include factor(NumberContacts) then you will not constrain its form and you will not lose many degrees-of-freedom. You could even use the interaction Gloves*factor(NumberContacts) without losing too many degrees-of-freedom. However, it is worth considering whether using a factor variable would involve over-fitting the data. Given that there is a fairly smooth relationship in your plot a simple linear function or quadratic would get good results without over-fitting. How do you make Participant a random slope but not intercept variable? You have already put your response variable on a log-scale by using a logarithmic link function, so an intercept effect for Participant is giving a multiplicative effect on the response. If you were to give this a random slope interacting with NumberContacts then it would have a power-based effect on the response. If you want this then you can get it with (~ -1 + NumberContacts|Participant) which will remove the intercept but add a slope based on the number of contacts. Should I use Box-Cox for transforming my data? (e.g. lambda=0.779) If in doubt, try fitting a model with this transformation and see how it compares to other models using appropriate goodness-of-fit statistics. If you are going to use this transformation it would be better to leave the parameter $\lambda$ as a free parameter and let it be estimated as part of your model, rather than pre-specifying a value. Should I include weights for variance? Start by looking at your residual plot to see if there is evidence of heteroscedasticity. Based on the plots you have already included it looks to me like this is not an issue, so you don't need to add any weights for the variance. If in doubt you could add weights using a simple linear function and then perform a statistical test to see if the slope of the weighting is flat. That would amount to a formal test of heteroscedasticity, which would give you some backup for your choice. Should I include autocorrelation in NumberContacts? If you have already included a random effect term for the participant then it would probably be a bad idea to add an auto-correlation term on the number of contacts. Your experiment uses a different finger for different numbers of contacts so you would not expect autocorrelation for the case where you have already accounted for the participant. Adding an autocorrelation term in addition to the participant effect would mean that you think there is a conditional dependence between the outcome of different fingers, based on the number of contacts, even for a given participant. $^\dagger$ Your graph is good in showing the relationships, but you could improve it aesthetically by adding a title and subtitle information and giving it better axis labels. You could also simplify your legend by removing its title and changing 'Yes' to 'Gloves' and 'No' to 'No Gloves'.
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, c
Firstly, good work on your graph; it gives a clear representation of the data, so you can already see the kind of pattern in the data based on the number of contacts and the use or absence of gloves.$
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, crossed participants Firstly, good work on your graph; it gives a clear representation of the data, so you can already see the kind of pattern in the data based on the number of contacts and the use or absence of gloves.$^\dagger$ Looking at this graph, I would think you will get good results with a basic log-polynomial model, with random effects for the participants. The model you have chosen looks reasonable, but you might also consider adding a quadratic term for the number of contacts. As to whether to use MASS:glmmPQL or lme4:glmer for your model, my understanding is that both these functions will fit the same model (so long as you set the model equation, distribution and link function the same) but they use different estimation methods to find the fit. I could be mistaken, but my understanding from the documentation is that glmmPQL uses penalised quasi-likelihood as described in Wolfinger and O'Connell (1993), whereas glmer uses Gauss-Hermite quadrature. If you are worried about it you can fit your model with both methods and check that they give the same coefficient estimates and that way you will have greater confidence that the fitting algorithm has converged to the true MLEs of the coefficients. Should NumberContacts be a categorical factor? This variable has a natural ordering that appears from your plots to have a smooth relationship with the response variable, so you could reasonably treat it as a numeric variable. If you were to include factor(NumberContacts) then you will not constrain its form and you will not lose many degrees-of-freedom. You could even use the interaction Gloves*factor(NumberContacts) without losing too many degrees-of-freedom. However, it is worth considering whether using a factor variable would involve over-fitting the data. Given that there is a fairly smooth relationship in your plot a simple linear function or quadratic would get good results without over-fitting. How do you make Participant a random slope but not intercept variable? You have already put your response variable on a log-scale by using a logarithmic link function, so an intercept effect for Participant is giving a multiplicative effect on the response. If you were to give this a random slope interacting with NumberContacts then it would have a power-based effect on the response. If you want this then you can get it with (~ -1 + NumberContacts|Participant) which will remove the intercept but add a slope based on the number of contacts. Should I use Box-Cox for transforming my data? (e.g. lambda=0.779) If in doubt, try fitting a model with this transformation and see how it compares to other models using appropriate goodness-of-fit statistics. If you are going to use this transformation it would be better to leave the parameter $\lambda$ as a free parameter and let it be estimated as part of your model, rather than pre-specifying a value. Should I include weights for variance? Start by looking at your residual plot to see if there is evidence of heteroscedasticity. Based on the plots you have already included it looks to me like this is not an issue, so you don't need to add any weights for the variance. If in doubt you could add weights using a simple linear function and then perform a statistical test to see if the slope of the weighting is flat. That would amount to a formal test of heteroscedasticity, which would give you some backup for your choice. Should I include autocorrelation in NumberContacts? If you have already included a random effect term for the participant then it would probably be a bad idea to add an auto-correlation term on the number of contacts. Your experiment uses a different finger for different numbers of contacts so you would not expect autocorrelation for the case where you have already accounted for the participant. Adding an autocorrelation term in addition to the participant effect would mean that you think there is a conditional dependence between the outcome of different fingers, based on the number of contacts, even for a given participant. $^\dagger$ Your graph is good in showing the relationships, but you could improve it aesthetically by adding a title and subtitle information and giving it better axis labels. You could also simplify your legend by removing its title and changing 'Yes' to 'Gloves' and 'No' to 'No Gloves'.
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, c Firstly, good work on your graph; it gives a clear representation of the data, so you can already see the kind of pattern in the data based on the number of contacts and the use or absence of gloves.$
28,681
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, crossed participants
Indeed, it is reasonable to argue that measurements taken from one participant are not independent from those taken from another participant. For example, some people might tend to press their finger with more (or less) force, which would affect all their measurements accross each number of contacts. So the 2-way repeated-measures ANOVA would be an acceptable model to apply in this case. Alternatively, one could also apply a mixed-effects model with participant as a random factor. This is a more advanced and a more sophisticated solution.
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, c
Indeed, it is reasonable to argue that measurements taken from one participant are not independent from those taken from another participant. For example, some people might tend to press their finger
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, crossed participants Indeed, it is reasonable to argue that measurements taken from one participant are not independent from those taken from another participant. For example, some people might tend to press their finger with more (or less) force, which would affect all their measurements accross each number of contacts. So the 2-way repeated-measures ANOVA would be an acceptable model to apply in this case. Alternatively, one could also apply a mixed-effects model with participant as a random factor. This is a more advanced and a more sophisticated solution.
Bacteria picked up on fingers after multiple surface contacts: non-normal data, repeated measures, c Indeed, it is reasonable to argue that measurements taken from one participant are not independent from those taken from another participant. For example, some people might tend to press their finger
28,682
The advantage of log-loss metric over f-score
The log-loss is a type of loss function. Your model will optimize it (e.g. minimizing) for reaching your goal. Usually it needs to be differentiable, since you could need to calculate the derivative for getting the max or min (these details depend from your optimization algorithm). The f-score is a metric. A metric is used to evaluate the performance of your model, in this case considering the harmonic mean between precision and recall, but it's not involved in the optimization process and they are not required to be differentiable (so you can't use them for training your model).
The advantage of log-loss metric over f-score
The log-loss is a type of loss function. Your model will optimize it (e.g. minimizing) for reaching your goal. Usually it needs to be differentiable, since you could need to calculate the derivative f
The advantage of log-loss metric over f-score The log-loss is a type of loss function. Your model will optimize it (e.g. minimizing) for reaching your goal. Usually it needs to be differentiable, since you could need to calculate the derivative for getting the max or min (these details depend from your optimization algorithm). The f-score is a metric. A metric is used to evaluate the performance of your model, in this case considering the harmonic mean between precision and recall, but it's not involved in the optimization process and they are not required to be differentiable (so you can't use them for training your model).
The advantage of log-loss metric over f-score The log-loss is a type of loss function. Your model will optimize it (e.g. minimizing) for reaching your goal. Usually it needs to be differentiable, since you could need to calculate the derivative f
28,683
Convergence of Stochastic Gradient Descent as a function of training set size
In the first part they are talking about large-scale SGD convergence in practice and in the second part theoretical results on the convergence of SGD when the optimisation problem is convex. "The number of updates required to reach convergence usually increases with training set size". I found this statement confusing but as @DeltaIV kindly pointed out in the comments I think they are talking about practical considerations for a fixed model as the dataset size $m \rightarrow \infty$. I think there are two relevant phenomena: performance tradeoffs when you try to do distributed SGD, or performance on a real-world non-convex optimisation problem Computational tradeoffs for distributed SGD In a large volume and high rate data scenario, you might want to try to implement a distributed version of SGD (or more likely minibatch SGD). Unfortunately making a distributed, efficient version of SGD is difficult as you need to frequently share the parameter state $w$. In particular, you incur a large overhead cost for synchronising between computers so it incentivises you use larger minibatchs. The following figure from (Li et al., 2014) illustrates this nicely SGD here is minibatch SGD and the other lines are algorithms they propose. However it's also known that for convex problems minibatchs incur a computational cost which effectively slows convergence with increased minibatch size. As you increase minibatch size $m'$ towards the dataset size $m$ it becomes slower and slower until you're just doing regular batch gradient descent. This decrease can be kinda drastic if a large mini-batch size is used. Again this is illustrated nicely by (Li et al, 2014): Here they are plotting the minimum objective value they found on the KDD04 dataset after using $10^7$ datapoints. Formally, if $f$ is a strongly convex function with global optimum $w^*$, and if $w_t$ is the output of SGD at the $t^{th}$ iteration. Then you can prove that in expectation you have: $$ \mathbb{E}[f(w_t) - f(w^*)] \leq \mathcal{O}(\frac{1}{\sqrt{t}}). $$ Note that this doesn't depend on the dataset size (this is relevant to your next question)! However for minibatch SGD with batch size $b$ the convergence to the optimum happens at a rate of $\mathcal{O}(\frac{1}{\sqrt{bt}} + \frac{1}{bt})$. When you have a very large amount of data (Li et al., 2014) make the point that: Since the total number of examples examined is $bt$ while there is only a $\sqrt{b}$ times improvement, the convergence speed degrades with increasing minibatch size. You have a trade-off between the synchronisation cost for small mini-batches, and the performance penalty for increased minibatch size. If you naively parallelise (minibatch) SGD you pay some penalty and your convergence rate slows as the data size increases. Nonconvexity of the empirical optimisation problem This is basically the point that @dopexxx has made. It's pretty well-known that the optimisation problem that you want to solve for deep neural nets in practice is not convex. In particular, it can have the following bad properties: local minima and saddle points plateau regions widely varying curvature In general the shape you're trying to optimise over is thought to be a manifold and as far as I am aware all you can say about convergence is that you're going converge to (a noise ball around) a stationary point. It seems reasonable that the greater the variety of real world data, the more complicated this manifold will be. Because the real gradient is more complicated as $m$ increase you need more samples to approximate $\nabla f$ with SGD. "However, as m approaches infinity, the model will eventually converge to its best possible test error before SGD has sampled every example in the training set. Increasing m further will not extend the amount of training time needed to reach the model’s best possible test error." (Goodfellow et al., 2016) state this a little more precisely in the discussion in section 8.3.1, where they state: The most important property of SGD and the related minibatch or online gradient-based optimisation is that computation time per update does not grow with the number of training examples. This allows convergence even when the number of training examples becomes very large. For a large enough dataset, SGD may converge to within some fixed tolerance of its final test set error before it has processed the entire training dataset. (Bottou et al., 2017) offer the following clear explanation: On an intuitive level, SG employs information more efficiently than a batch method. To see this, consider a situation in which a training set, call it $S$, consists of ten copies of a set $S_{sub}$. A minimizer of empirical risk for the larger set S is clearly given by a minimizer for the smaller set $S_{sub}$, but if one were to apply a batch approach to minimize $R_n$ over $S$, then each iteration would be ten times more expensive than if one only had one copy of $S_{sub}$. On the other hand, SG performs the same computations in both scenarios, in the sense that the stochastic gradient computations involve choosing elements from $S_{sub}$ with the same probabilities. where $R_n$ is the empirical risk (essentially the training loss). If you let the number of copies get arbitrarily large, then SGD will certainly converge before it's sampled every data point. I think this agrees with my statistical intuition. You can achieve $|x^{\text{opt}} - x_k| < \epsilon$ at iteration $k$ before you necessarily sample all the points in your dataset, because your tolerance for error $\epsilon$ really determines how much data you need to look at, i.e. how many iterations of SGD you need to complete. I found the first part of the paper by (Bottou et al., 2017) quite helpful for understanding SGD better. References Bottou, Léon, Frank E. Curtis, and Jorge Nocedal. "Optimization methods for large-scale machine learning." arXiv preprint arXiv:1606.04838 (2016). https://arxiv.org/pdf/1606.04838.pdf Li, Mu, et al. "Efficient mini-batch training for stochastic optimization." Proceedings of the 20th ACM SIGKDD international conference on Knowledge discovery and data mining. ACM, 2014. https://www.cs.cmu.edu/~muli/file/minibatch_sgd.pdf
Convergence of Stochastic Gradient Descent as a function of training set size
In the first part they are talking about large-scale SGD convergence in practice and in the second part theoretical results on the convergence of SGD when the optimisation problem is convex. "The nu
Convergence of Stochastic Gradient Descent as a function of training set size In the first part they are talking about large-scale SGD convergence in practice and in the second part theoretical results on the convergence of SGD when the optimisation problem is convex. "The number of updates required to reach convergence usually increases with training set size". I found this statement confusing but as @DeltaIV kindly pointed out in the comments I think they are talking about practical considerations for a fixed model as the dataset size $m \rightarrow \infty$. I think there are two relevant phenomena: performance tradeoffs when you try to do distributed SGD, or performance on a real-world non-convex optimisation problem Computational tradeoffs for distributed SGD In a large volume and high rate data scenario, you might want to try to implement a distributed version of SGD (or more likely minibatch SGD). Unfortunately making a distributed, efficient version of SGD is difficult as you need to frequently share the parameter state $w$. In particular, you incur a large overhead cost for synchronising between computers so it incentivises you use larger minibatchs. The following figure from (Li et al., 2014) illustrates this nicely SGD here is minibatch SGD and the other lines are algorithms they propose. However it's also known that for convex problems minibatchs incur a computational cost which effectively slows convergence with increased minibatch size. As you increase minibatch size $m'$ towards the dataset size $m$ it becomes slower and slower until you're just doing regular batch gradient descent. This decrease can be kinda drastic if a large mini-batch size is used. Again this is illustrated nicely by (Li et al, 2014): Here they are plotting the minimum objective value they found on the KDD04 dataset after using $10^7$ datapoints. Formally, if $f$ is a strongly convex function with global optimum $w^*$, and if $w_t$ is the output of SGD at the $t^{th}$ iteration. Then you can prove that in expectation you have: $$ \mathbb{E}[f(w_t) - f(w^*)] \leq \mathcal{O}(\frac{1}{\sqrt{t}}). $$ Note that this doesn't depend on the dataset size (this is relevant to your next question)! However for minibatch SGD with batch size $b$ the convergence to the optimum happens at a rate of $\mathcal{O}(\frac{1}{\sqrt{bt}} + \frac{1}{bt})$. When you have a very large amount of data (Li et al., 2014) make the point that: Since the total number of examples examined is $bt$ while there is only a $\sqrt{b}$ times improvement, the convergence speed degrades with increasing minibatch size. You have a trade-off between the synchronisation cost for small mini-batches, and the performance penalty for increased minibatch size. If you naively parallelise (minibatch) SGD you pay some penalty and your convergence rate slows as the data size increases. Nonconvexity of the empirical optimisation problem This is basically the point that @dopexxx has made. It's pretty well-known that the optimisation problem that you want to solve for deep neural nets in practice is not convex. In particular, it can have the following bad properties: local minima and saddle points plateau regions widely varying curvature In general the shape you're trying to optimise over is thought to be a manifold and as far as I am aware all you can say about convergence is that you're going converge to (a noise ball around) a stationary point. It seems reasonable that the greater the variety of real world data, the more complicated this manifold will be. Because the real gradient is more complicated as $m$ increase you need more samples to approximate $\nabla f$ with SGD. "However, as m approaches infinity, the model will eventually converge to its best possible test error before SGD has sampled every example in the training set. Increasing m further will not extend the amount of training time needed to reach the model’s best possible test error." (Goodfellow et al., 2016) state this a little more precisely in the discussion in section 8.3.1, where they state: The most important property of SGD and the related minibatch or online gradient-based optimisation is that computation time per update does not grow with the number of training examples. This allows convergence even when the number of training examples becomes very large. For a large enough dataset, SGD may converge to within some fixed tolerance of its final test set error before it has processed the entire training dataset. (Bottou et al., 2017) offer the following clear explanation: On an intuitive level, SG employs information more efficiently than a batch method. To see this, consider a situation in which a training set, call it $S$, consists of ten copies of a set $S_{sub}$. A minimizer of empirical risk for the larger set S is clearly given by a minimizer for the smaller set $S_{sub}$, but if one were to apply a batch approach to minimize $R_n$ over $S$, then each iteration would be ten times more expensive than if one only had one copy of $S_{sub}$. On the other hand, SG performs the same computations in both scenarios, in the sense that the stochastic gradient computations involve choosing elements from $S_{sub}$ with the same probabilities. where $R_n$ is the empirical risk (essentially the training loss). If you let the number of copies get arbitrarily large, then SGD will certainly converge before it's sampled every data point. I think this agrees with my statistical intuition. You can achieve $|x^{\text{opt}} - x_k| < \epsilon$ at iteration $k$ before you necessarily sample all the points in your dataset, because your tolerance for error $\epsilon$ really determines how much data you need to look at, i.e. how many iterations of SGD you need to complete. I found the first part of the paper by (Bottou et al., 2017) quite helpful for understanding SGD better. References Bottou, Léon, Frank E. Curtis, and Jorge Nocedal. "Optimization methods for large-scale machine learning." arXiv preprint arXiv:1606.04838 (2016). https://arxiv.org/pdf/1606.04838.pdf Li, Mu, et al. "Efficient mini-batch training for stochastic optimization." Proceedings of the 20th ACM SIGKDD international conference on Knowledge discovery and data mining. ACM, 2014. https://www.cs.cmu.edu/~muli/file/minibatch_sgd.pdf
Convergence of Stochastic Gradient Descent as a function of training set size In the first part they are talking about large-scale SGD convergence in practice and in the second part theoretical results on the convergence of SGD when the optimisation problem is convex. "The nu
28,684
Convergence of Stochastic Gradient Descent as a function of training set size
In SGD you use mini-batches of fixed size, let's call it $d$. So if you have for example: $m=1024$ and $d=8$, you need 128 updates to go thru the whole training set. If you increase the training set size to $m=2048$, you will need 256 updates. This means that the number of updates increased. Another thing is, that if there is more data, then you need more time to converge (because model has to learn more). Hopefully you should also converge to a better point. So the authors want to say that more time in this case means more updates (as contrary to GD, where the number of updates stays the same, but they are longer). It just says that adding data to train set will not infinitively increase your model performance. In practice it means that if your training set is very big, performance of your model is rather limited by the model itself, not by the size of your training set.
Convergence of Stochastic Gradient Descent as a function of training set size
In SGD you use mini-batches of fixed size, let's call it $d$. So if you have for example: $m=1024$ and $d=8$, you need 128 updates to go thru the whole training set. If you increase the training set s
Convergence of Stochastic Gradient Descent as a function of training set size In SGD you use mini-batches of fixed size, let's call it $d$. So if you have for example: $m=1024$ and $d=8$, you need 128 updates to go thru the whole training set. If you increase the training set size to $m=2048$, you will need 256 updates. This means that the number of updates increased. Another thing is, that if there is more data, then you need more time to converge (because model has to learn more). Hopefully you should also converge to a better point. So the authors want to say that more time in this case means more updates (as contrary to GD, where the number of updates stays the same, but they are longer). It just says that adding data to train set will not infinitively increase your model performance. In practice it means that if your training set is very big, performance of your model is rather limited by the model itself, not by the size of your training set.
Convergence of Stochastic Gradient Descent as a function of training set size In SGD you use mini-batches of fixed size, let's call it $d$. So if you have for example: $m=1024$ and $d=8$, you need 128 updates to go thru the whole training set. If you increase the training set s
28,685
Convergence of Stochastic Gradient Descent as a function of training set size
The fact that as $m\to\infty$, the number of iterations $N$ needed for a deterministic optimization algorithm to reach the same loss value increases, is quite intuitive. Remember that Goodfellow et al. argument is made For a fixed model size[..] This means that you're increasing $m$, but the number of weights $n_w$ stays the same. It's clear that using a model of fixed complexity, it becomes increasingly harder to fit a larger training set. The second point, i.e., the fact that instead $N$ for SGD reaches a maximum and then plateaus, can be understood in the following way. As $m$ grows indefinitely but the model stays the same, you'll reach a point where $m$ is sufficienty larger than the model capacity (let’s say, once $m$ is enough larger than the VC dimension of the model). At this point we don’t even need to examine all the training set examples, before the model has reached its minimum test set error, because the model isn’t able to overfit the training set anyway. Showing the model more random examples from the training set (which is what SGD does) will only make the training set error and the test set error oscillate around a minimum value, but neither of them will decrease significantly.
Convergence of Stochastic Gradient Descent as a function of training set size
The fact that as $m\to\infty$, the number of iterations $N$ needed for a deterministic optimization algorithm to reach the same loss value increases, is quite intuitive. Remember that Goodfellow et al
Convergence of Stochastic Gradient Descent as a function of training set size The fact that as $m\to\infty$, the number of iterations $N$ needed for a deterministic optimization algorithm to reach the same loss value increases, is quite intuitive. Remember that Goodfellow et al. argument is made For a fixed model size[..] This means that you're increasing $m$, but the number of weights $n_w$ stays the same. It's clear that using a model of fixed complexity, it becomes increasingly harder to fit a larger training set. The second point, i.e., the fact that instead $N$ for SGD reaches a maximum and then plateaus, can be understood in the following way. As $m$ grows indefinitely but the model stays the same, you'll reach a point where $m$ is sufficienty larger than the model capacity (let’s say, once $m$ is enough larger than the VC dimension of the model). At this point we don’t even need to examine all the training set examples, before the model has reached its minimum test set error, because the model isn’t able to overfit the training set anyway. Showing the model more random examples from the training set (which is what SGD does) will only make the training set error and the test set error oscillate around a minimum value, but neither of them will decrease significantly.
Convergence of Stochastic Gradient Descent as a function of training set size The fact that as $m\to\infty$, the number of iterations $N$ needed for a deterministic optimization algorithm to reach the same loss value increases, is quite intuitive. Remember that Goodfellow et al
28,686
Convergence of Stochastic Gradient Descent as a function of training set size
What I think it means is that the number of GD iterations required does not grow linearly with $m$. Imagine you are trying to estimate some $\theta$ parameter, with only one data vector $x$: You start with a guess, then have a better estimation based on $x_1$. next, you have even better estimation, based on $x_1$ and $x_2$. The more observations you have, the closer you get to the target. As you have more and more observations, the weight of each observation is getting smaller and thus the relative impact of each additional observation shrinks. Assuming you have no outliers (wait a sec with this), you either converge to target or get to tiny fluctuations within a number of steps which is almost constant. If you do have outliers then a surge would be observed but afterwards you'll go back to converging towards target (each outlier would require an amount of additional steps to cover for). That's as far as I can go with intuition, based on both the model and my experience with it. However, I can't provide you with sources.
Convergence of Stochastic Gradient Descent as a function of training set size
What I think it means is that the number of GD iterations required does not grow linearly with $m$. Imagine you are trying to estimate some $\theta$ parameter, with only one data vector $x$: You start
Convergence of Stochastic Gradient Descent as a function of training set size What I think it means is that the number of GD iterations required does not grow linearly with $m$. Imagine you are trying to estimate some $\theta$ parameter, with only one data vector $x$: You start with a guess, then have a better estimation based on $x_1$. next, you have even better estimation, based on $x_1$ and $x_2$. The more observations you have, the closer you get to the target. As you have more and more observations, the weight of each observation is getting smaller and thus the relative impact of each additional observation shrinks. Assuming you have no outliers (wait a sec with this), you either converge to target or get to tiny fluctuations within a number of steps which is almost constant. If you do have outliers then a surge would be observed but afterwards you'll go back to converging towards target (each outlier would require an amount of additional steps to cover for). That's as far as I can go with intuition, based on both the model and my experience with it. However, I can't provide you with sources.
Convergence of Stochastic Gradient Descent as a function of training set size What I think it means is that the number of GD iterations required does not grow linearly with $m$. Imagine you are trying to estimate some $\theta$ parameter, with only one data vector $x$: You start
28,687
Convergence of Stochastic Gradient Descent as a function of training set size
A larger training set almost inevitably implies greater variability of examples. Thus, pulling random batches during training will yield, on average, a higher entropy (across batches, not within). And so, the function you try to approximate gets more complex and you need to train longer in order to converge. Imagine, you want to solve a standard classification problem such as recognizing animals from images. Let's say you dataset comprises $10^9$ images and imagine this set of images $1cm$ high stack. The amount of discernibly different images is in the range of $10^{40}$ with the stack being $9.98 \times 10^{25} km$, which extends the diameter of the universe which is around $8.85 \times 10^{23} km$. (I saw this calculation at ICCV 2017; for details see slide no. 3 here). Now, imagine you train on this vast dataset ($m:=10^{40}$). Even if it would be computationally feasible, at some point it would not further help you to classify your animal images correctly. That means, while training you would realize that after having seen only $n<m$ samples your algorithm does not further improve and since $n\ll m$, you can validly argue that asymptotic training cost is in $\mathcal{O}(1)$
Convergence of Stochastic Gradient Descent as a function of training set size
A larger training set almost inevitably implies greater variability of examples. Thus, pulling random batches during training will yield, on average, a higher entropy (across batches, not within). And
Convergence of Stochastic Gradient Descent as a function of training set size A larger training set almost inevitably implies greater variability of examples. Thus, pulling random batches during training will yield, on average, a higher entropy (across batches, not within). And so, the function you try to approximate gets more complex and you need to train longer in order to converge. Imagine, you want to solve a standard classification problem such as recognizing animals from images. Let's say you dataset comprises $10^9$ images and imagine this set of images $1cm$ high stack. The amount of discernibly different images is in the range of $10^{40}$ with the stack being $9.98 \times 10^{25} km$, which extends the diameter of the universe which is around $8.85 \times 10^{23} km$. (I saw this calculation at ICCV 2017; for details see slide no. 3 here). Now, imagine you train on this vast dataset ($m:=10^{40}$). Even if it would be computationally feasible, at some point it would not further help you to classify your animal images correctly. That means, while training you would realize that after having seen only $n<m$ samples your algorithm does not further improve and since $n\ll m$, you can validly argue that asymptotic training cost is in $\mathcal{O}(1)$
Convergence of Stochastic Gradient Descent as a function of training set size A larger training set almost inevitably implies greater variability of examples. Thus, pulling random batches during training will yield, on average, a higher entropy (across batches, not within). And
28,688
Convergence of Stochastic Gradient Descent as a function of training set size
I think for this question, you need to understand the definition of convergence. Generally, the convergence defined by the number of steps required to reach a certain threshold (e.g., the norm of gradient). SGD will go through the dataset once, as the dataset size increase, the solution will become more accurate. Once reaching a certain point, more data will not help too much because of the convergence property of SGD. There is also another issue regarding this optimization problem, SGD only cares about error bound of samples, but we actually care about the generalization capability. So two problems are not equivalent.
Convergence of Stochastic Gradient Descent as a function of training set size
I think for this question, you need to understand the definition of convergence. Generally, the convergence defined by the number of steps required to reach a certain threshold (e.g., the norm of grad
Convergence of Stochastic Gradient Descent as a function of training set size I think for this question, you need to understand the definition of convergence. Generally, the convergence defined by the number of steps required to reach a certain threshold (e.g., the norm of gradient). SGD will go through the dataset once, as the dataset size increase, the solution will become more accurate. Once reaching a certain point, more data will not help too much because of the convergence property of SGD. There is also another issue regarding this optimization problem, SGD only cares about error bound of samples, but we actually care about the generalization capability. So two problems are not equivalent.
Convergence of Stochastic Gradient Descent as a function of training set size I think for this question, you need to understand the definition of convergence. Generally, the convergence defined by the number of steps required to reach a certain threshold (e.g., the norm of grad
28,689
Understanding the Typical Set for Markov chain Monte Carlo sampling
$\mathrm{d}q$ is uniform across the entire space and that's the problem! Unfortunately as we consider higher-dimensional spaces out intuition of uniform starts failing us and we end up in conceptual difficulties like this. Yes, the volume of the neighborhood around any given point remains the same size as we increase the dimensionality of our space. But as we do so we also add many more points to the space, and hence many more points and corresponding neighborhoods. It's not that the volume around our chosen point is shrinking in any absolute sense, it's rather the the volume is shrinking relative to the volume of the rest of the space. If we consider radial shells around any point we see that volume increases exponentially fast (the exponent being $N - 1$, or $2 - 1 = 1$ in your $2$-dimensional example) as we move further away from that point. The growth of volume away from a point is the same no matter which point we take! The symmetry of this behavior is broken only when we consider the particular density representation of our probability distribution. The mode of the density identifies a special point in space around which the density is the largest. Then in order to understand how the typical set behaves we have to consider how volume behaves around this one, special point. We don't alway take $r = 0$ -- it just happens that $r = 0$ is the mode of an independently identically distributed unit Gaussian that we usually use to demonstrate the phenomenon.
Understanding the Typical Set for Markov chain Monte Carlo sampling
$\mathrm{d}q$ is uniform across the entire space and that's the problem! Unfortunately as we consider higher-dimensional spaces out intuition of uniform starts failing us and we end up in conceptual
Understanding the Typical Set for Markov chain Monte Carlo sampling $\mathrm{d}q$ is uniform across the entire space and that's the problem! Unfortunately as we consider higher-dimensional spaces out intuition of uniform starts failing us and we end up in conceptual difficulties like this. Yes, the volume of the neighborhood around any given point remains the same size as we increase the dimensionality of our space. But as we do so we also add many more points to the space, and hence many more points and corresponding neighborhoods. It's not that the volume around our chosen point is shrinking in any absolute sense, it's rather the the volume is shrinking relative to the volume of the rest of the space. If we consider radial shells around any point we see that volume increases exponentially fast (the exponent being $N - 1$, or $2 - 1 = 1$ in your $2$-dimensional example) as we move further away from that point. The growth of volume away from a point is the same no matter which point we take! The symmetry of this behavior is broken only when we consider the particular density representation of our probability distribution. The mode of the density identifies a special point in space around which the density is the largest. Then in order to understand how the typical set behaves we have to consider how volume behaves around this one, special point. We don't alway take $r = 0$ -- it just happens that $r = 0$ is the mode of an independently identically distributed unit Gaussian that we usually use to demonstrate the phenomenon.
Understanding the Typical Set for Markov chain Monte Carlo sampling $\mathrm{d}q$ is uniform across the entire space and that's the problem! Unfortunately as we consider higher-dimensional spaces out intuition of uniform starts failing us and we end up in conceptual
28,690
Detecting manipulation (e.g, photo copy-pasting) in images
In general, it's hard to detect tampering and it's a whole field of research in digital image forensics. I'll try to summarise some of the key approaches to this problem. What you're talking about is sometimes called image forgery or image tampering. And the copy-paste operation is called image composition or image splicing. From a practical perspective there are number of different variants to this problem: add something to the image (source) removing something from the image (source) changing global properties of the image (source) using one image vs. multiple images e.g. this use of the clone tool: (source) detecting whether if an image has been tampered vs. localising the tampering determining the type of tampering How you solve the problem is going to be very different depending on whether you are involved in a reviewing video surveillance footage, examining a single photo at a court case or running a photo sharing site. The problem is substantially harder if the problem is adversarial and the image manipulation may have been hidden. Another point is that there is a lot of legitimate postprocessing that happens in images. To take an extreme example new digital camera introduce bokeh and blurring effects even though this is not present in the finished image. So if you are interested in detecting more general types of image manipulation beyond image splicing it's helpful to be aware of what's happening in cameras and apps. A digital image is acquired on a camera as follows: scene $\rightarrow$ imaging sensor $\rightarrow$ on camera postprocessing $\rightarrow$ storage where the scene is the external geometry of the image the image sensor is a CCD or CMOS photodetector which converts light into electrical charge postprocessing is where the camera is where the electrical charge is converted into a digital signal and several corrective steps are taken to account for camera geometry, colour correction, etc. storage of is where the finished image written to memory. Often it's converted into a compressed format such as JPEG and stored along with relevant metadata. By considering the acquisition process you can see several possible points where tampering will result in inconsistencies in the image: physical scene geometry sensor and acquisition noise postprocessing and compression artifacts metadata Metadata. An obvious thing to look at is the metadata associated with the image, often it can have camera information, time information and possibly location information. All of these can possible identify inconsistency. If you have the statue of Liberty in your image but the GPS coordinates say you are at McMurdo Station in Antartica then the image is probably a forgery. But the metadata is itself easy altered or stripped so this is not reliable. Sensor noise. Sensor noise can be quite distinctive for digital camera, so much so that it can used to fingerprint the sensors in different camera models. There are several distinct types of noise introduced by sensors in digital cameras, but a very useful kind is photo-response nonuniformity (PRNU). This is a fingerprint associated with sensor noise and postprocessing, and it is robust to several image processing transformations, including lossy compression such as downsampling. You can calculate the PRNU across blocks in the image, and introducing a new element from a different camera will introduce and inconsistency in the image. This seems to work pretty well, but it works best if you know the camera type. It's still possible to estimte PRNU from a single image. Color filter array interpolation should also be consistent across the image, and will be distrupted by splicing. Compression and processing artifacts. All image processing techniques will leave a trace on the image statistics. Digital images are very commonly compressed via JPEG which compresses things using the discrete cosine transform. This process leaves traces in the image statistics. One interesting technique is to detect JPEG ghosts, that is parts of an image which have been compressed twice via DCT. As you mention, I believe that downsampling will remove some of these artifacts although the downsampling itself will be detectable. Scene consistency. An image acquire from single source should have consistent perspective (vanishing points), and illumination. Moreover it's hard to fake these fake these with a composite image. I recommend looking through (Redi et al., 2011) for more details here. Finally, if you say "Okay I give up. There's too many possible method, I just want a detector" you can look at this recent ICCV paper where they train a detector to find where an image has been manipulated. This may give you some more insight into training a blackbox model. Bappy, Jawadul H., et al. "Exploiting Spatial Structure for Localizing Manipulated Image Regions." Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition. 2017. Datasets/Contests: Casia V1.0 and V2.0 (image splicing) http://forensics.idealtest.org/ coverage (copy-move manipulations) https://github.com/wenbihan/coverage Media Forensics Challenge 2018 (various manipulations, requires registration) https://www.nist.gov/itl/iad/mig/media-forensics-challenge-2018 IEEE IFS-TC Image Forensics Challenge Dataset. (website currently unavailable) Raise (raw, unprocessed images along with camera metadata) http://mmlab.science.unitn.it/RAISE/index.php Surveys: Redi, Judith A., Wiem Taktak, and Jean-Luc Dugelay. "Digital image forensics: a booklet for beginners." Multimedia Tools and Applications 51.1 (2011): 133-162. https://pdfs.semanticscholar.org/8e85/c7ad6cd0986225e63dc1b4264b3e084b3f9b.pdf Fridrich, Jessica. "Digital image forensics." IEEE Signal Processing Magazine 26.2 (2009). http://ws.binghamton.edu/fridrich/Research/full_paper_02.pdf Farid, Hany. Digital Image Forensics: lecture notes, exercises, and matlab code for a survey course in digital image and video forensics. http://www.cs.dartmouth.edu/farid/downloads/tutorials/digitalimageforensics.pdf Kirchner, Matthias. Notes on digital image forensics and counter-forensics. Diss. Dartmouth College, 2012. http://ws.binghamton.edu/kirchner/papers/image_forensics_and_counter_forensics.pdf Memon, Nasir. "Photo Forensics–There Is More to a Picture than Meets the Eye." International Workshop on Digital Watermarking. Springer, Berlin, Heidelberg, 2011. Mahdian, Babak, and Stanislav Saic. "A bibliography on blind methods for identifying image forgery." Signal Processing: Image Communication 25.6 (2010): 389-399. Image Tampering Detection and Localization (includes recent deep learning references) https://github.com/yannadani/image_tampering_detection_references
Detecting manipulation (e.g, photo copy-pasting) in images
In general, it's hard to detect tampering and it's a whole field of research in digital image forensics. I'll try to summarise some of the key approaches to this problem. What you're talking about is
Detecting manipulation (e.g, photo copy-pasting) in images In general, it's hard to detect tampering and it's a whole field of research in digital image forensics. I'll try to summarise some of the key approaches to this problem. What you're talking about is sometimes called image forgery or image tampering. And the copy-paste operation is called image composition or image splicing. From a practical perspective there are number of different variants to this problem: add something to the image (source) removing something from the image (source) changing global properties of the image (source) using one image vs. multiple images e.g. this use of the clone tool: (source) detecting whether if an image has been tampered vs. localising the tampering determining the type of tampering How you solve the problem is going to be very different depending on whether you are involved in a reviewing video surveillance footage, examining a single photo at a court case or running a photo sharing site. The problem is substantially harder if the problem is adversarial and the image manipulation may have been hidden. Another point is that there is a lot of legitimate postprocessing that happens in images. To take an extreme example new digital camera introduce bokeh and blurring effects even though this is not present in the finished image. So if you are interested in detecting more general types of image manipulation beyond image splicing it's helpful to be aware of what's happening in cameras and apps. A digital image is acquired on a camera as follows: scene $\rightarrow$ imaging sensor $\rightarrow$ on camera postprocessing $\rightarrow$ storage where the scene is the external geometry of the image the image sensor is a CCD or CMOS photodetector which converts light into electrical charge postprocessing is where the camera is where the electrical charge is converted into a digital signal and several corrective steps are taken to account for camera geometry, colour correction, etc. storage of is where the finished image written to memory. Often it's converted into a compressed format such as JPEG and stored along with relevant metadata. By considering the acquisition process you can see several possible points where tampering will result in inconsistencies in the image: physical scene geometry sensor and acquisition noise postprocessing and compression artifacts metadata Metadata. An obvious thing to look at is the metadata associated with the image, often it can have camera information, time information and possibly location information. All of these can possible identify inconsistency. If you have the statue of Liberty in your image but the GPS coordinates say you are at McMurdo Station in Antartica then the image is probably a forgery. But the metadata is itself easy altered or stripped so this is not reliable. Sensor noise. Sensor noise can be quite distinctive for digital camera, so much so that it can used to fingerprint the sensors in different camera models. There are several distinct types of noise introduced by sensors in digital cameras, but a very useful kind is photo-response nonuniformity (PRNU). This is a fingerprint associated with sensor noise and postprocessing, and it is robust to several image processing transformations, including lossy compression such as downsampling. You can calculate the PRNU across blocks in the image, and introducing a new element from a different camera will introduce and inconsistency in the image. This seems to work pretty well, but it works best if you know the camera type. It's still possible to estimte PRNU from a single image. Color filter array interpolation should also be consistent across the image, and will be distrupted by splicing. Compression and processing artifacts. All image processing techniques will leave a trace on the image statistics. Digital images are very commonly compressed via JPEG which compresses things using the discrete cosine transform. This process leaves traces in the image statistics. One interesting technique is to detect JPEG ghosts, that is parts of an image which have been compressed twice via DCT. As you mention, I believe that downsampling will remove some of these artifacts although the downsampling itself will be detectable. Scene consistency. An image acquire from single source should have consistent perspective (vanishing points), and illumination. Moreover it's hard to fake these fake these with a composite image. I recommend looking through (Redi et al., 2011) for more details here. Finally, if you say "Okay I give up. There's too many possible method, I just want a detector" you can look at this recent ICCV paper where they train a detector to find where an image has been manipulated. This may give you some more insight into training a blackbox model. Bappy, Jawadul H., et al. "Exploiting Spatial Structure for Localizing Manipulated Image Regions." Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition. 2017. Datasets/Contests: Casia V1.0 and V2.0 (image splicing) http://forensics.idealtest.org/ coverage (copy-move manipulations) https://github.com/wenbihan/coverage Media Forensics Challenge 2018 (various manipulations, requires registration) https://www.nist.gov/itl/iad/mig/media-forensics-challenge-2018 IEEE IFS-TC Image Forensics Challenge Dataset. (website currently unavailable) Raise (raw, unprocessed images along with camera metadata) http://mmlab.science.unitn.it/RAISE/index.php Surveys: Redi, Judith A., Wiem Taktak, and Jean-Luc Dugelay. "Digital image forensics: a booklet for beginners." Multimedia Tools and Applications 51.1 (2011): 133-162. https://pdfs.semanticscholar.org/8e85/c7ad6cd0986225e63dc1b4264b3e084b3f9b.pdf Fridrich, Jessica. "Digital image forensics." IEEE Signal Processing Magazine 26.2 (2009). http://ws.binghamton.edu/fridrich/Research/full_paper_02.pdf Farid, Hany. Digital Image Forensics: lecture notes, exercises, and matlab code for a survey course in digital image and video forensics. http://www.cs.dartmouth.edu/farid/downloads/tutorials/digitalimageforensics.pdf Kirchner, Matthias. Notes on digital image forensics and counter-forensics. Diss. Dartmouth College, 2012. http://ws.binghamton.edu/kirchner/papers/image_forensics_and_counter_forensics.pdf Memon, Nasir. "Photo Forensics–There Is More to a Picture than Meets the Eye." International Workshop on Digital Watermarking. Springer, Berlin, Heidelberg, 2011. Mahdian, Babak, and Stanislav Saic. "A bibliography on blind methods for identifying image forgery." Signal Processing: Image Communication 25.6 (2010): 389-399. Image Tampering Detection and Localization (includes recent deep learning references) https://github.com/yannadani/image_tampering_detection_references
Detecting manipulation (e.g, photo copy-pasting) in images In general, it's hard to detect tampering and it's a whole field of research in digital image forensics. I'll try to summarise some of the key approaches to this problem. What you're talking about is
28,691
Showing $\frac{2X}{1-X^2}$ is standard Cauchy when $X$ is standard Cauchy
An alternative, more simplistic, way to look at it: standard Cauchy distribution: $$f(x) \text{d}x = \frac{\pi^{-1}}{x^2+1} \text{d}x $$ transformations of variables: $$ u(x) = \frac{2x}{1-x^2} \qquad \text{and} \qquad x_1(u) = \frac{-1 - \sqrt{u^2+1}}{u} \, , \, x_2(u) = \frac{-1 + \sqrt{u^2+1}}{u} $$ transformation of distribution: $$g(u)\text{d}u = \sum_{i=1,2} f(x_i(u)) \left|\frac{\text{d}x_i}{\text{d}u}\right|\text{d}u $$ If you work with that, which does not need to become so messy, then you will get $$g(u) = \frac{\pi^{-1}}{u^2+1}$$ graphical representation This sort of works like the identity $\frac{2\tan z}{1-\tan^2z}=\tan 2z$, but written more explicitly. Or like your representation with the split cumulative distribution function $F_Y(y) = Pr(Y \leq y)$ but now for a split in $f_Y(y) = Pr(y-\frac{1}{2}dy \leq Y\leq y+\frac{1}{2}dy)$.
Showing $\frac{2X}{1-X^2}$ is standard Cauchy when $X$ is standard Cauchy
An alternative, more simplistic, way to look at it: standard Cauchy distribution: $$f(x) \text{d}x = \frac{\pi^{-1}}{x^2+1} \text{d}x $$ transformations of variables: $$ u(x) = \frac{2x}{1-x^2} \qquad
Showing $\frac{2X}{1-X^2}$ is standard Cauchy when $X$ is standard Cauchy An alternative, more simplistic, way to look at it: standard Cauchy distribution: $$f(x) \text{d}x = \frac{\pi^{-1}}{x^2+1} \text{d}x $$ transformations of variables: $$ u(x) = \frac{2x}{1-x^2} \qquad \text{and} \qquad x_1(u) = \frac{-1 - \sqrt{u^2+1}}{u} \, , \, x_2(u) = \frac{-1 + \sqrt{u^2+1}}{u} $$ transformation of distribution: $$g(u)\text{d}u = \sum_{i=1,2} f(x_i(u)) \left|\frac{\text{d}x_i}{\text{d}u}\right|\text{d}u $$ If you work with that, which does not need to become so messy, then you will get $$g(u) = \frac{\pi^{-1}}{u^2+1}$$ graphical representation This sort of works like the identity $\frac{2\tan z}{1-\tan^2z}=\tan 2z$, but written more explicitly. Or like your representation with the split cumulative distribution function $F_Y(y) = Pr(Y \leq y)$ but now for a split in $f_Y(y) = Pr(y-\frac{1}{2}dy \leq Y\leq y+\frac{1}{2}dy)$.
Showing $\frac{2X}{1-X^2}$ is standard Cauchy when $X$ is standard Cauchy An alternative, more simplistic, way to look at it: standard Cauchy distribution: $$f(x) \text{d}x = \frac{\pi^{-1}}{x^2+1} \text{d}x $$ transformations of variables: $$ u(x) = \frac{2x}{1-x^2} \qquad
28,692
Showing $\frac{2X}{1-X^2}$ is standard Cauchy when $X$ is standard Cauchy
The transformation in the second approach seems lack of motivation (some details in that also need to be filled up with). Here, from the characteristic function calculation, I am trying to back up your "mysterious" transformation. The characteristic function of $Y$ can be calculated as follows: \begin{align} \varphi_Y(t) = & E[e^{itY}] = \int_{-\infty}^{\infty} e^{it\frac{2x}{1 - x^2}} \frac{1}{\pi(1 + x^2)} dx \\ = & \frac{1}{\pi}\int_{-\infty}^\infty e^{it\frac{2x}{1 - x^2}} d\arctan x, \end{align} which suggests us trying the transformation $u = \arctan x$, which leads to \begin{align} \varphi_Y(t)= \frac{1}{\pi}\int_{-\pi/2}^{\pi/2} e^{it\frac{2\tan u}{1 - \tan^2 u}} du = \frac{1}{\pi}\int_{-\pi/2}^{\pi/2}e^{it\tan(2u)}du. \tag{1} \end{align} Our goal is to show that the integral in $(1)$ equals to the characteristic function of a standard Cauchy random variable $X$: \begin{align} \varphi_X(t) = & \int_{-\infty}^\infty e^{itx}\frac{1}{\pi(1 + x^2)} dx \\ = & \frac{1}{\pi}\int_{-\pi/2}^{\pi/2} e^{it\tan u} du \tag{2} \end{align} Why does the integral in $(1)$ equal to the integral in $(2)$? At the first glance, this is a little counter-intuitive. To verify it, we need to treat the monotonicity of the function $\tan(\cdot)$ carefully. Let's continue to work on $(1)$: \begin{align} \varphi_Y(t) = & \frac{1}{\pi}\int_{-\pi/2}^{\pi/2}e^{it\tan(2u)}du \\ = & \frac{1}{2\pi}\int_{-\pi}^\pi e^{it\tan v} dv \quad (\text{Change of variable } v = 2u) \\ = & \frac{1}{2\pi}\left[\int_{-\pi}^{-\pi/2} + \int_{-\pi/2}^{\pi/2} + \int_{\pi/2}^{\pi}\right]e^{it\tan u} du \\ = & \frac{1}{2}\varphi_X(t) + \frac{1}{2\pi}\int_{-\pi}^{-\pi/2}e^{it\tan v} dv + \frac{1}{2\pi}\int_{\pi/2}^{\pi}e^{it\tan v} dv \quad (3) \\ = & \frac{1}{2}\varphi_X(t) + \frac{1}{2\pi}\int_{-\pi/2}^{0} e^{-it\tan u_1} du_1 + \frac{1}{2\pi}\int_{0}^{\pi/2} e^{-it\tan u_2} du_2 \quad (4) \\ = & \frac{1}{2}\varphi_X(t) + \frac{1}{2\pi}\int_{-\pi/2}^{\pi/2} e^{-it\tan v} dv \\ = & \varphi_X(t) \quad (5) \end{align} $(3)$: Because the function $u \mapsto \tan(u)$ is not monotone on the interval $(-\pi, \pi)$, I made such division such that each integrand is monotone on the separated interval (which ensures subsequent change of variable formulae valid). $(4)$: The two change of variable formulae are $u_1 = -\pi - v$ and $u_2 = \pi - v$. $(5)$: Last change of variable formula $u = -v$. The steps $(3)$--$(5)$ elaborated the statement "the last one being a 2-to-1 transformation" in OP's question.
Showing $\frac{2X}{1-X^2}$ is standard Cauchy when $X$ is standard Cauchy
The transformation in the second approach seems lack of motivation (some details in that also need to be filled up with). Here, from the characteristic function calculation, I am trying to back up you
Showing $\frac{2X}{1-X^2}$ is standard Cauchy when $X$ is standard Cauchy The transformation in the second approach seems lack of motivation (some details in that also need to be filled up with). Here, from the characteristic function calculation, I am trying to back up your "mysterious" transformation. The characteristic function of $Y$ can be calculated as follows: \begin{align} \varphi_Y(t) = & E[e^{itY}] = \int_{-\infty}^{\infty} e^{it\frac{2x}{1 - x^2}} \frac{1}{\pi(1 + x^2)} dx \\ = & \frac{1}{\pi}\int_{-\infty}^\infty e^{it\frac{2x}{1 - x^2}} d\arctan x, \end{align} which suggests us trying the transformation $u = \arctan x$, which leads to \begin{align} \varphi_Y(t)= \frac{1}{\pi}\int_{-\pi/2}^{\pi/2} e^{it\frac{2\tan u}{1 - \tan^2 u}} du = \frac{1}{\pi}\int_{-\pi/2}^{\pi/2}e^{it\tan(2u)}du. \tag{1} \end{align} Our goal is to show that the integral in $(1)$ equals to the characteristic function of a standard Cauchy random variable $X$: \begin{align} \varphi_X(t) = & \int_{-\infty}^\infty e^{itx}\frac{1}{\pi(1 + x^2)} dx \\ = & \frac{1}{\pi}\int_{-\pi/2}^{\pi/2} e^{it\tan u} du \tag{2} \end{align} Why does the integral in $(1)$ equal to the integral in $(2)$? At the first glance, this is a little counter-intuitive. To verify it, we need to treat the monotonicity of the function $\tan(\cdot)$ carefully. Let's continue to work on $(1)$: \begin{align} \varphi_Y(t) = & \frac{1}{\pi}\int_{-\pi/2}^{\pi/2}e^{it\tan(2u)}du \\ = & \frac{1}{2\pi}\int_{-\pi}^\pi e^{it\tan v} dv \quad (\text{Change of variable } v = 2u) \\ = & \frac{1}{2\pi}\left[\int_{-\pi}^{-\pi/2} + \int_{-\pi/2}^{\pi/2} + \int_{\pi/2}^{\pi}\right]e^{it\tan u} du \\ = & \frac{1}{2}\varphi_X(t) + \frac{1}{2\pi}\int_{-\pi}^{-\pi/2}e^{it\tan v} dv + \frac{1}{2\pi}\int_{\pi/2}^{\pi}e^{it\tan v} dv \quad (3) \\ = & \frac{1}{2}\varphi_X(t) + \frac{1}{2\pi}\int_{-\pi/2}^{0} e^{-it\tan u_1} du_1 + \frac{1}{2\pi}\int_{0}^{\pi/2} e^{-it\tan u_2} du_2 \quad (4) \\ = & \frac{1}{2}\varphi_X(t) + \frac{1}{2\pi}\int_{-\pi/2}^{\pi/2} e^{-it\tan v} dv \\ = & \varphi_X(t) \quad (5) \end{align} $(3)$: Because the function $u \mapsto \tan(u)$ is not monotone on the interval $(-\pi, \pi)$, I made such division such that each integrand is monotone on the separated interval (which ensures subsequent change of variable formulae valid). $(4)$: The two change of variable formulae are $u_1 = -\pi - v$ and $u_2 = \pi - v$. $(5)$: Last change of variable formula $u = -v$. The steps $(3)$--$(5)$ elaborated the statement "the last one being a 2-to-1 transformation" in OP's question.
Showing $\frac{2X}{1-X^2}$ is standard Cauchy when $X$ is standard Cauchy The transformation in the second approach seems lack of motivation (some details in that also need to be filled up with). Here, from the characteristic function calculation, I am trying to back up you
28,693
Training LSTM with and without resetting states
Yes, you are right. In both cases, the model is trained for 10 epochs. During each epoch, all examples in your training data flow through the network. The batch size determines the number of examples after which the weights or parameters of the model are updated. The difference between the first and the second case is that the first one allows you to perform some processing outside the fit() method between the epochs, such as model.reset_states(). However, similar processing can also be applied to the second case within the fit() method via custom callbacks class, which include, for example, on_epoch_begin, on_epoch_end, on_batch_begin and on_batch_end functions. Regarding the problem of getting quite different results with the two cases when model.reset_states() is removed from the first one: it shouldn't happen. You will get different results from each case if you reset the states of the model between the epochs in one case but not in the other. The results (loss after a certain number of epochs) will be the same if you don't reset the states in either case between the epochs, initialize a pseudorandom number generator before importing Keras and restart the Python interpreter between running the two cases. I validated this with the following example, where the objective is to learn a pure sine wave from a noisy one. The following code snippet has been implemented with Python 3.5, NumPy 1.12.1, Keras 2.0.4 and Matplotlib 2.0.2.: import numpy as np # Needed for reproducible results np.random.seed(1) from keras.models import Sequential from keras.layers import LSTM, Dense # Generate example data # ----------------------------------------------------------------------------- x_train = y_train = [np.sin(i) for i in np.arange(start=0, stop=10, step=0.01)] noise = np.random.normal(loc=0, scale=0.1, size=len(x_train)) x_train += noise n_examples = len(x_train) n_features = 1 n_outputs = 1 time_steps = 1 x_train = np.reshape(x_train, (n_examples, time_steps, n_features)) y_train = np.reshape(y_train, (n_examples, n_outputs)) # Initialize LSTM # ----------------------------------------------------------------------------- batch_size = 100 model = Sequential() model.add(LSTM(units=10, input_shape=(time_steps, n_features), return_sequences=True, stateful=True, batch_size=batch_size)) model.add(LSTM(units=10, return_sequences=False, stateful=True)) model.add(Dense(units=n_outputs, activation='linear')) model.compile(loss='mse', optimizer='adadelta') # Train LSTM # ----------------------------------------------------------------------------- epochs = 70 # Case 1 for i in range(epochs): model.fit(x_train, y_train, epochs=1, batch_size=batch_size, verbose=2, shuffle=False) # !!! To get exactly the same results between the cases, do the following: # !!! * To record the loss of the 1st case, run all the code until here. # !!! * To record the loss of the 2nd case, # !!! restart Python, comment out the 1st case and run all the code. # Case 2 model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, verbose=2, shuffle=False) As an extra, here is a visualization of the results of either case where states weren't reset: import matplotlib.pyplot as plt plt.style.use('ggplot') ax = plt.figure(figsize=(10, 6)).add_subplot(111) ax.plot(x_train[:, 0], label='x_train', color='#111111', alpha=0.8, lw=3) ax.plot(y_train[:, 0], label='y_train', color='#E69F00', alpha=1, lw=3) ax.plot(model.predict(x_train, batch_size=batch_size)[:, 0], label='Predictions for x_train after %i epochs' % epochs, color='#56B4E9', alpha=0.8, lw=3) plt.legend(loc='lower right') On the Keras website, the statefulness of RNNs is discussed in recurrent layers documentation and in FAQ. Edit: The above solution currently works with Theano backend but not with TensorFlow backend.
Training LSTM with and without resetting states
Yes, you are right. In both cases, the model is trained for 10 epochs. During each epoch, all examples in your training data flow through the network. The batch size determines the number of examples
Training LSTM with and without resetting states Yes, you are right. In both cases, the model is trained for 10 epochs. During each epoch, all examples in your training data flow through the network. The batch size determines the number of examples after which the weights or parameters of the model are updated. The difference between the first and the second case is that the first one allows you to perform some processing outside the fit() method between the epochs, such as model.reset_states(). However, similar processing can also be applied to the second case within the fit() method via custom callbacks class, which include, for example, on_epoch_begin, on_epoch_end, on_batch_begin and on_batch_end functions. Regarding the problem of getting quite different results with the two cases when model.reset_states() is removed from the first one: it shouldn't happen. You will get different results from each case if you reset the states of the model between the epochs in one case but not in the other. The results (loss after a certain number of epochs) will be the same if you don't reset the states in either case between the epochs, initialize a pseudorandom number generator before importing Keras and restart the Python interpreter between running the two cases. I validated this with the following example, where the objective is to learn a pure sine wave from a noisy one. The following code snippet has been implemented with Python 3.5, NumPy 1.12.1, Keras 2.0.4 and Matplotlib 2.0.2.: import numpy as np # Needed for reproducible results np.random.seed(1) from keras.models import Sequential from keras.layers import LSTM, Dense # Generate example data # ----------------------------------------------------------------------------- x_train = y_train = [np.sin(i) for i in np.arange(start=0, stop=10, step=0.01)] noise = np.random.normal(loc=0, scale=0.1, size=len(x_train)) x_train += noise n_examples = len(x_train) n_features = 1 n_outputs = 1 time_steps = 1 x_train = np.reshape(x_train, (n_examples, time_steps, n_features)) y_train = np.reshape(y_train, (n_examples, n_outputs)) # Initialize LSTM # ----------------------------------------------------------------------------- batch_size = 100 model = Sequential() model.add(LSTM(units=10, input_shape=(time_steps, n_features), return_sequences=True, stateful=True, batch_size=batch_size)) model.add(LSTM(units=10, return_sequences=False, stateful=True)) model.add(Dense(units=n_outputs, activation='linear')) model.compile(loss='mse', optimizer='adadelta') # Train LSTM # ----------------------------------------------------------------------------- epochs = 70 # Case 1 for i in range(epochs): model.fit(x_train, y_train, epochs=1, batch_size=batch_size, verbose=2, shuffle=False) # !!! To get exactly the same results between the cases, do the following: # !!! * To record the loss of the 1st case, run all the code until here. # !!! * To record the loss of the 2nd case, # !!! restart Python, comment out the 1st case and run all the code. # Case 2 model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, verbose=2, shuffle=False) As an extra, here is a visualization of the results of either case where states weren't reset: import matplotlib.pyplot as plt plt.style.use('ggplot') ax = plt.figure(figsize=(10, 6)).add_subplot(111) ax.plot(x_train[:, 0], label='x_train', color='#111111', alpha=0.8, lw=3) ax.plot(y_train[:, 0], label='y_train', color='#E69F00', alpha=1, lw=3) ax.plot(model.predict(x_train, batch_size=batch_size)[:, 0], label='Predictions for x_train after %i epochs' % epochs, color='#56B4E9', alpha=0.8, lw=3) plt.legend(loc='lower right') On the Keras website, the statefulness of RNNs is discussed in recurrent layers documentation and in FAQ. Edit: The above solution currently works with Theano backend but not with TensorFlow backend.
Training LSTM with and without resetting states Yes, you are right. In both cases, the model is trained for 10 epochs. During each epoch, all examples in your training data flow through the network. The batch size determines the number of examples
28,694
Finding the distribution of sum of Lognormal Random Variables
The sum of lognormal variables is not a commonly found "standard" distribution. There are various approximation methods in use, such as the Fenton-Wilkinson one. Different methods work better depending on whether you are mainly interested in high quantiles of the sum distribution, or the middle part. "Flexible lognormal sum approximation method" by Wu, Mehta & Zhang (2005, IEEE GLOBECOM proceedings) would be a good starting point.
Finding the distribution of sum of Lognormal Random Variables
The sum of lognormal variables is not a commonly found "standard" distribution. There are various approximation methods in use, such as the Fenton-Wilkinson one. Different methods work better dependin
Finding the distribution of sum of Lognormal Random Variables The sum of lognormal variables is not a commonly found "standard" distribution. There are various approximation methods in use, such as the Fenton-Wilkinson one. Different methods work better depending on whether you are mainly interested in high quantiles of the sum distribution, or the middle part. "Flexible lognormal sum approximation method" by Wu, Mehta & Zhang (2005, IEEE GLOBECOM proceedings) would be a good starting point.
Finding the distribution of sum of Lognormal Random Variables The sum of lognormal variables is not a commonly found "standard" distribution. There are various approximation methods in use, such as the Fenton-Wilkinson one. Different methods work better dependin
28,695
Why does sklearn.grid_search.GridSearchCV return random results on every execution?
You can avoid this by using any value for random_state parameter as mentioned in documentation: random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. example: try DecisionTreeClassifier(random_state=0) Explaination: This occurs because, you are not using a random_state variable while declaring decision_tree_classifier = DecisionTreeClassifier() . So, each time a different Decision Tree is generated because: Decision trees can be unstable because small variations in the data might result in a completely different tree being generated. This problem is mitigated by using decision trees within an ensemble. This is also mentioned in interface Documentation: The problem of learning an optimal decision tree is known to be NP-complete under several aspects of optimality and even for simple concepts. Consequently, practical decision-tree learning algorithms are based on heuristic algorithms such as the greedy algorithm where locally optimal decisions are made at each node. Such algorithms cannot guarantee to return the globally optimal decision tree. This can be mitigated by training multiple trees in an ensemble learner, where the features and samples are randomly sampled with replacement.
Why does sklearn.grid_search.GridSearchCV return random results on every execution?
You can avoid this by using any value for random_state parameter as mentioned in documentation: random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the
Why does sklearn.grid_search.GridSearchCV return random results on every execution? You can avoid this by using any value for random_state parameter as mentioned in documentation: random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. example: try DecisionTreeClassifier(random_state=0) Explaination: This occurs because, you are not using a random_state variable while declaring decision_tree_classifier = DecisionTreeClassifier() . So, each time a different Decision Tree is generated because: Decision trees can be unstable because small variations in the data might result in a completely different tree being generated. This problem is mitigated by using decision trees within an ensemble. This is also mentioned in interface Documentation: The problem of learning an optimal decision tree is known to be NP-complete under several aspects of optimality and even for simple concepts. Consequently, practical decision-tree learning algorithms are based on heuristic algorithms such as the greedy algorithm where locally optimal decisions are made at each node. Such algorithms cannot guarantee to return the globally optimal decision tree. This can be mitigated by training multiple trees in an ensemble learner, where the features and samples are randomly sampled with replacement.
Why does sklearn.grid_search.GridSearchCV return random results on every execution? You can avoid this by using any value for random_state parameter as mentioned in documentation: random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the
28,696
PCA with anomaly detection
PCA may be used to reduce your number of features, but it doesn't have to. You will have as many PC's as the number of original features, only that some of them will account for very few of the total variability. That can be visualized in a scree or pareto plot, where the accumulated variance reaches 100% with the last PC. Therefore, you should not be missing any information by using PCA. There is some discussion about this in [Do components of PCA really represent percentage of variance? Can they sum to more than 100%? But then, two contraditory points emerge here: 1) If no reduction in dimensionality is achieved when retaining all PCs, that is if you are care about all the anomalies present in your dataset, and your first goal was to have less features to work with (which will make you lose some information), why use PCA? 2) PCA is generally used when the interest is the "main modes of variability" of your dataset: the first couple of PC's, generally. Small anomalies, as I believe is the case of the ones you pointed out, are expexted to be ignored once only the main components are retained when you consider only the firts PC's for dimensionality reduction. Hope this helps. EDIT: The "size" or frequency of the anomalies of one feature are not important by themselves, but you should compare them to the the others in order to know wether they will disappear when you reduce dimensionality. Say, if the variability of this specific anomaly is (quasi-)orthogonal to the first PC's (the ones you use), then you will lose this information. If you are lucky that the mode of variability of the anomalies you are interested in is similar to the main modes of the variability of your entire dataset, then this iformation is kept in the first PC's. There is a nice discussion about this matter here: https://stats.stackexchange.com/a/235107/144543
PCA with anomaly detection
PCA may be used to reduce your number of features, but it doesn't have to. You will have as many PC's as the number of original features, only that some of them will account for very few of the total
PCA with anomaly detection PCA may be used to reduce your number of features, but it doesn't have to. You will have as many PC's as the number of original features, only that some of them will account for very few of the total variability. That can be visualized in a scree or pareto plot, where the accumulated variance reaches 100% with the last PC. Therefore, you should not be missing any information by using PCA. There is some discussion about this in [Do components of PCA really represent percentage of variance? Can they sum to more than 100%? But then, two contraditory points emerge here: 1) If no reduction in dimensionality is achieved when retaining all PCs, that is if you are care about all the anomalies present in your dataset, and your first goal was to have less features to work with (which will make you lose some information), why use PCA? 2) PCA is generally used when the interest is the "main modes of variability" of your dataset: the first couple of PC's, generally. Small anomalies, as I believe is the case of the ones you pointed out, are expexted to be ignored once only the main components are retained when you consider only the firts PC's for dimensionality reduction. Hope this helps. EDIT: The "size" or frequency of the anomalies of one feature are not important by themselves, but you should compare them to the the others in order to know wether they will disappear when you reduce dimensionality. Say, if the variability of this specific anomaly is (quasi-)orthogonal to the first PC's (the ones you use), then you will lose this information. If you are lucky that the mode of variability of the anomalies you are interested in is similar to the main modes of the variability of your entire dataset, then this iformation is kept in the first PC's. There is a nice discussion about this matter here: https://stats.stackexchange.com/a/235107/144543
PCA with anomaly detection PCA may be used to reduce your number of features, but it doesn't have to. You will have as many PC's as the number of original features, only that some of them will account for very few of the total
28,697
PCA with anomaly detection
You could implement robust PCA from this paper, which aims to decompose a given matrix into a sparse and a low rank part. The low rank part can be considered as the “robust principal components” while the sparse part can give you a clue on anomalies. I have used it on economic data, where it gave reasonable results.
PCA with anomaly detection
You could implement robust PCA from this paper, which aims to decompose a given matrix into a sparse and a low rank part. The low rank part can be considered as the “robust principal components” while
PCA with anomaly detection You could implement robust PCA from this paper, which aims to decompose a given matrix into a sparse and a low rank part. The low rank part can be considered as the “robust principal components” while the sparse part can give you a clue on anomalies. I have used it on economic data, where it gave reasonable results.
PCA with anomaly detection You could implement robust PCA from this paper, which aims to decompose a given matrix into a sparse and a low rank part. The low rank part can be considered as the “robust principal components” while
28,698
PCA with anomaly detection
I found the previous answer confusing so this is my attempt to explain it. I can see this question two ways: By anomaly here you appear to mean that a particular feature is consistently corrupted, and your question is therefore: "if I do PCA and take the components corresponding to 95% of my variance, will the corrupted feature be present in these components?" If so, the answer is "insufficient data for meaningful conclusion." PCA operates by looking at the empirical covariance of your data -- if the anomalous feature skews the empirical covariance sufficiently, then it will be present in the components you remove (assuming you mean standard PCA). So if the range of all your features is, say, [-0.1,0.1], you have few samples, and the anomaly is what you describe then it is going to heavily skew your PCA projection. Generally speaking, this is not a good idea at all. You might also be asking, "Some of my trials are anomalous, but only in a few dimensions. Does PCA for dimensionality reduction get rid of the anomaly?" to which the answer is "no." PCA, assuming it is applied to the data on which it is computed, looks at all dimensions and datapoints equally. If you are interested in outlier detection (which this would correspond to), and you know it is isolated to certain dimensions, your best bet is to simply run some sort of standard outlier detection procedure on each dimension independently.
PCA with anomaly detection
I found the previous answer confusing so this is my attempt to explain it. I can see this question two ways: By anomaly here you appear to mean that a particular feature is consistently corrupted, an
PCA with anomaly detection I found the previous answer confusing so this is my attempt to explain it. I can see this question two ways: By anomaly here you appear to mean that a particular feature is consistently corrupted, and your question is therefore: "if I do PCA and take the components corresponding to 95% of my variance, will the corrupted feature be present in these components?" If so, the answer is "insufficient data for meaningful conclusion." PCA operates by looking at the empirical covariance of your data -- if the anomalous feature skews the empirical covariance sufficiently, then it will be present in the components you remove (assuming you mean standard PCA). So if the range of all your features is, say, [-0.1,0.1], you have few samples, and the anomaly is what you describe then it is going to heavily skew your PCA projection. Generally speaking, this is not a good idea at all. You might also be asking, "Some of my trials are anomalous, but only in a few dimensions. Does PCA for dimensionality reduction get rid of the anomaly?" to which the answer is "no." PCA, assuming it is applied to the data on which it is computed, looks at all dimensions and datapoints equally. If you are interested in outlier detection (which this would correspond to), and you know it is isolated to certain dimensions, your best bet is to simply run some sort of standard outlier detection procedure on each dimension independently.
PCA with anomaly detection I found the previous answer confusing so this is my attempt to explain it. I can see this question two ways: By anomaly here you appear to mean that a particular feature is consistently corrupted, an
28,699
PCA with anomaly detection
PCA summarises the covariance structure of the training set data and will therefore reflect all variance present on that set.Will PCA detect all anomalous behaviour? No method will, but it has its strengths, but its biggest one is in pattern handling, and identifying unusual patterns which alas is not what you are describing. You appear to be talking about rare events confined to one variable, but there is still a lot PCA can do Two issues arise for outliers 1)in training/calibration. Are any samples presenting variance that is not well represented throughout the dataset? If only one sample presents a behaviour then your PCA model will not describe that behaviour reliably. Many methods exist to identify such issues, including Hotelling's $T^2$, distance to model, leverage, residuals (both of the latter 2 can be used sample or variable wise) . It is a hot topic, and no answer is universally applicable. To me if any variation is not well described the samples should be removed or the experiment redesigned as otherwise they create an unreliable element in your model that will behave unpredictably in new datasets as you have neither good understanding of its variance nor its covariance with everything else. 2) in the test /validation /application. All PCA models should build in sanity checks to determine if there are significant residual variation that the model does not explain in new data so that you can estimate how well the model describes the sample. If there is a lot of unexplained variance then you are extrapolating and should proceed with caution. . Our consideration is that the PCA will neglect this feature and when >we will reduce the number of columns after the PCA (say we take >95% of data) the anomaly will "disappear". Not if you use PCA correctly, if you look beyond your basic eigenvectors at the metrics mentioned above you would see any such behaviour. Where few samples or variable are anomalous and causing an outsize influence on the model these often are detectable in leverage , while residuals are good for ensuring the variation of specific samples or variables has been accounted for by your chosen number of PCs. If the problem is that you are looking at a rare event that you specifically want the model to handle, then the problem is whether you have powered your study sufficiently well to get a reliable estimate of its behaviour, not a problem with PCA itself. There are also things can be done with Design Of Experiment to ensure that maximal relevant variance is captured with an efficient dataset. Is using PCA for finding anomalies discouraged? or we are missing something? I would say that using PCA for finding anomalies should be encouraged, but the full range of tools need to be explored to look for different types of anomalies. Anomalies however may reflect a study design inadequate for the variation of interest.
PCA with anomaly detection
PCA summarises the covariance structure of the training set data and will therefore reflect all variance present on that set.Will PCA detect all anomalous behaviour? No method will, but it has its str
PCA with anomaly detection PCA summarises the covariance structure of the training set data and will therefore reflect all variance present on that set.Will PCA detect all anomalous behaviour? No method will, but it has its strengths, but its biggest one is in pattern handling, and identifying unusual patterns which alas is not what you are describing. You appear to be talking about rare events confined to one variable, but there is still a lot PCA can do Two issues arise for outliers 1)in training/calibration. Are any samples presenting variance that is not well represented throughout the dataset? If only one sample presents a behaviour then your PCA model will not describe that behaviour reliably. Many methods exist to identify such issues, including Hotelling's $T^2$, distance to model, leverage, residuals (both of the latter 2 can be used sample or variable wise) . It is a hot topic, and no answer is universally applicable. To me if any variation is not well described the samples should be removed or the experiment redesigned as otherwise they create an unreliable element in your model that will behave unpredictably in new datasets as you have neither good understanding of its variance nor its covariance with everything else. 2) in the test /validation /application. All PCA models should build in sanity checks to determine if there are significant residual variation that the model does not explain in new data so that you can estimate how well the model describes the sample. If there is a lot of unexplained variance then you are extrapolating and should proceed with caution. . Our consideration is that the PCA will neglect this feature and when >we will reduce the number of columns after the PCA (say we take >95% of data) the anomaly will "disappear". Not if you use PCA correctly, if you look beyond your basic eigenvectors at the metrics mentioned above you would see any such behaviour. Where few samples or variable are anomalous and causing an outsize influence on the model these often are detectable in leverage , while residuals are good for ensuring the variation of specific samples or variables has been accounted for by your chosen number of PCs. If the problem is that you are looking at a rare event that you specifically want the model to handle, then the problem is whether you have powered your study sufficiently well to get a reliable estimate of its behaviour, not a problem with PCA itself. There are also things can be done with Design Of Experiment to ensure that maximal relevant variance is captured with an efficient dataset. Is using PCA for finding anomalies discouraged? or we are missing something? I would say that using PCA for finding anomalies should be encouraged, but the full range of tools need to be explored to look for different types of anomalies. Anomalies however may reflect a study design inadequate for the variation of interest.
PCA with anomaly detection PCA summarises the covariance structure of the training set data and will therefore reflect all variance present on that set.Will PCA detect all anomalous behaviour? No method will, but it has its str
28,700
regarding the output format for semantic segmentation
Semantic segmentation is just extended classification, where you perform classification of each pixel into the n_classes. Let's say your input is an RGB image with size (cols,rows,3), you pass a batch of such images sized (batch_size, cols, rows, 3) to the CNN. After performing computations in the network graph, you will end up with a choice to have the last convolutional layer to have n_outputs. Binary segmentation (pixelwise yes / no ) Then you have can have n_outputs = 1 and the output shape will be (batch_size, cols, rows, 1). You later take the sigmoid activation use binary_crossentropy loss. Note that this only works for binary segmentation. MultiClass segmentation (pixelwise probability vector) Then you have n_outputs = n_classes and the output shape will be (batch_size, cols, rows, n_classes). Now comes the tricky part. You need to apply softmax to each pixel probability vector which generally involves permuting dimensions depending on the deep learning framework you are using. In this case you use categorical_crossentropy as it In Keras you can final_conv_out = Convolution2D(n_classes, 1, 1)(conv9) x = Reshape((n_classes, rows*cols))(final_conv_out) x = Permute((2,1))(x) # seg is a pixelwise probability vector sized (batch_size, rows*cols, n_classes) seg = Activation("softmax")(x)
regarding the output format for semantic segmentation
Semantic segmentation is just extended classification, where you perform classification of each pixel into the n_classes. Let's say your input is an RGB image with size (cols,rows,3), you pass a batc
regarding the output format for semantic segmentation Semantic segmentation is just extended classification, where you perform classification of each pixel into the n_classes. Let's say your input is an RGB image with size (cols,rows,3), you pass a batch of such images sized (batch_size, cols, rows, 3) to the CNN. After performing computations in the network graph, you will end up with a choice to have the last convolutional layer to have n_outputs. Binary segmentation (pixelwise yes / no ) Then you have can have n_outputs = 1 and the output shape will be (batch_size, cols, rows, 1). You later take the sigmoid activation use binary_crossentropy loss. Note that this only works for binary segmentation. MultiClass segmentation (pixelwise probability vector) Then you have n_outputs = n_classes and the output shape will be (batch_size, cols, rows, n_classes). Now comes the tricky part. You need to apply softmax to each pixel probability vector which generally involves permuting dimensions depending on the deep learning framework you are using. In this case you use categorical_crossentropy as it In Keras you can final_conv_out = Convolution2D(n_classes, 1, 1)(conv9) x = Reshape((n_classes, rows*cols))(final_conv_out) x = Permute((2,1))(x) # seg is a pixelwise probability vector sized (batch_size, rows*cols, n_classes) seg = Activation("softmax")(x)
regarding the output format for semantic segmentation Semantic segmentation is just extended classification, where you perform classification of each pixel into the n_classes. Let's say your input is an RGB image with size (cols,rows,3), you pass a batc