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
17,301
Confidence intervals for regression parameters: Bayesian vs. classical
For linear Gaussian models it is better to use the bayesm package. It implements the semi-conjugate family of priors, and the Jeffreys prior is a limit case of this family. See my example below. These are classical simulations, there's no need to use MCMC. I do not remember whether the credibility intervals about the regression parameters are exactly the same as the usual least squares confidence intervals, but in any case they are very close. > # required package > library(bayesm) > # data > age <- c(35,45,55,65,75) > tension <- c(114,124,143,158,166) > y <- tension > # model matrix > X <- model.matrix(tension~age) > # prior parameters > Theta0 <- c(0,0) > A0 <- 0.0001*diag(2) > nu0 <- 0 > sigam0sq <- 0 > # number of simulations > n.sims <- 5000 > # run posterior simulations > Data <- list(y=y,X=X) > Prior <- list(betabar=Theta0, A=A0, nu=nu0, ssq=sigam0sq) > Mcmc <- list(R=n.sims) > bayesian.reg <- runireg(Data, Prior, Mcmc) > beta.sims <- t(bayesian.reg$betadraw) # transpose of bayesian.reg$betadraw > sigmasq.sims <- bayesian.reg$sigmasqdraw > apply(beta.sims, 1, quantile, probs = c(0.025, 0.975)) [,1] [,2] 2.5% 53.33948 1.170794 97.5% 77.23371 1.585798 > # to be compared with: > frequentist.reg <- lm(tension~age)
Confidence intervals for regression parameters: Bayesian vs. classical
For linear Gaussian models it is better to use the bayesm package. It implements the semi-conjugate family of priors, and the Jeffreys prior is a limit case of this family. See my example below. These
Confidence intervals for regression parameters: Bayesian vs. classical For linear Gaussian models it is better to use the bayesm package. It implements the semi-conjugate family of priors, and the Jeffreys prior is a limit case of this family. See my example below. These are classical simulations, there's no need to use MCMC. I do not remember whether the credibility intervals about the regression parameters are exactly the same as the usual least squares confidence intervals, but in any case they are very close. > # required package > library(bayesm) > # data > age <- c(35,45,55,65,75) > tension <- c(114,124,143,158,166) > y <- tension > # model matrix > X <- model.matrix(tension~age) > # prior parameters > Theta0 <- c(0,0) > A0 <- 0.0001*diag(2) > nu0 <- 0 > sigam0sq <- 0 > # number of simulations > n.sims <- 5000 > # run posterior simulations > Data <- list(y=y,X=X) > Prior <- list(betabar=Theta0, A=A0, nu=nu0, ssq=sigam0sq) > Mcmc <- list(R=n.sims) > bayesian.reg <- runireg(Data, Prior, Mcmc) > beta.sims <- t(bayesian.reg$betadraw) # transpose of bayesian.reg$betadraw > sigmasq.sims <- bayesian.reg$sigmasqdraw > apply(beta.sims, 1, quantile, probs = c(0.025, 0.975)) [,1] [,2] 2.5% 53.33948 1.170794 97.5% 77.23371 1.585798 > # to be compared with: > frequentist.reg <- lm(tension~age)
Confidence intervals for regression parameters: Bayesian vs. classical For linear Gaussian models it is better to use the bayesm package. It implements the semi-conjugate family of priors, and the Jeffreys prior is a limit case of this family. See my example below. These
17,302
Confidence intervals for regression parameters: Bayesian vs. classical
Given that simple linear regression is analytically identical between classical and Bayesian analysis with Jeffrey's prior, both of which are analytic, it seems a bit odd to resort to a numerical method such as MCMC to do the Bayesian analysis. MCMC is just a numerical integration tool, which allows Bayesian methods to be used in more complicated problems which are analytically intractable, just the same as Newton-Rhapson or Fisher Scoring are numerical methods for solving classical problems which are intractable. The posterior distribution p(b|y) using the Jeffrey's prior p(a,b,s) proportional to 1/s (where s is the standard deviation of the error) is a student t distribution with location b_ols, scale se_b_ols ("ols" for "ordinary least squares" estimate), and n-2 degrees of freedom. But the sampling distribution of b_ols is also a student t with location b, scale se_b_ols, and n-2 degrees of freedom. Thus they are identical except that b and b_ols have been swapped, so when it comes to creating the interval, the "est +- bound" of the confidence interval gets reversed to a "est -+ bound" in the credible interval. So the confidence interval and credible interval are analytically identical, and it matters not which method is used (provided there is no additional prior information) - so take the method which is computationally cheaper (e.g. the one with fewer matrix inversions). What your result with MCMC shows is that the particular approximation used with MCMC gives a credible interval which is too wide compared to the exact analytic credible interval. This is probably a good thing (although we would want the approximation to be better) that the approximate Bayesian solution appears more conservative than the exact Bayesian solution.
Confidence intervals for regression parameters: Bayesian vs. classical
Given that simple linear regression is analytically identical between classical and Bayesian analysis with Jeffrey's prior, both of which are analytic, it seems a bit odd to resort to a numerical meth
Confidence intervals for regression parameters: Bayesian vs. classical Given that simple linear regression is analytically identical between classical and Bayesian analysis with Jeffrey's prior, both of which are analytic, it seems a bit odd to resort to a numerical method such as MCMC to do the Bayesian analysis. MCMC is just a numerical integration tool, which allows Bayesian methods to be used in more complicated problems which are analytically intractable, just the same as Newton-Rhapson or Fisher Scoring are numerical methods for solving classical problems which are intractable. The posterior distribution p(b|y) using the Jeffrey's prior p(a,b,s) proportional to 1/s (where s is the standard deviation of the error) is a student t distribution with location b_ols, scale se_b_ols ("ols" for "ordinary least squares" estimate), and n-2 degrees of freedom. But the sampling distribution of b_ols is also a student t with location b, scale se_b_ols, and n-2 degrees of freedom. Thus they are identical except that b and b_ols have been swapped, so when it comes to creating the interval, the "est +- bound" of the confidence interval gets reversed to a "est -+ bound" in the credible interval. So the confidence interval and credible interval are analytically identical, and it matters not which method is used (provided there is no additional prior information) - so take the method which is computationally cheaper (e.g. the one with fewer matrix inversions). What your result with MCMC shows is that the particular approximation used with MCMC gives a credible interval which is too wide compared to the exact analytic credible interval. This is probably a good thing (although we would want the approximation to be better) that the approximate Bayesian solution appears more conservative than the exact Bayesian solution.
Confidence intervals for regression parameters: Bayesian vs. classical Given that simple linear regression is analytically identical between classical and Bayesian analysis with Jeffrey's prior, both of which are analytic, it seems a bit odd to resort to a numerical meth
17,303
Autocorrelation in the presence of non-stationarity?
@whuber gave a nice answer. I would just add, that you can simulate this very easily in R: op <- par(mfrow = c(2,2), mar = .5 + c(0,0,0,0)) N <- 500 # Simulate a Gaussian noise process y1 <- rnorm(N) # Turn it into integrated noise (a random walk) y2 <- cumsum(y1) plot(ts(y1), xlab="", ylab="", main="", axes=F); box() plot(ts(y2), xlab="", ylab="", main="", axes=F); box() acf(y1, xlab="", ylab="", main="", axes=F); box() acf(y2, xlab="", ylab="", main="", axes=F); box() par(op) Which ends up looking somewhat like this: So you can easily see that the ACF function trails off slowly to zero in the case of a non-stationary series. The rate of decline is some measure of the trend, as @whuber mentioned, although this isn't the best tool to use for that kind of analysis.
Autocorrelation in the presence of non-stationarity?
@whuber gave a nice answer. I would just add, that you can simulate this very easily in R: op <- par(mfrow = c(2,2), mar = .5 + c(0,0,0,0)) N <- 500 # Simulate a Gaussian noise process y1 <- rnorm(N
Autocorrelation in the presence of non-stationarity? @whuber gave a nice answer. I would just add, that you can simulate this very easily in R: op <- par(mfrow = c(2,2), mar = .5 + c(0,0,0,0)) N <- 500 # Simulate a Gaussian noise process y1 <- rnorm(N) # Turn it into integrated noise (a random walk) y2 <- cumsum(y1) plot(ts(y1), xlab="", ylab="", main="", axes=F); box() plot(ts(y2), xlab="", ylab="", main="", axes=F); box() acf(y1, xlab="", ylab="", main="", axes=F); box() acf(y2, xlab="", ylab="", main="", axes=F); box() par(op) Which ends up looking somewhat like this: So you can easily see that the ACF function trails off slowly to zero in the case of a non-stationary series. The rate of decline is some measure of the trend, as @whuber mentioned, although this isn't the best tool to use for that kind of analysis.
Autocorrelation in the presence of non-stationarity? @whuber gave a nice answer. I would just add, that you can simulate this very easily in R: op <- par(mfrow = c(2,2), mar = .5 + c(0,0,0,0)) N <- 500 # Simulate a Gaussian noise process y1 <- rnorm(N
17,304
Autocorrelation in the presence of non-stationarity?
In its alternative form as a variogram, the rate at which the function grows with large lags is roughly the square of the average trend. This can sometimes be a useful way to decide whether you have adequately removed any trends. You can think of the variogram as the squared correlation multiplied by an appropriate variance and flipped upside down. (This result is a direct consequence of the analysis presented at Why does including latitude and longitude in a GAM account for spatial autocorrelation?, which shows how the variogram includes information about the expected squared difference between values at different locations.)
Autocorrelation in the presence of non-stationarity?
In its alternative form as a variogram, the rate at which the function grows with large lags is roughly the square of the average trend. This can sometimes be a useful way to decide whether you have
Autocorrelation in the presence of non-stationarity? In its alternative form as a variogram, the rate at which the function grows with large lags is roughly the square of the average trend. This can sometimes be a useful way to decide whether you have adequately removed any trends. You can think of the variogram as the squared correlation multiplied by an appropriate variance and flipped upside down. (This result is a direct consequence of the analysis presented at Why does including latitude and longitude in a GAM account for spatial autocorrelation?, which shows how the variogram includes information about the expected squared difference between values at different locations.)
Autocorrelation in the presence of non-stationarity? In its alternative form as a variogram, the rate at which the function grows with large lags is roughly the square of the average trend. This can sometimes be a useful way to decide whether you have
17,305
Autocorrelation in the presence of non-stationarity?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. One idea could be to make your time series stationary and then to perform ACF on it. One way to make a time series stationary is to compute the differences between consecutive observations. The ACF of the differenced signal should not suffer from the effects of trends or seasonality in the signal.
Autocorrelation in the presence of non-stationarity?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Autocorrelation in the presence of non-stationarity? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. One idea could be to make your time series stationary and then to perform ACF on it. One way to make a time series stationary is to compute the differences between consecutive observations. The ACF of the differenced signal should not suffer from the effects of trends or seasonality in the signal.
Autocorrelation in the presence of non-stationarity? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
17,306
What does a data-generating process (DGP) actually mean?
The DGP is the processes that cause data to occur as they do. They are a Platonic ideal that we do not and cannot know. Only in simulations can we define a mathematical DGP, in the real world they are hidden from us. The aim of mathematical modelling is abstraction of the data. This means taking what we know and observe and trying to find a more generalised description of underlying reality that would allow us to make useful predictions in new situations. There is saying widely used on this site that all models are wrong but some are useful, this is the cause of that saying. 'the DGP is given as $y=a+bx+e$ where the error term fulfills all the OLS assumptions.' Is a cop out because the $e$ term encapsulates a wide array of lower order contributors to the data generation. Whatever has produced the data has a precise form, not a hand wavy error term. What we call error is just variation that we can't explain a) Given knowledge of the value x takes one would describe their belief about the value y takes with the probability distribution on the right hand side. That is the aim that we try to evaluate or beliefs about y based on x. However the example in isolation is misleading wrt the data generating process, what is quoted is a regression model not a DGP. I'd prefer to write something like $y=a+bx+cU_1+...zU_i$ where the $e$ term is split into a series of unknown underlying factors $U$ from 1 up to an indeterminate $i$. We then try to learn about $y$ by hypothesiseing $y=a+bx+e$ and projecting that model onto the data. We find that x is not quite enough to fit the data and after more poking around we realise that a previously unidentified factor is related, so we can replace $U_1$ with $z$ and collect new data to test the new hypothesis. If it fits better then we update our beliefs about the DGP. We keep going until we run out of ideas, it is no longer economically possible to collect data accurate enough to eliminate more $U_i$ terms, the model performs well enough for our needs or for a whole host of pragmatic reasons. We never stop because we have tried every possible $U_i$ term. b)something that allows a causal interpretation? This is getting deeper into extremely philosophical territory. Science is based on the premise that DGPs underpin reality and through careful thought and experimentation we can uncover that underlying reality. We use statistics to compare the outcome of the DGP with our hypothesis of what the DPG is and we look for a small $e$ to give us faith that we have captured a significant portion of the DGP. However because we never truly know the DGP we try to quantify the risk we are taking. Let us suppose the model we estimate is $y=a+bx+e$ but that the DGP is $y=a+bx+cz+e$ this will yield biased estimates if $x$ and z are correlated". I don't get what this is supposed to mean if the regression equation describes the mean of y conditional on x. The "underspecified" model will yield a higher(or lower) coefficient to take into account the correlation, it will however still correctly describe the expectation of Y conditional on x. Here it seems to me that they are interpreting the regression coefficients as meaning the expected change in y if the regressor is changed by one unit(in a specific instance) If the model has not been exposed to variation in $U_i$, in this case crystallised as $z$, it cannot account for the correlation. Part of the relationship between $x$ and $y$ is dependent on an unknown third factor which influences the nature of the relationship between $x$ and $y$. If the unseen $z$ changes it has an unpredictable effect on the x-y relationship because it has not been captured. If you are familiar with PCA or PLS or similar methods you will understand how subtle and complex correlations are. A correlation matrix is a high level summary that hides a lot of detail. PCA can unpack a single correlation matrix into several distinct underlying causes of correlated behaviour. Each PC describes a unique set of correlated behaviour. Furthermore each PC is uncorrelated with the others so knowing about one set of correlated behaviour gives you zero information on the others. You have to explicitly look at each possible correlation to account for it. however still correctly describe the expectation of Y conditional on x This will hold true while the underlying correlation structure applies, but if you haven't investigated the interaction of $x$ and $z$ then you don't know when it breaks down or changes. This issue is what underlies the need for verification of models in any new population or situation. A real world example of z may be unmeasured dietary factors affecting an analytic target (x) correlated to disease mortality (y). Over years dietary habits of populations change, which can change the metabolism of the analyte or the underlying physiology the analyte acts on and from there affects mortality in a different way. @Carl provides some examples of commonly used scenarios for explaining DGP where we use very simple statistical models of probability to allow us to predict long run behaviour. However all these probability models have physics mechanisms underpinning them. Consider rolling dice, what factors may include that? I'll list a few I can think of : Symmetry of the dice Starting orientation Direction of throw Force of throw Local topography (shape of surface its thrown towards) Spin Coefficient of friction between dice and surface Roundness of edges and corners Air movement Temperature The theory behind DGP is that if you could identify and accurately measure enough factors then you could predict the outcome of a single throw to within your desired precision. So let's say we build a model for dice rolling in a Las Vegas casino and we win so much we get blacklisted in every major casino (we forgot to lose enough). Now take that model and apply it to a poorly maintained drafty gambling den, will it still apply accurately enough to win more than we lose? We won't know until we test it.
What does a data-generating process (DGP) actually mean?
The DGP is the processes that cause data to occur as they do. They are a Platonic ideal that we do not and cannot know. Only in simulations can we define a mathematical DGP, in the real world they are
What does a data-generating process (DGP) actually mean? The DGP is the processes that cause data to occur as they do. They are a Platonic ideal that we do not and cannot know. Only in simulations can we define a mathematical DGP, in the real world they are hidden from us. The aim of mathematical modelling is abstraction of the data. This means taking what we know and observe and trying to find a more generalised description of underlying reality that would allow us to make useful predictions in new situations. There is saying widely used on this site that all models are wrong but some are useful, this is the cause of that saying. 'the DGP is given as $y=a+bx+e$ where the error term fulfills all the OLS assumptions.' Is a cop out because the $e$ term encapsulates a wide array of lower order contributors to the data generation. Whatever has produced the data has a precise form, not a hand wavy error term. What we call error is just variation that we can't explain a) Given knowledge of the value x takes one would describe their belief about the value y takes with the probability distribution on the right hand side. That is the aim that we try to evaluate or beliefs about y based on x. However the example in isolation is misleading wrt the data generating process, what is quoted is a regression model not a DGP. I'd prefer to write something like $y=a+bx+cU_1+...zU_i$ where the $e$ term is split into a series of unknown underlying factors $U$ from 1 up to an indeterminate $i$. We then try to learn about $y$ by hypothesiseing $y=a+bx+e$ and projecting that model onto the data. We find that x is not quite enough to fit the data and after more poking around we realise that a previously unidentified factor is related, so we can replace $U_1$ with $z$ and collect new data to test the new hypothesis. If it fits better then we update our beliefs about the DGP. We keep going until we run out of ideas, it is no longer economically possible to collect data accurate enough to eliminate more $U_i$ terms, the model performs well enough for our needs or for a whole host of pragmatic reasons. We never stop because we have tried every possible $U_i$ term. b)something that allows a causal interpretation? This is getting deeper into extremely philosophical territory. Science is based on the premise that DGPs underpin reality and through careful thought and experimentation we can uncover that underlying reality. We use statistics to compare the outcome of the DGP with our hypothesis of what the DPG is and we look for a small $e$ to give us faith that we have captured a significant portion of the DGP. However because we never truly know the DGP we try to quantify the risk we are taking. Let us suppose the model we estimate is $y=a+bx+e$ but that the DGP is $y=a+bx+cz+e$ this will yield biased estimates if $x$ and z are correlated". I don't get what this is supposed to mean if the regression equation describes the mean of y conditional on x. The "underspecified" model will yield a higher(or lower) coefficient to take into account the correlation, it will however still correctly describe the expectation of Y conditional on x. Here it seems to me that they are interpreting the regression coefficients as meaning the expected change in y if the regressor is changed by one unit(in a specific instance) If the model has not been exposed to variation in $U_i$, in this case crystallised as $z$, it cannot account for the correlation. Part of the relationship between $x$ and $y$ is dependent on an unknown third factor which influences the nature of the relationship between $x$ and $y$. If the unseen $z$ changes it has an unpredictable effect on the x-y relationship because it has not been captured. If you are familiar with PCA or PLS or similar methods you will understand how subtle and complex correlations are. A correlation matrix is a high level summary that hides a lot of detail. PCA can unpack a single correlation matrix into several distinct underlying causes of correlated behaviour. Each PC describes a unique set of correlated behaviour. Furthermore each PC is uncorrelated with the others so knowing about one set of correlated behaviour gives you zero information on the others. You have to explicitly look at each possible correlation to account for it. however still correctly describe the expectation of Y conditional on x This will hold true while the underlying correlation structure applies, but if you haven't investigated the interaction of $x$ and $z$ then you don't know when it breaks down or changes. This issue is what underlies the need for verification of models in any new population or situation. A real world example of z may be unmeasured dietary factors affecting an analytic target (x) correlated to disease mortality (y). Over years dietary habits of populations change, which can change the metabolism of the analyte or the underlying physiology the analyte acts on and from there affects mortality in a different way. @Carl provides some examples of commonly used scenarios for explaining DGP where we use very simple statistical models of probability to allow us to predict long run behaviour. However all these probability models have physics mechanisms underpinning them. Consider rolling dice, what factors may include that? I'll list a few I can think of : Symmetry of the dice Starting orientation Direction of throw Force of throw Local topography (shape of surface its thrown towards) Spin Coefficient of friction between dice and surface Roundness of edges and corners Air movement Temperature The theory behind DGP is that if you could identify and accurately measure enough factors then you could predict the outcome of a single throw to within your desired precision. So let's say we build a model for dice rolling in a Las Vegas casino and we win so much we get blacklisted in every major casino (we forgot to lose enough). Now take that model and apply it to a poorly maintained drafty gambling den, will it still apply accurately enough to win more than we lose? We won't know until we test it.
What does a data-generating process (DGP) actually mean? The DGP is the processes that cause data to occur as they do. They are a Platonic ideal that we do not and cannot know. Only in simulations can we define a mathematical DGP, in the real world they are
17,307
What does a data-generating process (DGP) actually mean?
A data generating process is a generic term for any process that generates data. For example, rolling dice, a Monte Carlo simulation of normal data with $\mathcal{N}(0,1)$, blowing confetti into the air to see how many pieces land inside a bucket as a function of time, throwing darts at an $x$-mark on a wall to show a 2D data cloud, dealing a poker hand from a marked deck of cards or whatever it takes to generate data.
What does a data-generating process (DGP) actually mean?
A data generating process is a generic term for any process that generates data. For example, rolling dice, a Monte Carlo simulation of normal data with $\mathcal{N}(0,1)$, blowing confetti into the a
What does a data-generating process (DGP) actually mean? A data generating process is a generic term for any process that generates data. For example, rolling dice, a Monte Carlo simulation of normal data with $\mathcal{N}(0,1)$, blowing confetti into the air to see how many pieces land inside a bucket as a function of time, throwing darts at an $x$-mark on a wall to show a 2D data cloud, dealing a poker hand from a marked deck of cards or whatever it takes to generate data.
What does a data-generating process (DGP) actually mean? A data generating process is a generic term for any process that generates data. For example, rolling dice, a Monte Carlo simulation of normal data with $\mathcal{N}(0,1)$, blowing confetti into the a
17,308
What is the difference between period cycle and seasonality?
The difference between seasonal and cyclical behavior has to do with how regular the period of change is. A seasonal behavior is very strictly regular, meaning there is a precise amount of time between the peaks and troughs of the data. For instance temperature would have a seasonal behavior. The coldest day of the year and the warmest day of the year may move (because of factors other than time than influence the data) but you will never see drift over time where eventually winter comes in June in the northern hemisphere. Cyclical behavior on the other hand can drift over time because the time between periods isn't precise. For example, the stock market tends to cycle between periods of high and low values, but there is no set amount of time between those fluctuations. Series can show both cyclical and seasonal behavior. In the home prices example above, there is a cyclical effect due to the market, but there is also a seasonal effect because most people would rather move in the summer when their kids are between grades of school. You can also have multiple seasonal (or cyclical) effects. For example, people tend to try and make positive behavioral changes on the "1st" of something, so you see spikes in gym attendance of course on the 1st of the year, but also the first of each month and each week, so gym attendance has yearly, monthly, and weekly seasonality. When you are looking for a second seasonal pattern or a cyclical pattern in seasonal data, it can help to take a moving average at the higher seasonal frequency to remove those seasonal effects. For instance, if you take a moving average of the housing data with a window size of 12 you will see the cyclical pattern more clearly. This only works though to remove a higher frequency pattern from a lower frequency one. Also, for the record, seasonal behavior does not have to happen only on sub-year time units. For example, the sun goes through what are called "solar cycles" which are periods of time where it puts out more or less heat. This behavior shows a seasonality of almost exactly 11 years, so a yearly time series of the heat put out by the sun would have a seasonality of 11. In many cases the difference in seasonal vs cyclical behavior can be known or measured with reasonable accuracy by looking at the regularity of the peaks in your data and looking for a drift the timing peaks from the mean distance between them. A series with strong seasonality will show clear peaks in the partial auto-correlation function as well as the auto-correlation function, whereas a cyclical series will only have the strong peaks in the auto-correlation function. However if you don't have enough data to determine this or if the data is very noisy making the measurements difficult, the best way to determine if a behavior is cyclical or seasonal can be by thinking about the cause of the fluctuation in the data. If the cause is dependent directly on time then the data are likely seasonal (ex. it takes ~365.25 days for the earth to travel around the sun, the position of the earth around the sun effects temperature, therefore temperature shows a yearly seasonal pattern). If on the other hand, the cause is based on previous values of the series rather than directly on time, the series is likely cyclical (ex. when the value of stocks go up, it gives confidence in the market, so more people invest making prices go up, and vice versa, therefore stocks show a cyclical pattern).
What is the difference between period cycle and seasonality?
The difference between seasonal and cyclical behavior has to do with how regular the period of change is. A seasonal behavior is very strictly regular, meaning there is a precise amount of time betwe
What is the difference between period cycle and seasonality? The difference between seasonal and cyclical behavior has to do with how regular the period of change is. A seasonal behavior is very strictly regular, meaning there is a precise amount of time between the peaks and troughs of the data. For instance temperature would have a seasonal behavior. The coldest day of the year and the warmest day of the year may move (because of factors other than time than influence the data) but you will never see drift over time where eventually winter comes in June in the northern hemisphere. Cyclical behavior on the other hand can drift over time because the time between periods isn't precise. For example, the stock market tends to cycle between periods of high and low values, but there is no set amount of time between those fluctuations. Series can show both cyclical and seasonal behavior. In the home prices example above, there is a cyclical effect due to the market, but there is also a seasonal effect because most people would rather move in the summer when their kids are between grades of school. You can also have multiple seasonal (or cyclical) effects. For example, people tend to try and make positive behavioral changes on the "1st" of something, so you see spikes in gym attendance of course on the 1st of the year, but also the first of each month and each week, so gym attendance has yearly, monthly, and weekly seasonality. When you are looking for a second seasonal pattern or a cyclical pattern in seasonal data, it can help to take a moving average at the higher seasonal frequency to remove those seasonal effects. For instance, if you take a moving average of the housing data with a window size of 12 you will see the cyclical pattern more clearly. This only works though to remove a higher frequency pattern from a lower frequency one. Also, for the record, seasonal behavior does not have to happen only on sub-year time units. For example, the sun goes through what are called "solar cycles" which are periods of time where it puts out more or less heat. This behavior shows a seasonality of almost exactly 11 years, so a yearly time series of the heat put out by the sun would have a seasonality of 11. In many cases the difference in seasonal vs cyclical behavior can be known or measured with reasonable accuracy by looking at the regularity of the peaks in your data and looking for a drift the timing peaks from the mean distance between them. A series with strong seasonality will show clear peaks in the partial auto-correlation function as well as the auto-correlation function, whereas a cyclical series will only have the strong peaks in the auto-correlation function. However if you don't have enough data to determine this or if the data is very noisy making the measurements difficult, the best way to determine if a behavior is cyclical or seasonal can be by thinking about the cause of the fluctuation in the data. If the cause is dependent directly on time then the data are likely seasonal (ex. it takes ~365.25 days for the earth to travel around the sun, the position of the earth around the sun effects temperature, therefore temperature shows a yearly seasonal pattern). If on the other hand, the cause is based on previous values of the series rather than directly on time, the series is likely cyclical (ex. when the value of stocks go up, it gives confidence in the market, so more people invest making prices go up, and vice versa, therefore stocks show a cyclical pattern).
What is the difference between period cycle and seasonality? The difference between seasonal and cyclical behavior has to do with how regular the period of change is. A seasonal behavior is very strictly regular, meaning there is a precise amount of time betwe
17,309
What is the difference between period cycle and seasonality?
The term cycle refers to the recurrent variations in time series that in generally last longer than a year and it can be as many as 15 or 20 years. These variations are regular neither in amplitude nor in length. Most of the time series relating to business exhibit some kind of cyclical or oscillatory variation. These fluctuations are long term movements that represent consistently recurring rises and declines in activity. Seasonal variations are those periodic movements in business activity which occur regularly every year and have their origin in the nature of the year itself. Since these variations repeat during a period of 12 months they can be predicted fairly accurately. Nearly every type of business activity is subject to seasonal influence to a greater or lesser degree and as such these variations are regarded as normal phenomena recurring every year.
What is the difference between period cycle and seasonality?
The term cycle refers to the recurrent variations in time series that in generally last longer than a year and it can be as many as 15 or 20 years. These variations are regular neither in amplitude no
What is the difference between period cycle and seasonality? The term cycle refers to the recurrent variations in time series that in generally last longer than a year and it can be as many as 15 or 20 years. These variations are regular neither in amplitude nor in length. Most of the time series relating to business exhibit some kind of cyclical or oscillatory variation. These fluctuations are long term movements that represent consistently recurring rises and declines in activity. Seasonal variations are those periodic movements in business activity which occur regularly every year and have their origin in the nature of the year itself. Since these variations repeat during a period of 12 months they can be predicted fairly accurately. Nearly every type of business activity is subject to seasonal influence to a greater or lesser degree and as such these variations are regarded as normal phenomena recurring every year.
What is the difference between period cycle and seasonality? The term cycle refers to the recurrent variations in time series that in generally last longer than a year and it can be as many as 15 or 20 years. These variations are regular neither in amplitude no
17,310
How to choose the null and alternative hypothesis?
The rule for the proper formulation of a hypothesis test is that the alternative or research hypothesis is the statement that, if true, is strongly supported by the evidence furnished by the data. The null hypothesis is generally the complement of the alternative hypothesis. Frequently, it is (or contains) the assumption that you are making about how the data are distributed in order to calculate the test statistic. Here are a few examples to help you understand how these are properly chosen. Suppose I am an epidemiologist in public health, and I'm investigating whether the incidence of smoking among a certain ethnic group is greater than the population as a whole, and therefore there is a need to target anti-smoking campaigns for this sub-population through greater community outreach and education. From previous studies that have been published in the literature, I find that the incidence among the general population is $p_0$. I can then go about collecting sample data (that's actually the hard part!) to test $$H_0 : p = p_0 \quad \mathrm{vs.} \quad H_a : p > p_0.$$ This is a one-sided binomial proportion test. $H_a$ is the statement that, if it were true, would need to be strongly supported by the data we collected. It is the statement that carries the burden of proof. This is because any conclusion we draw from the test is conditional upon assuming that the null is true: either $H_a$ is accepted, or the test is inconclusive and there is insufficient evidence from the data to suggest $H_a$ is true. The choice of $H_0$ reflects the underlying assumption that there is no difference in the smoking rates of the sub-population compared to the whole. Now suppose I am a researcher investigating a new drug that I believe to be equally effective to an existing standard of treatment, but with fewer side effects and therefore a more desirable safety profile. I would like to demonstrate the equal efficacy by conducting a bioequivalence test. If $\mu_0$ is the mean existing standard treatment effect, then my hypothesis might look like this: $$H_0 : |\mu - \mu_0| \ge \Delta \quad \mathrm{vs.} \quad H_a : |\mu - \mu_0| < \Delta,$$ for some choice of margin $\Delta$ that I consider to be clinically significant. For example, a clinician might say that two treatments are sufficiently bioequivalent if there is less than a $\Delta = 10\%$ difference in treatment effect. Note again that $H_a$ is the statement that carries the burden of proof: the data we collect must strongly support it, in order for us to accept it; otherwise, it could still be true but we don't have the evidence to support the claim. Now suppose I am doing an analysis for a small business owner who sells three products $A$, $B$, $C$. They suspect that there is a statistically significant preference for these three products. Then my hypothesis is $$H_0 : \mu_A = \mu_B = \mu_C \quad \mathrm{vs.} \quad H_a : \exists i \ne j \text{ such that } \mu_i \ne \mu_j.$$ Really, all that $H_a$ is saying is that there are two means that are not equal to each other, which would then suggest that some difference in preference exists.
How to choose the null and alternative hypothesis?
The rule for the proper formulation of a hypothesis test is that the alternative or research hypothesis is the statement that, if true, is strongly supported by the evidence furnished by the data. The
How to choose the null and alternative hypothesis? The rule for the proper formulation of a hypothesis test is that the alternative or research hypothesis is the statement that, if true, is strongly supported by the evidence furnished by the data. The null hypothesis is generally the complement of the alternative hypothesis. Frequently, it is (or contains) the assumption that you are making about how the data are distributed in order to calculate the test statistic. Here are a few examples to help you understand how these are properly chosen. Suppose I am an epidemiologist in public health, and I'm investigating whether the incidence of smoking among a certain ethnic group is greater than the population as a whole, and therefore there is a need to target anti-smoking campaigns for this sub-population through greater community outreach and education. From previous studies that have been published in the literature, I find that the incidence among the general population is $p_0$. I can then go about collecting sample data (that's actually the hard part!) to test $$H_0 : p = p_0 \quad \mathrm{vs.} \quad H_a : p > p_0.$$ This is a one-sided binomial proportion test. $H_a$ is the statement that, if it were true, would need to be strongly supported by the data we collected. It is the statement that carries the burden of proof. This is because any conclusion we draw from the test is conditional upon assuming that the null is true: either $H_a$ is accepted, or the test is inconclusive and there is insufficient evidence from the data to suggest $H_a$ is true. The choice of $H_0$ reflects the underlying assumption that there is no difference in the smoking rates of the sub-population compared to the whole. Now suppose I am a researcher investigating a new drug that I believe to be equally effective to an existing standard of treatment, but with fewer side effects and therefore a more desirable safety profile. I would like to demonstrate the equal efficacy by conducting a bioequivalence test. If $\mu_0$ is the mean existing standard treatment effect, then my hypothesis might look like this: $$H_0 : |\mu - \mu_0| \ge \Delta \quad \mathrm{vs.} \quad H_a : |\mu - \mu_0| < \Delta,$$ for some choice of margin $\Delta$ that I consider to be clinically significant. For example, a clinician might say that two treatments are sufficiently bioequivalent if there is less than a $\Delta = 10\%$ difference in treatment effect. Note again that $H_a$ is the statement that carries the burden of proof: the data we collect must strongly support it, in order for us to accept it; otherwise, it could still be true but we don't have the evidence to support the claim. Now suppose I am doing an analysis for a small business owner who sells three products $A$, $B$, $C$. They suspect that there is a statistically significant preference for these three products. Then my hypothesis is $$H_0 : \mu_A = \mu_B = \mu_C \quad \mathrm{vs.} \quad H_a : \exists i \ne j \text{ such that } \mu_i \ne \mu_j.$$ Really, all that $H_a$ is saying is that there are two means that are not equal to each other, which would then suggest that some difference in preference exists.
How to choose the null and alternative hypothesis? The rule for the proper formulation of a hypothesis test is that the alternative or research hypothesis is the statement that, if true, is strongly supported by the evidence furnished by the data. The
17,311
How to choose the null and alternative hypothesis?
The null hypothesis is nearly always "something didn't happen" or "there is no effect" or "there is no relationship" or something similar. But it need not be this. In your case, the null would be "there is no relationship between CRM and performance" The usual method is to test the null at some significance level (most often, 0.05). Whether this is a good method is another matter, but it is what is commonly done.
How to choose the null and alternative hypothesis?
The null hypothesis is nearly always "something didn't happen" or "there is no effect" or "there is no relationship" or something similar. But it need not be this. In your case, the null would be "th
How to choose the null and alternative hypothesis? The null hypothesis is nearly always "something didn't happen" or "there is no effect" or "there is no relationship" or something similar. But it need not be this. In your case, the null would be "there is no relationship between CRM and performance" The usual method is to test the null at some significance level (most often, 0.05). Whether this is a good method is another matter, but it is what is commonly done.
How to choose the null and alternative hypothesis? The null hypothesis is nearly always "something didn't happen" or "there is no effect" or "there is no relationship" or something similar. But it need not be this. In your case, the null would be "th
17,312
How to choose the null and alternative hypothesis?
In science proofs, you can never prove anything, you can only demonstrate that your model describes the data better than another model. You want your alternate hypothesis to come from the new model under test, and the null hypothesis to be from a different model. The null hypothesis should come from a model which others would choose to use when challenging your scientific claims! The most common pattern for a scientific claim is "I think that X is a factor in process Y. If everyone already believes X is a factor in the process, then there is nothing to prove, and everyone can just go out and talk about it over drinks. Scientific arguments with null hypothesis are interesting because, if someone takes the opposing view, "X is not a factor in process Y, then there is a disagreement. This is where science does its thing. If you believe "X is a factor in process Y" enough to run an experiment, you should generally know what you're looking to see in the results. So now your phrase becomes "X is a factor in process Y, producing visible outcome Z." This is where you pick your null hypothesis. If someone believes X is not a factor, and your experiment does indeed show Z, then they need an explanation for Z. With your choice of null hypothesis, you are effectively challenging their explanation. The dead simplest explanation is always "Z was caused by random chance because science is based on statistics." Accordingly, most null hypothesis are in the form of "The outcome should be predicted using the previously accepted model plus some random chance to account for statistics. Both hypothesis should be phrased in terms of the visible outcome, NOT the model you intend to prove.[note] You never start with an alternate hypothesis of "I believe X is a factor." You phrase it "I expect to see this result when I observe Z." The null hypothesis will be phrased similarly, "The status quo predicts that we will see this different result when I observe Z." There is always a statistical phrasing in there such as "I expect to observe a normal distribution on Z when I do this experiment over and over." Once you observe results that defend your alternate hypothesis and reject the null hypothsis, you are THEN in a position to make claims about the validity of your model. [note] This bolded statement is my opinion, but I feel confident enough in its wording choice to post it. The hypotheses draw a strong line between the intuitive portion of the science, and the data and analysis of the science. If your phrasing is too close to the model, it becomes hard to separate the model from the data, and makes it harder for the next scientist to use your data In the case of our simple model with process Y and visible outcome Z, the existing belief is that Z will fit a distribution that everyone is already comfortable with, such as "the randomness expected by your particular laboratory equipment setup" or "the purity of the reagents used in the experiment." When you "reject the null hypothesis" what you are saying is most literally, "I have run this experiment, and it is so tremendously unlikely that random chance generated the observed behavior, that everybody should start considering that maybe there's more to this than meets the eye." The alternative hypothesis is what you offer to the world to replace the null hypothesis. It is one thing to go do experiments to poke at holes in other's models, but that doesn't promote science nearly as well as poking holes in other's models and then replacing them with new models that do a better job. Summary With the null and alternate hypothesis, you are trying to challenge the current conventional thinking of the day. Choose the hypotheses so that they effectively declare "Here is a result everybody would expect (null hypothesis). However, I actually went out and did the experiment and gathered data, and it is VERY unlikely that the null hypothesis is true. Here is the result I expected (the alternate hypothesis). Nobody expected this hypothesis to be true but me, but when I gathered the data and did the statistics, it is very likely that my model does a better job of describing reality than the existing model. Accordingly, I reject the null hypothesis, accept my hypothesis, and challenge my fellow scientists to work from this new data." And the fellow scientists are free to: Rejoice and accept your data and model with open arms. Ignore your data or model (sorry, it happens... welcome to real life) Reject your data, and spend their effort running experiments to show different data (It is very common for the science community to say "We do not trust your sample size of 10. We are going to redo your experiment with a sample size of 1000.) Accept your data, but not your model. They then must spend their effort generating a new model which explains the data in a different manner. The last outcome causes strife and bickering, but is ABSOLUTELY part of the scientific process. By using the scientific method to publish your results, you accept that others are free to use the scientific method to contradict your results. They will do so, and publish their results. At this point, the scientific community will make a political decision: who has to go out and spend the money to test their model, and whose model do we accept. TYPICALLY, because you published the model and the data first, and they are refuting your data, the onus is on them to run the experiments which proves why their model is better than yours. But this is now WELL beyond the hypothesis that caused the strife in the first place, so I leave you to experience them in your lifetime!
How to choose the null and alternative hypothesis?
In science proofs, you can never prove anything, you can only demonstrate that your model describes the data better than another model. You want your alternate hypothesis to come from the new model u
How to choose the null and alternative hypothesis? In science proofs, you can never prove anything, you can only demonstrate that your model describes the data better than another model. You want your alternate hypothesis to come from the new model under test, and the null hypothesis to be from a different model. The null hypothesis should come from a model which others would choose to use when challenging your scientific claims! The most common pattern for a scientific claim is "I think that X is a factor in process Y. If everyone already believes X is a factor in the process, then there is nothing to prove, and everyone can just go out and talk about it over drinks. Scientific arguments with null hypothesis are interesting because, if someone takes the opposing view, "X is not a factor in process Y, then there is a disagreement. This is where science does its thing. If you believe "X is a factor in process Y" enough to run an experiment, you should generally know what you're looking to see in the results. So now your phrase becomes "X is a factor in process Y, producing visible outcome Z." This is where you pick your null hypothesis. If someone believes X is not a factor, and your experiment does indeed show Z, then they need an explanation for Z. With your choice of null hypothesis, you are effectively challenging their explanation. The dead simplest explanation is always "Z was caused by random chance because science is based on statistics." Accordingly, most null hypothesis are in the form of "The outcome should be predicted using the previously accepted model plus some random chance to account for statistics. Both hypothesis should be phrased in terms of the visible outcome, NOT the model you intend to prove.[note] You never start with an alternate hypothesis of "I believe X is a factor." You phrase it "I expect to see this result when I observe Z." The null hypothesis will be phrased similarly, "The status quo predicts that we will see this different result when I observe Z." There is always a statistical phrasing in there such as "I expect to observe a normal distribution on Z when I do this experiment over and over." Once you observe results that defend your alternate hypothesis and reject the null hypothsis, you are THEN in a position to make claims about the validity of your model. [note] This bolded statement is my opinion, but I feel confident enough in its wording choice to post it. The hypotheses draw a strong line between the intuitive portion of the science, and the data and analysis of the science. If your phrasing is too close to the model, it becomes hard to separate the model from the data, and makes it harder for the next scientist to use your data In the case of our simple model with process Y and visible outcome Z, the existing belief is that Z will fit a distribution that everyone is already comfortable with, such as "the randomness expected by your particular laboratory equipment setup" or "the purity of the reagents used in the experiment." When you "reject the null hypothesis" what you are saying is most literally, "I have run this experiment, and it is so tremendously unlikely that random chance generated the observed behavior, that everybody should start considering that maybe there's more to this than meets the eye." The alternative hypothesis is what you offer to the world to replace the null hypothesis. It is one thing to go do experiments to poke at holes in other's models, but that doesn't promote science nearly as well as poking holes in other's models and then replacing them with new models that do a better job. Summary With the null and alternate hypothesis, you are trying to challenge the current conventional thinking of the day. Choose the hypotheses so that they effectively declare "Here is a result everybody would expect (null hypothesis). However, I actually went out and did the experiment and gathered data, and it is VERY unlikely that the null hypothesis is true. Here is the result I expected (the alternate hypothesis). Nobody expected this hypothesis to be true but me, but when I gathered the data and did the statistics, it is very likely that my model does a better job of describing reality than the existing model. Accordingly, I reject the null hypothesis, accept my hypothesis, and challenge my fellow scientists to work from this new data." And the fellow scientists are free to: Rejoice and accept your data and model with open arms. Ignore your data or model (sorry, it happens... welcome to real life) Reject your data, and spend their effort running experiments to show different data (It is very common for the science community to say "We do not trust your sample size of 10. We are going to redo your experiment with a sample size of 1000.) Accept your data, but not your model. They then must spend their effort generating a new model which explains the data in a different manner. The last outcome causes strife and bickering, but is ABSOLUTELY part of the scientific process. By using the scientific method to publish your results, you accept that others are free to use the scientific method to contradict your results. They will do so, and publish their results. At this point, the scientific community will make a political decision: who has to go out and spend the money to test their model, and whose model do we accept. TYPICALLY, because you published the model and the data first, and they are refuting your data, the onus is on them to run the experiments which proves why their model is better than yours. But this is now WELL beyond the hypothesis that caused the strife in the first place, so I leave you to experience them in your lifetime!
How to choose the null and alternative hypothesis? In science proofs, you can never prove anything, you can only demonstrate that your model describes the data better than another model. You want your alternate hypothesis to come from the new model u
17,313
Berry inversion
Consider a multinomial logit model in which you estimate market shares as $$\widehat{s}_{jt} = \frac{\exp(\delta_{jt})}{1 + \sum^{J}_{g=1}\exp(\delta_{gt})}$$ where the outside good is normalized to zero. When you take the log of this expression, you get $$\log (\widehat{s}_{jt}) = \delta_{jt} – \log \left( 1 + \sum^{J}_{g=1}\exp(\delta_{gt}) \right)$$ for the inside goods and for the outside good: $$\log (\widehat{s}_{0t}) = 0 – \log \left( 1 + \sum^{J}_{g=1}\exp(\delta_{gt}) \right)$$ Then your $\delta_{jt}$ is given by $$\delta_{jt} = \log (\widehat{s}_{jt}) – \log (\widehat{s}_{0t}) = X'_{jt}\beta - \alpha p_{jt} + \xi_{jt}$$ and assuming that given a large enough sample the estimated market shares equal the true market shares, as you stated. This can be estimated via OLS where the error term is given by $\xi_{jt}$. Note that markets are assumed to be independent from each other. To clarify the concept, let’s consider an example in Stata. I don’t have a suitable data set in mind for such an exercise, so let us just assume we have aggregate data on 5 products (prod) product prices (p) quantity sold (q) two product characteristics (x1, x2) Suppose good 1 is the outside good with a market share of 10-20% (varying by market) and the remainder being split between the other goods. What you would do in Stata is the following: * calculate the market share of your goods in all markets egen mktsales = sum(q), by(mkt) gen share = q/mktsales * generate logs gen ln_share = ln(share) * subtract the log share of the outside good from the log share of the inside goods gen diffshare = . forval i = 1(1)100 { qui sum ln_share if prod==1 & mkt==`i’ replace diffshare = ln_share - `r(max)’ if mkt==`i’ } * run the regression reg diffshare p x1 x2 And this gives you the Berry inversion or Berry logit for demand estimation. One thing to be cautious about: if the unobserved product characteristics $\xi_{jt}$ include factors that are correlated with price (like quality of the product or advertising campaigns) then you need to use instrumental variables regression. You can do this because we have linearized the market demand system, hence standard 2SLS is an option. In this case you need something which exogenously changes the price but that doesn’t affect demand. Common instruments used in the empirical industrial organizations literature in economics are cost shifters (see Berry et al., 1995) as for instance the price of fish is affected by rough weather on the sea but consumer demand won’t be; product characteristics of rival firms under the assumption that consumer valuation of good $i$ does not depend on other products’ characteristics (see Nevo, 2001) or if you have a spatial dimension to the data, Hausman (1997) uses price changes of a brand in city A to instrument prices in city B. This works given that products of a brand in both cities share common marginal costs but not the same demand. As an alternative, Berry et al. (1995) develop a random coefficients logit model which gives more accurate own and cross-price elasticities and more flexible substitution patterns between goods. References: Berry, S., J. Levinsohn & A. Pakes (1995), “Automobile prices in market equilibrium”, Econmetrica, 63, 4, 841-90 Hausman, J., “Valuation of New Goods Under Perfect and Imperfect Competition,” in Bresnahan and Gordon (eds.), The Economics of New Goods, NBER Studies in Income and Wealth 58, 1997, 209-237 Nevo, A. (2001), “Measuring market power in the ready-to-eat cereal industry”, Econometrica, 69, 2, 307-42
Berry inversion
Consider a multinomial logit model in which you estimate market shares as $$\widehat{s}_{jt} = \frac{\exp(\delta_{jt})}{1 + \sum^{J}_{g=1}\exp(\delta_{gt})}$$ where the outside good is normalized to z
Berry inversion Consider a multinomial logit model in which you estimate market shares as $$\widehat{s}_{jt} = \frac{\exp(\delta_{jt})}{1 + \sum^{J}_{g=1}\exp(\delta_{gt})}$$ where the outside good is normalized to zero. When you take the log of this expression, you get $$\log (\widehat{s}_{jt}) = \delta_{jt} – \log \left( 1 + \sum^{J}_{g=1}\exp(\delta_{gt}) \right)$$ for the inside goods and for the outside good: $$\log (\widehat{s}_{0t}) = 0 – \log \left( 1 + \sum^{J}_{g=1}\exp(\delta_{gt}) \right)$$ Then your $\delta_{jt}$ is given by $$\delta_{jt} = \log (\widehat{s}_{jt}) – \log (\widehat{s}_{0t}) = X'_{jt}\beta - \alpha p_{jt} + \xi_{jt}$$ and assuming that given a large enough sample the estimated market shares equal the true market shares, as you stated. This can be estimated via OLS where the error term is given by $\xi_{jt}$. Note that markets are assumed to be independent from each other. To clarify the concept, let’s consider an example in Stata. I don’t have a suitable data set in mind for such an exercise, so let us just assume we have aggregate data on 5 products (prod) product prices (p) quantity sold (q) two product characteristics (x1, x2) Suppose good 1 is the outside good with a market share of 10-20% (varying by market) and the remainder being split between the other goods. What you would do in Stata is the following: * calculate the market share of your goods in all markets egen mktsales = sum(q), by(mkt) gen share = q/mktsales * generate logs gen ln_share = ln(share) * subtract the log share of the outside good from the log share of the inside goods gen diffshare = . forval i = 1(1)100 { qui sum ln_share if prod==1 & mkt==`i’ replace diffshare = ln_share - `r(max)’ if mkt==`i’ } * run the regression reg diffshare p x1 x2 And this gives you the Berry inversion or Berry logit for demand estimation. One thing to be cautious about: if the unobserved product characteristics $\xi_{jt}$ include factors that are correlated with price (like quality of the product or advertising campaigns) then you need to use instrumental variables regression. You can do this because we have linearized the market demand system, hence standard 2SLS is an option. In this case you need something which exogenously changes the price but that doesn’t affect demand. Common instruments used in the empirical industrial organizations literature in economics are cost shifters (see Berry et al., 1995) as for instance the price of fish is affected by rough weather on the sea but consumer demand won’t be; product characteristics of rival firms under the assumption that consumer valuation of good $i$ does not depend on other products’ characteristics (see Nevo, 2001) or if you have a spatial dimension to the data, Hausman (1997) uses price changes of a brand in city A to instrument prices in city B. This works given that products of a brand in both cities share common marginal costs but not the same demand. As an alternative, Berry et al. (1995) develop a random coefficients logit model which gives more accurate own and cross-price elasticities and more flexible substitution patterns between goods. References: Berry, S., J. Levinsohn & A. Pakes (1995), “Automobile prices in market equilibrium”, Econmetrica, 63, 4, 841-90 Hausman, J., “Valuation of New Goods Under Perfect and Imperfect Competition,” in Bresnahan and Gordon (eds.), The Economics of New Goods, NBER Studies in Income and Wealth 58, 1997, 209-237 Nevo, A. (2001), “Measuring market power in the ready-to-eat cereal industry”, Econometrica, 69, 2, 307-42
Berry inversion Consider a multinomial logit model in which you estimate market shares as $$\widehat{s}_{jt} = \frac{\exp(\delta_{jt})}{1 + \sum^{J}_{g=1}\exp(\delta_{gt})}$$ where the outside good is normalized to z
17,314
How to fix one coefficient and fit others using regression
You need to use the offset argument like this: library(glmnet) x=matrix(rnorm(100*20),100,20) x1=matrix(rnorm(100),100,1) y=rnorm(100) fit1=glmnet(x,y,offset=x1) fit1$offset print(fit1) About the range ... I don't think that has been implemented in glmnet. If they use some numerical method, you may want to dig into the R code and try to restrict it over there, but you'll need a good, solid programming background.
How to fix one coefficient and fit others using regression
You need to use the offset argument like this: library(glmnet) x=matrix(rnorm(100*20),100,20) x1=matrix(rnorm(100),100,1) y=rnorm(100) fit1=glmnet(x,y,offset=x1) fit1$offset print(fit1) About the ran
How to fix one coefficient and fit others using regression You need to use the offset argument like this: library(glmnet) x=matrix(rnorm(100*20),100,20) x1=matrix(rnorm(100),100,1) y=rnorm(100) fit1=glmnet(x,y,offset=x1) fit1$offset print(fit1) About the range ... I don't think that has been implemented in glmnet. If they use some numerical method, you may want to dig into the R code and try to restrict it over there, but you'll need a good, solid programming background.
How to fix one coefficient and fit others using regression You need to use the offset argument like this: library(glmnet) x=matrix(rnorm(100*20),100,20) x1=matrix(rnorm(100),100,1) y=rnorm(100) fit1=glmnet(x,y,offset=x1) fit1$offset print(fit1) About the ran
17,315
How to fix one coefficient and fit others using regression
Well, let's think. You have: $Y = b_0 + b_1x_1 + b_2x_2 + e$ (to keep it simple) You want to force $b_1 = 1$ so, you want $Y = b_0 + x_1 + b_2x_2 + e$ so you could just subtract $x_1$ from each side leaving: $Ynew = Y-x_1 = b_0 + b_2x_2 + e$ which can then estimate $b_2$.
How to fix one coefficient and fit others using regression
Well, let's think. You have: $Y = b_0 + b_1x_1 + b_2x_2 + e$ (to keep it simple) You want to force $b_1 = 1$ so, you want $Y = b_0 + x_1 + b_2x_2 + e$ so you could just subtract $x_1$ from each side
How to fix one coefficient and fit others using regression Well, let's think. You have: $Y = b_0 + b_1x_1 + b_2x_2 + e$ (to keep it simple) You want to force $b_1 = 1$ so, you want $Y = b_0 + x_1 + b_2x_2 + e$ so you could just subtract $x_1$ from each side leaving: $Ynew = Y-x_1 = b_0 + b_2x_2 + e$ which can then estimate $b_2$.
How to fix one coefficient and fit others using regression Well, let's think. You have: $Y = b_0 + b_1x_1 + b_2x_2 + e$ (to keep it simple) You want to force $b_1 = 1$ so, you want $Y = b_0 + x_1 + b_2x_2 + e$ so you could just subtract $x_1$ from each side
17,316
How to fix one coefficient and fit others using regression
With respect to constraining coefficients to be within a range, a Bayesian approach to estimation is one means to accomplish this. In particular, one would rely on a Markov Chain Monte Carlo. First, consider a Gibbs sampling algorithm, which is how you would fit the MCMC in a Bayesian framework absent the restriction. In Gibbs sampling, in each step of the algorithm you sample from the posterior distribution of each parameter (or group of parameters) conditional on the data and all other parameters. Wikipedia provides a good summary of the approach. One way to constrain the range is to apply a Metropolis-Hastings step. The basic idea is to simply throw out any simulated variable that is outside of your bounds. You could then keep re-sampling until that is within your bounds before moving on to the next iteration. The downside to this is that you might get stuck simulating a lot of times, which slows down the MCMC. An alternative approach, originally developed by John Geweke in a few papers and extended in a paper by Rodriguez-Yam, Davis, Sharpe is to simulate from a constrained multivariate normal distribution. This approach can handle linear and non-linear inequality constraints on parameters and I've had some success with it.
How to fix one coefficient and fit others using regression
With respect to constraining coefficients to be within a range, a Bayesian approach to estimation is one means to accomplish this. In particular, one would rely on a Markov Chain Monte Carlo. First,
How to fix one coefficient and fit others using regression With respect to constraining coefficients to be within a range, a Bayesian approach to estimation is one means to accomplish this. In particular, one would rely on a Markov Chain Monte Carlo. First, consider a Gibbs sampling algorithm, which is how you would fit the MCMC in a Bayesian framework absent the restriction. In Gibbs sampling, in each step of the algorithm you sample from the posterior distribution of each parameter (or group of parameters) conditional on the data and all other parameters. Wikipedia provides a good summary of the approach. One way to constrain the range is to apply a Metropolis-Hastings step. The basic idea is to simply throw out any simulated variable that is outside of your bounds. You could then keep re-sampling until that is within your bounds before moving on to the next iteration. The downside to this is that you might get stuck simulating a lot of times, which slows down the MCMC. An alternative approach, originally developed by John Geweke in a few papers and extended in a paper by Rodriguez-Yam, Davis, Sharpe is to simulate from a constrained multivariate normal distribution. This approach can handle linear and non-linear inequality constraints on parameters and I've had some success with it.
How to fix one coefficient and fit others using regression With respect to constraining coefficients to be within a range, a Bayesian approach to estimation is one means to accomplish this. In particular, one would rely on a Markov Chain Monte Carlo. First,
17,317
How to fix one coefficient and fit others using regression
I'm not familiar with LASSO or glmnet, but lavaan (short for "latent variable analysis") facilitates multiple regression models with both equality constraints and single-bounded inequality constraints (see the table on page 7 of this PDF, "lavaan: An R package for structural equation modeling"). I don't know if you could have both upper and lower bounds on the coefficient, but maybe you could add each bound with separate lines, e.g: Coefficient>.49999999 Coefficient<1.0000001 Of course, if you're standardizing everything before fitting the model, you shouldn't have to worry about imposing an upper bound of 1 on your regression coefficients anyway. I'd say you're better off omitting it in this case, just in case something goes wrong! (lavaan is still in beta after all...I've seen some slightly fishy results in my own limited use of it thus far.)
How to fix one coefficient and fit others using regression
I'm not familiar with LASSO or glmnet, but lavaan (short for "latent variable analysis") facilitates multiple regression models with both equality constraints and single-bounded inequality constraints
How to fix one coefficient and fit others using regression I'm not familiar with LASSO or glmnet, but lavaan (short for "latent variable analysis") facilitates multiple regression models with both equality constraints and single-bounded inequality constraints (see the table on page 7 of this PDF, "lavaan: An R package for structural equation modeling"). I don't know if you could have both upper and lower bounds on the coefficient, but maybe you could add each bound with separate lines, e.g: Coefficient>.49999999 Coefficient<1.0000001 Of course, if you're standardizing everything before fitting the model, you shouldn't have to worry about imposing an upper bound of 1 on your regression coefficients anyway. I'd say you're better off omitting it in this case, just in case something goes wrong! (lavaan is still in beta after all...I've seen some slightly fishy results in my own limited use of it thus far.)
How to fix one coefficient and fit others using regression I'm not familiar with LASSO or glmnet, but lavaan (short for "latent variable analysis") facilitates multiple regression models with both equality constraints and single-bounded inequality constraints
17,318
Does applying ARMA-GARCH require stationarity?
Copying from the abstract of Engle's original paper: "These are mean zero, serially uncorrelated processes with nonconstant variances conditional on the past, but constant unconditional variances. For such processes, the recent past gives information about the one-period forecast variance". Continuing with the references, as the author who introduced GARCH shows (Bollerslev, Tim (1986). "Generalized Autoregressive Conditional Heteroskedasticity", Journal of Econometrics, 31:307-327) for the GARCH(1,1) process, it suffices that $\alpha_1 + \beta_1 <1$ for 2nd-order stationarity. Stationarity (the one needed for estimation procedures), is defined relative to the unconditional distribution and moments. ADDENDUM To summarize here discussion in the comments, the GARCH modeling approach is an ingenious way to model suspected heteroskedasticity over time, i.e. of some form of heterogeneity of the process (which would render the process non-stationary) as an observed feature that comes from the existence of memory of the process, in essence inducing stationarity at the unconditional level. In other words, we took our two "great opponents" in stochastic process analysis (heterogeneity and memory), and used the one to neutralize the other -and this is indeed an inspired strategy.
Does applying ARMA-GARCH require stationarity?
Copying from the abstract of Engle's original paper: "These are mean zero, serially uncorrelated processes with nonconstant variances conditional on the past, but constant unconditional variances. For
Does applying ARMA-GARCH require stationarity? Copying from the abstract of Engle's original paper: "These are mean zero, serially uncorrelated processes with nonconstant variances conditional on the past, but constant unconditional variances. For such processes, the recent past gives information about the one-period forecast variance". Continuing with the references, as the author who introduced GARCH shows (Bollerslev, Tim (1986). "Generalized Autoregressive Conditional Heteroskedasticity", Journal of Econometrics, 31:307-327) for the GARCH(1,1) process, it suffices that $\alpha_1 + \beta_1 <1$ for 2nd-order stationarity. Stationarity (the one needed for estimation procedures), is defined relative to the unconditional distribution and moments. ADDENDUM To summarize here discussion in the comments, the GARCH modeling approach is an ingenious way to model suspected heteroskedasticity over time, i.e. of some form of heterogeneity of the process (which would render the process non-stationary) as an observed feature that comes from the existence of memory of the process, in essence inducing stationarity at the unconditional level. In other words, we took our two "great opponents" in stochastic process analysis (heterogeneity and memory), and used the one to neutralize the other -and this is indeed an inspired strategy.
Does applying ARMA-GARCH require stationarity? Copying from the abstract of Engle's original paper: "These are mean zero, serially uncorrelated processes with nonconstant variances conditional on the past, but constant unconditional variances. For
17,319
Does applying ARMA-GARCH require stationarity?
Yes the the series should be stationary. GARCH models are actually white noise processes with not trivial dependence structure. Classical GARCH(1,1) model is defined as $$r_t=\sigma_t\varepsilon_t,$$ with $$\sigma_t^2=\alpha_0+\alpha_1\varepsilon_{t-1}^2+\beta_1\sigma_{t-1}^2,$$ where $\varepsilon_t$ are independent standard normal variables with unit variance. Then $$Er_t=EE(r_t|\varepsilon_{t-1},\varepsilon_{t-2},...)=E\sigma_tE(\varepsilon_t|\varepsilon_{t-1},\varepsilon_{t-2},...)=0$$ and $$Er_tr_{t-h}=EE(r_tr_{t-h}|\varepsilon_{t-1},\varepsilon_{t-2},...)=Er_{t-h}\sigma_{t}E(\varepsilon_t|\varepsilon_{t-1},\varepsilon_{t-2},...)=0$$ for $h>0$. Hence $r_t$ is a white noise process. However it is possible to show that $r_t^2$ is actually a $ARMA(1,1)$ process. So GARCH(1,1) is stationary process, yet has non-constant conditional variance.
Does applying ARMA-GARCH require stationarity?
Yes the the series should be stationary. GARCH models are actually white noise processes with not trivial dependence structure. Classical GARCH(1,1) model is defined as $$r_t=\sigma_t\varepsilon_t,$$
Does applying ARMA-GARCH require stationarity? Yes the the series should be stationary. GARCH models are actually white noise processes with not trivial dependence structure. Classical GARCH(1,1) model is defined as $$r_t=\sigma_t\varepsilon_t,$$ with $$\sigma_t^2=\alpha_0+\alpha_1\varepsilon_{t-1}^2+\beta_1\sigma_{t-1}^2,$$ where $\varepsilon_t$ are independent standard normal variables with unit variance. Then $$Er_t=EE(r_t|\varepsilon_{t-1},\varepsilon_{t-2},...)=E\sigma_tE(\varepsilon_t|\varepsilon_{t-1},\varepsilon_{t-2},...)=0$$ and $$Er_tr_{t-h}=EE(r_tr_{t-h}|\varepsilon_{t-1},\varepsilon_{t-2},...)=Er_{t-h}\sigma_{t}E(\varepsilon_t|\varepsilon_{t-1},\varepsilon_{t-2},...)=0$$ for $h>0$. Hence $r_t$ is a white noise process. However it is possible to show that $r_t^2$ is actually a $ARMA(1,1)$ process. So GARCH(1,1) is stationary process, yet has non-constant conditional variance.
Does applying ARMA-GARCH require stationarity? Yes the the series should be stationary. GARCH models are actually white noise processes with not trivial dependence structure. Classical GARCH(1,1) model is defined as $$r_t=\sigma_t\varepsilon_t,$$
17,320
Does applying ARMA-GARCH require stationarity?
For anyone who is wondering about this question still, i will clarify - Volatility clustering does not at all imply that the series is non-stationary. It would suggest that there is a shifting conditional variance regime - which may still satisfy constancy of the unconditional distribution. The GARCH(1,1) model of Bollerslev is not weakly stationary when $\alpha_{1}+\beta>1$, however it is actually still stricktly stationary for a much larger range, Nelson 1990. Further Rahbek & Jensen 2004 (Asymptotic inference in the non-stationary GARCH), showed that the ML estimator of $\alpha_{1}$ and $\beta$ is consistent and asymptotically normal for any parameter specification that ensure the model is non-stationary. Combining this with the results of Nelson 1990 (all weak or strict stationary GARCH(1,1) models have MLE estimator as consistent and asymptotically normal), suggests that any parameter combination whatsoever of $\alpha_{1}$ and $\beta>1$ will have consistent and Asymptotically normal estimators. It is important to note however that if the GARCH(1,1) model is non stationary, the constant term in the conditional variance is not estimated consistently. Regardless, this suggests that you do not have to worry about stationarity before estimating the GARCH model. You do however have to wonder whether it seems to have a symmetric distribution, and whether the series has high persistence, as this is not allowed in the classical GARCH(1,1) model. When you have estimated the model it is of interest to test whether $\alpha_{1}+\beta=1$ if you are working with financial timeseries, since this would imply a trending conditional variance which is hard to immagine being a behavioral tendency amongst investors. Testing this however can be done with a normal LR test. Stationarity is fairly misunderstood, and is only partially connected to whether the variance or mean seems to be ocationally changing - as this can still ocour while the process maintains a constant unconditional distribution. The reason you may think that the seeming shifts in variance may cause a departure from stationarity, is because such a thing as permanent levelshift in the variance equation (or the mean equation) would by definition break stationarity. But if the changes are caused by the dynamic specification of the model, it may still be stationary even though the mean is impossible to identify and the volatility constantly changes. Another Beautiful example of this is the DAR(1,1) model introduced by Ling in 2002.
Does applying ARMA-GARCH require stationarity?
For anyone who is wondering about this question still, i will clarify - Volatility clustering does not at all imply that the series is non-stationary. It would suggest that there is a shifting conditi
Does applying ARMA-GARCH require stationarity? For anyone who is wondering about this question still, i will clarify - Volatility clustering does not at all imply that the series is non-stationary. It would suggest that there is a shifting conditional variance regime - which may still satisfy constancy of the unconditional distribution. The GARCH(1,1) model of Bollerslev is not weakly stationary when $\alpha_{1}+\beta>1$, however it is actually still stricktly stationary for a much larger range, Nelson 1990. Further Rahbek & Jensen 2004 (Asymptotic inference in the non-stationary GARCH), showed that the ML estimator of $\alpha_{1}$ and $\beta$ is consistent and asymptotically normal for any parameter specification that ensure the model is non-stationary. Combining this with the results of Nelson 1990 (all weak or strict stationary GARCH(1,1) models have MLE estimator as consistent and asymptotically normal), suggests that any parameter combination whatsoever of $\alpha_{1}$ and $\beta>1$ will have consistent and Asymptotically normal estimators. It is important to note however that if the GARCH(1,1) model is non stationary, the constant term in the conditional variance is not estimated consistently. Regardless, this suggests that you do not have to worry about stationarity before estimating the GARCH model. You do however have to wonder whether it seems to have a symmetric distribution, and whether the series has high persistence, as this is not allowed in the classical GARCH(1,1) model. When you have estimated the model it is of interest to test whether $\alpha_{1}+\beta=1$ if you are working with financial timeseries, since this would imply a trending conditional variance which is hard to immagine being a behavioral tendency amongst investors. Testing this however can be done with a normal LR test. Stationarity is fairly misunderstood, and is only partially connected to whether the variance or mean seems to be ocationally changing - as this can still ocour while the process maintains a constant unconditional distribution. The reason you may think that the seeming shifts in variance may cause a departure from stationarity, is because such a thing as permanent levelshift in the variance equation (or the mean equation) would by definition break stationarity. But if the changes are caused by the dynamic specification of the model, it may still be stationary even though the mean is impossible to identify and the volatility constantly changes. Another Beautiful example of this is the DAR(1,1) model introduced by Ling in 2002.
Does applying ARMA-GARCH require stationarity? For anyone who is wondering about this question still, i will clarify - Volatility clustering does not at all imply that the series is non-stationary. It would suggest that there is a shifting conditi
17,321
Does applying ARMA-GARCH require stationarity?
Stationarity is a theoretical concept which is then modified to other forms like Weak Sense Stationarity which can be tested easily. Most of the tests like adf test as you have mentioned test for linear conditions only. the ARCH effects are made for series which do not have autocorrelation in the first order but there is dependence in the squared series. The ARMA-GARCH process you talk about, here the second order dependence is removed using the GARCH part and then any dependence in the linear terms is captured by the ARMA process. The way to go about is to check for the autocorrelation of the squared series, if there is dependence, then apply the GARCH models and check the residuals for any linear time series properties which can then be modelled using ARMA processes.
Does applying ARMA-GARCH require stationarity?
Stationarity is a theoretical concept which is then modified to other forms like Weak Sense Stationarity which can be tested easily. Most of the tests like adf test as you have mentioned test for line
Does applying ARMA-GARCH require stationarity? Stationarity is a theoretical concept which is then modified to other forms like Weak Sense Stationarity which can be tested easily. Most of the tests like adf test as you have mentioned test for linear conditions only. the ARCH effects are made for series which do not have autocorrelation in the first order but there is dependence in the squared series. The ARMA-GARCH process you talk about, here the second order dependence is removed using the GARCH part and then any dependence in the linear terms is captured by the ARMA process. The way to go about is to check for the autocorrelation of the squared series, if there is dependence, then apply the GARCH models and check the residuals for any linear time series properties which can then be modelled using ARMA processes.
Does applying ARMA-GARCH require stationarity? Stationarity is a theoretical concept which is then modified to other forms like Weak Sense Stationarity which can be tested easily. Most of the tests like adf test as you have mentioned test for line
17,322
Is this an acceptable way to analyse mixed effect models with lme4 in R?
Your question(s) is a little bit "big", so I'll start with some general comments and tips. Some background reading and useful packages You should probably take a look at some of the tutorial introductions to using mixed models, I would recommend starting with Baayen et al (2008) -- Baayen is the author of languageR. Barr et al (2013) discuss some issues with random effects structure, and Ben Bolker is one of the current developers of lme4. Baayen et al is especially good for your questions because they spend a lot of time discussing the use of bootstrapping / permutation tests (the stuff behind mcp.fnc). Literature Baayen, R.H., D. Davidson und D. Bates (2008). Mixed-effects modeling with crossed random effects for subjects and items. Journal of Memory and Language, 59(390–412). Barr, Dale J, R. Levy, C. Scheepers und H. J. Tily (2013). Random effects structure for confirmatory hypothesis testing: Keep it maximal. Journal of Memory and Language, 68:255– 278. Bolker, Benjamin M, M. E. Brooks, C. J. Clark, S. W. Geange, J. R. Poulsen, M. H. H. Stevens und J.-S. S. White (2009). Generalized linear mixed models: a practical guide for ecology and evolution. Trends Ecol Evol, 24(3):127–35. Florian Jaeger also has a bunch of stuff on the practical side of mixed models on his lab's blog. There are also a number of useful R packages for visualizing and testing mixed models, like lmerTest and effects. The effects package is especially nice because it lets you plot the linear regression and confidence intervals going on behind the scenes. Goodness of fit and comparing models $p$-values are a really lousy way to compare mixed models (and are generally not a great method for anything). There is a reason why Doug Bates (the original author of lme4) does not feel it is necessary to include them. If you really want to go that way (and I beg you not to), the aforementioned lmerTest provides some additional facilities for calculating and dealing with them. Better ways of comparing models are log-likelihood or the various information-theoretic criteria like AIC and BIC. For AIC and BIC, the general rule is "smaller is better", but you have to be careful there because they both penalize for more model degrees of freedom and there is no "absolute" good or bad value. To get a nice summary of AIC and log-likelihood models, you can use the anova() function, which has been overloaded to accept mer objects. Please note that the $\chi^2$ values given their are only valid for comparisons between nested models. Nonetheless, the output is quite nice for being so tabular, even for other comparisons. For nested models, you have a nice $\chi^2$ test and don't need $p$-values to directly compare two models. The downside to this is that it's not immediately clear just how good your fit is. For looking at the individual effects (i.e. the stuff you would see in a traditional ANOVA), you should look at the $t$-values for the fixed effects in the models (which are part of the summary() if I'm not mistaken). Generally, anything $|t|>2$ is considered good (more details in Baayen et al). You can also access the fixed effects directly with the helper function fixef(). You should also make sure that none of your fixed effects are too strongly correlated -- multicollinearity violates model assumptions. Florian Jaeger has written a bit on this, as well as a few possible solutions. Multiple comparisons I'll address your question #4 a bit more directly. The answer is basically the same as good practice with traditional ANOVA, unfortunately this seems to be a spot where there is a great deal of uncertainty for most researchers. (It's the same as traditional ANOVA because both linear mixed-effects models and ANOVA are based on the general linear model, it's just that mixed models have an extra term for the random effects.) If you're assuming that the time windows make a difference and want to compare the effects of time, you should include time in your model. This, incidentally, will also provide a convenient way for you to judge whether time made a difference: is there a main (fixed) effect for time? The downside to going this route is that your model will get a LOT more complex and the single "super" model with time as a paramater will probably take longer to compute than three smaller models without time as a paramater. Indeed, the classic tutorial example for mixed models is sleepstudy which uses time as a paramater. I couldn't quite tell whether the different characteristics are meant to be predictors or dependent variables. If they're meant to be predictors, you could throw them all into one model and see which one has the largest $t$-value, but this model would be incredibly complex, even if you don't allow interactions, and take a long time to compute. The faster, and potentially easier way, would be to compute different models for each predictor. I would recommend using a foreach loop to parallelize it across as many cores as you have -- lme4 doesn't yet do its matrix operations in parallel, so you can compute a different model on each core in parallel. (See the short introduction here) Then, you can compare the AIC and BIC of each model to find which predictor is best. (They're not nested in this case, so you'$\chi^2$ statistic.) If your characteristics are the dependent variable, then you will have to compute different models anyway, and then you can use the AIC and BIC to compare the results.
Is this an acceptable way to analyse mixed effect models with lme4 in R?
Your question(s) is a little bit "big", so I'll start with some general comments and tips. Some background reading and useful packages You should probably take a look at some of the tutorial introduc
Is this an acceptable way to analyse mixed effect models with lme4 in R? Your question(s) is a little bit "big", so I'll start with some general comments and tips. Some background reading and useful packages You should probably take a look at some of the tutorial introductions to using mixed models, I would recommend starting with Baayen et al (2008) -- Baayen is the author of languageR. Barr et al (2013) discuss some issues with random effects structure, and Ben Bolker is one of the current developers of lme4. Baayen et al is especially good for your questions because they spend a lot of time discussing the use of bootstrapping / permutation tests (the stuff behind mcp.fnc). Literature Baayen, R.H., D. Davidson und D. Bates (2008). Mixed-effects modeling with crossed random effects for subjects and items. Journal of Memory and Language, 59(390–412). Barr, Dale J, R. Levy, C. Scheepers und H. J. Tily (2013). Random effects structure for confirmatory hypothesis testing: Keep it maximal. Journal of Memory and Language, 68:255– 278. Bolker, Benjamin M, M. E. Brooks, C. J. Clark, S. W. Geange, J. R. Poulsen, M. H. H. Stevens und J.-S. S. White (2009). Generalized linear mixed models: a practical guide for ecology and evolution. Trends Ecol Evol, 24(3):127–35. Florian Jaeger also has a bunch of stuff on the practical side of mixed models on his lab's blog. There are also a number of useful R packages for visualizing and testing mixed models, like lmerTest and effects. The effects package is especially nice because it lets you plot the linear regression and confidence intervals going on behind the scenes. Goodness of fit and comparing models $p$-values are a really lousy way to compare mixed models (and are generally not a great method for anything). There is a reason why Doug Bates (the original author of lme4) does not feel it is necessary to include them. If you really want to go that way (and I beg you not to), the aforementioned lmerTest provides some additional facilities for calculating and dealing with them. Better ways of comparing models are log-likelihood or the various information-theoretic criteria like AIC and BIC. For AIC and BIC, the general rule is "smaller is better", but you have to be careful there because they both penalize for more model degrees of freedom and there is no "absolute" good or bad value. To get a nice summary of AIC and log-likelihood models, you can use the anova() function, which has been overloaded to accept mer objects. Please note that the $\chi^2$ values given their are only valid for comparisons between nested models. Nonetheless, the output is quite nice for being so tabular, even for other comparisons. For nested models, you have a nice $\chi^2$ test and don't need $p$-values to directly compare two models. The downside to this is that it's not immediately clear just how good your fit is. For looking at the individual effects (i.e. the stuff you would see in a traditional ANOVA), you should look at the $t$-values for the fixed effects in the models (which are part of the summary() if I'm not mistaken). Generally, anything $|t|>2$ is considered good (more details in Baayen et al). You can also access the fixed effects directly with the helper function fixef(). You should also make sure that none of your fixed effects are too strongly correlated -- multicollinearity violates model assumptions. Florian Jaeger has written a bit on this, as well as a few possible solutions. Multiple comparisons I'll address your question #4 a bit more directly. The answer is basically the same as good practice with traditional ANOVA, unfortunately this seems to be a spot where there is a great deal of uncertainty for most researchers. (It's the same as traditional ANOVA because both linear mixed-effects models and ANOVA are based on the general linear model, it's just that mixed models have an extra term for the random effects.) If you're assuming that the time windows make a difference and want to compare the effects of time, you should include time in your model. This, incidentally, will also provide a convenient way for you to judge whether time made a difference: is there a main (fixed) effect for time? The downside to going this route is that your model will get a LOT more complex and the single "super" model with time as a paramater will probably take longer to compute than three smaller models without time as a paramater. Indeed, the classic tutorial example for mixed models is sleepstudy which uses time as a paramater. I couldn't quite tell whether the different characteristics are meant to be predictors or dependent variables. If they're meant to be predictors, you could throw them all into one model and see which one has the largest $t$-value, but this model would be incredibly complex, even if you don't allow interactions, and take a long time to compute. The faster, and potentially easier way, would be to compute different models for each predictor. I would recommend using a foreach loop to parallelize it across as many cores as you have -- lme4 doesn't yet do its matrix operations in parallel, so you can compute a different model on each core in parallel. (See the short introduction here) Then, you can compare the AIC and BIC of each model to find which predictor is best. (They're not nested in this case, so you'$\chi^2$ statistic.) If your characteristics are the dependent variable, then you will have to compute different models anyway, and then you can use the AIC and BIC to compare the results.
Is this an acceptable way to analyse mixed effect models with lme4 in R? Your question(s) is a little bit "big", so I'll start with some general comments and tips. Some background reading and useful packages You should probably take a look at some of the tutorial introduc
17,323
ROC curve crossing the diagonal
You get a nice symmetric ROC plot only when standard deviations for both outcomes are the same. If they are rather different then you may get exactly the result you describe. The following Mathematica code demonstrates this. We assume that a target yields a normal distribution in response space, and that noise also yields a normal distribution, but a displaced one. The ROC parameters are determined by the area below the Gaussian curves to the left or right of a decision criterion. Varying this criterion describes the ROC curve. Manipulate[ ParametricPlot[{CDF[NormalDistribution[4, \[Sigma]], c], CDF[NormalDistribution[0, 3], c] }, {c, -10, 10}, Frame -> True, Axes -> None, PlotRange -> {{0, 1}, {0, 1}}, Epilog -> Line[{{0, 0}, {1, 1}}]], {{\[Sigma], 3}, 0.1, 10, Appearance -> "Labeled"}] This is with equal standard deviations: This is with rather distinct ones: or with a few more parameters to play with: Manipulate[ ParametricPlot[{CDF[NormalDistribution[\[Mu]1, \[Sigma]1], c], CDF[NormalDistribution[\[Mu]2, \[Sigma]2], c]}, {c, -100, 100}, Frame -> True, Axes -> None, PlotRange -> {{0, 1}, {0, 1}}, Epilog -> Line[{{0, 0}, {1, 1}}]], {{\[Mu]1, 0}, 0, 10, Appearance -> "Labeled"}, {{\[Sigma]1, 4}, 0.1, 20, Appearance -> "Labeled"}, {{\[Mu]2, 5}, 0, 10, Appearance -> "Labeled"}, {{\[Sigma]2, 4}, 0.1, 20, Appearance -> "Labeled"}]
ROC curve crossing the diagonal
You get a nice symmetric ROC plot only when standard deviations for both outcomes are the same. If they are rather different then you may get exactly the result you describe. The following Mathematica
ROC curve crossing the diagonal You get a nice symmetric ROC plot only when standard deviations for both outcomes are the same. If they are rather different then you may get exactly the result you describe. The following Mathematica code demonstrates this. We assume that a target yields a normal distribution in response space, and that noise also yields a normal distribution, but a displaced one. The ROC parameters are determined by the area below the Gaussian curves to the left or right of a decision criterion. Varying this criterion describes the ROC curve. Manipulate[ ParametricPlot[{CDF[NormalDistribution[4, \[Sigma]], c], CDF[NormalDistribution[0, 3], c] }, {c, -10, 10}, Frame -> True, Axes -> None, PlotRange -> {{0, 1}, {0, 1}}, Epilog -> Line[{{0, 0}, {1, 1}}]], {{\[Sigma], 3}, 0.1, 10, Appearance -> "Labeled"}] This is with equal standard deviations: This is with rather distinct ones: or with a few more parameters to play with: Manipulate[ ParametricPlot[{CDF[NormalDistribution[\[Mu]1, \[Sigma]1], c], CDF[NormalDistribution[\[Mu]2, \[Sigma]2], c]}, {c, -100, 100}, Frame -> True, Axes -> None, PlotRange -> {{0, 1}, {0, 1}}, Epilog -> Line[{{0, 0}, {1, 1}}]], {{\[Mu]1, 0}, 0, 10, Appearance -> "Labeled"}, {{\[Sigma]1, 4}, 0.1, 20, Appearance -> "Labeled"}, {{\[Mu]2, 5}, 0, 10, Appearance -> "Labeled"}, {{\[Sigma]2, 4}, 0.1, 20, Appearance -> "Labeled"}]
ROC curve crossing the diagonal You get a nice symmetric ROC plot only when standard deviations for both outcomes are the same. If they are rather different then you may get exactly the result you describe. The following Mathematica
17,324
ROC curve crossing the diagonal
(The answers by @Sjoerd C. de Vries and @Hrishekesh Ganu are correct. I thought I could nonetheless present the ideas another way, which may help some people.) You can get a ROC like that if your model is misspecified. Consider the example below (coded in R), which is adapted from my answer here: How to use boxplots to find the point where values are more likely to come from different conditions? ## data Cond.1 = c(2.9, 3.0, 3.1, 3.1, 3.1, 3.3, 3.3, 3.4, 3.4, 3.4, 3.5, 3.5, 3.6, 3.7, 3.7, 3.8, 3.8, 3.8, 3.8, 3.9, 4.0, 4.0, 4.1, 4.1, 4.2, 4.4, 4.5, 4.5, 4.5, 4.6, 4.6, 4.6, 4.7, 4.8, 4.9, 4.9, 5.5, 5.5, 5.7) Cond.2 = c(2.3, 2.4, 2.6, 3.1, 3.7, 3.7, 3.8, 4.0, 4.2, 4.8, 4.9, 5.5, 5.5, 5.5, 5.7, 5.8, 5.9, 5.9, 6.0, 6.0, 6.1, 6.1, 6.3, 6.5, 6.7, 6.8, 6.9, 7.1, 7.1, 7.1, 7.2, 7.2, 7.4, 7.5, 7.6, 7.6, 10, 10.1, 12.5) dat = stack(list(cond1=Cond.1, cond2=Cond.2)) ord = order(dat$values) dat = dat[ord,] # now the data are sorted ## logistic regression models lr.model1 = glm(ind~values, dat, family="binomial") # w/o a squared term lr.model2 = glm(ind~values+I(values^2), dat, family="binomial") # w/ a squared term lr.preds1 = predict(lr.model1, data.frame(values=seq(2.3,12.5,by=.1)), type="response") lr.preds2 = predict(lr.model2, data.frame(values=seq(2.3,12.5,by=.1)), type="response") ## here I plot the data & the 2 models windows() with(dat, plot(values, ifelse(ind=="cond2",1,0), ylab="predicted probability of condition2")) lines(seq(2.3,12.5,by=.1), lr.preds1, lwd=2, col="red") lines(seq(2.3,12.5,by=.1), lr.preds2, lwd=2, col="blue") legend("bottomright", legend=c("model 1", "model 2"), lwd=2, col=c("red", "blue")) It's easy to see that the red model is missing the structure of the data. We can see what the ROC curves look like when plotted below: library(ROCR) # we'll use this package to make the ROC curve ## these are necessary to make the ROC curves pred1 = with(dat, prediction(fitted(lr.model1), ind)) pred2 = with(dat, prediction(fitted(lr.model2), ind)) perf1 = performance(pred1, "tpr", "fpr") perf2 = performance(pred2, "tpr", "fpr") ## here I plot the ROC curves windows() plot(perf1, col="red", lwd=2) plot(perf2, col="blue", lwd=2, add=T) abline(0,1, col="gray") legend("bottomright", legend=c("model 1", "model 2"), lwd=2, col=c("red", "blue")) We can now see that, for the misspecified (red) model, when the false positive rate becomes greater than $80\%$, the false positive rate increases more quickly than the true positive rate. Looking at the models above, we see that that point is where the red and blue lines cross at the lower left.
ROC curve crossing the diagonal
(The answers by @Sjoerd C. de Vries and @Hrishekesh Ganu are correct. I thought I could nonetheless present the ideas another way, which may help some people.) You can get a ROC like that if your m
ROC curve crossing the diagonal (The answers by @Sjoerd C. de Vries and @Hrishekesh Ganu are correct. I thought I could nonetheless present the ideas another way, which may help some people.) You can get a ROC like that if your model is misspecified. Consider the example below (coded in R), which is adapted from my answer here: How to use boxplots to find the point where values are more likely to come from different conditions? ## data Cond.1 = c(2.9, 3.0, 3.1, 3.1, 3.1, 3.3, 3.3, 3.4, 3.4, 3.4, 3.5, 3.5, 3.6, 3.7, 3.7, 3.8, 3.8, 3.8, 3.8, 3.9, 4.0, 4.0, 4.1, 4.1, 4.2, 4.4, 4.5, 4.5, 4.5, 4.6, 4.6, 4.6, 4.7, 4.8, 4.9, 4.9, 5.5, 5.5, 5.7) Cond.2 = c(2.3, 2.4, 2.6, 3.1, 3.7, 3.7, 3.8, 4.0, 4.2, 4.8, 4.9, 5.5, 5.5, 5.5, 5.7, 5.8, 5.9, 5.9, 6.0, 6.0, 6.1, 6.1, 6.3, 6.5, 6.7, 6.8, 6.9, 7.1, 7.1, 7.1, 7.2, 7.2, 7.4, 7.5, 7.6, 7.6, 10, 10.1, 12.5) dat = stack(list(cond1=Cond.1, cond2=Cond.2)) ord = order(dat$values) dat = dat[ord,] # now the data are sorted ## logistic regression models lr.model1 = glm(ind~values, dat, family="binomial") # w/o a squared term lr.model2 = glm(ind~values+I(values^2), dat, family="binomial") # w/ a squared term lr.preds1 = predict(lr.model1, data.frame(values=seq(2.3,12.5,by=.1)), type="response") lr.preds2 = predict(lr.model2, data.frame(values=seq(2.3,12.5,by=.1)), type="response") ## here I plot the data & the 2 models windows() with(dat, plot(values, ifelse(ind=="cond2",1,0), ylab="predicted probability of condition2")) lines(seq(2.3,12.5,by=.1), lr.preds1, lwd=2, col="red") lines(seq(2.3,12.5,by=.1), lr.preds2, lwd=2, col="blue") legend("bottomright", legend=c("model 1", "model 2"), lwd=2, col=c("red", "blue")) It's easy to see that the red model is missing the structure of the data. We can see what the ROC curves look like when plotted below: library(ROCR) # we'll use this package to make the ROC curve ## these are necessary to make the ROC curves pred1 = with(dat, prediction(fitted(lr.model1), ind)) pred2 = with(dat, prediction(fitted(lr.model2), ind)) perf1 = performance(pred1, "tpr", "fpr") perf2 = performance(pred2, "tpr", "fpr") ## here I plot the ROC curves windows() plot(perf1, col="red", lwd=2) plot(perf2, col="blue", lwd=2, add=T) abline(0,1, col="gray") legend("bottomright", legend=c("model 1", "model 2"), lwd=2, col=c("red", "blue")) We can now see that, for the misspecified (red) model, when the false positive rate becomes greater than $80\%$, the false positive rate increases more quickly than the true positive rate. Looking at the models above, we see that that point is where the red and blue lines cross at the lower left.
ROC curve crossing the diagonal (The answers by @Sjoerd C. de Vries and @Hrishekesh Ganu are correct. I thought I could nonetheless present the ideas another way, which may help some people.) You can get a ROC like that if your m
17,325
ROC curve crossing the diagonal
Having a string of negative instances in the part of the curve with high FPR can create this kind of a curve. This is ok as long as you are using the right algorithm for generating the ROC curve. The condition where you have a set of 2m points half of which are positive and half are negative-all having exactly the same score for your model is tricky. If while sorting the points based on the score (standard procedure in plotting ROC) all the negative examples are encountered first, this will cause your ROC curve to stay flat and move to the right.This paper talks about how to take care of such issues: Fawcett| Plotting ROC curves
ROC curve crossing the diagonal
Having a string of negative instances in the part of the curve with high FPR can create this kind of a curve. This is ok as long as you are using the right algorithm for generating the ROC curve. The
ROC curve crossing the diagonal Having a string of negative instances in the part of the curve with high FPR can create this kind of a curve. This is ok as long as you are using the right algorithm for generating the ROC curve. The condition where you have a set of 2m points half of which are positive and half are negative-all having exactly the same score for your model is tricky. If while sorting the points based on the score (standard procedure in plotting ROC) all the negative examples are encountered first, this will cause your ROC curve to stay flat and move to the right.This paper talks about how to take care of such issues: Fawcett| Plotting ROC curves
ROC curve crossing the diagonal Having a string of negative instances in the part of the curve with high FPR can create this kind of a curve. This is ok as long as you are using the right algorithm for generating the ROC curve. The
17,326
Assumptions of generalised linear model
I think trying to think of this as a generalized linear model is overkill. What you have is a plain old regression model. More specifically, because you have some categorical explanatory variables, and a continuous EV, but no interactions between them, this could also be called a classic ANCOVA. I would say that #3 is not really an assumption here that you need to worry about. Nor, for that matter, do you need to really worry about #2. Instead, I would supplant these with two different assumptions: 2'. Homogeneity of variance 3'. Normality of residuals Furthermore, #4 is an important thing to check, but I don't really think of it as an assumption per se. Lets think about how assumptions can be checked. Independence is often 'checked' firstly by thinking about what the data stand for and how they were collected. In addition, it can be checked using things like a runs test, Durbin-Watson test, or examining the pattern of autocorrelations--you can also look at partial autocorrelations. (Note that, these can only be assessed relative to your continuous covariate.) With primarily categorical explanatory variables, homogeneity of variance can be checked by calculating the variance at each level of your factors. Having computed these, there are several tests used to check if they are about the same, primarily Levene's test, but also the Brown-Forsyth test. The $F_{max}$ test, also called Hartley's test is not recommended; if you would like a little more information about that I discuss it here. (Note that these tests can be applied to your categorical covariates unlike above.) For a continuous EV, I like to just plot my residuals against the continuous covariate and examine them visually to see if they spread out further to one side or the other. The normality of the residuals can be assessed via some tests, like the Shapiro-Wilk, or the Kolmogorov-Smirnov tests, but is often best assessed visually via a qq-plot. (Note that this assumption is generally the least important of the set; if it is not met, your beta estimates will still be unbiased, but your p-values will be inaccurate.) There are several ways to assess the influence of your individual observations. It is possible to get numerical values that index this, but my favorite way, if you can do it, is to jackknife your data. That is, you drop each data point in turn and re-fit your model. Then you can examine how much your betas bounce around if that observation were not a part of your dataset. This measure is called dfbeta. This requires a bit of programming, but there are standard ways that software can often compute for you automatically. These include leverage and Cook's distance. Regarding your question as originally stated, if you want to know more about link functions and the generalized linear model, I discussed that fairly extensively here. Basically, the most important thing to consider in order to select an appropriate link function is the nature of your response distribution; since you believe $Y$ is Gaussian, the identity link is appropriate, and you can just think of this situation using standard ideas about regression models. Concerning the "correct scale of measurement of explanatory variables", I take you to be referring to Steven's levels of measurement (i.e., categorical, ordinal, interval & ratio). The first thing to realize is that regression methods (including GLiM's) do not make assumptions about the explanatory variables, instead, the manner in which you use your explanatory variables in your model reflects your beliefs about them. Furthermore, I tend to think Steven's levels are overplayed; for a more theoretical treatment of that topic, see here.
Assumptions of generalised linear model
I think trying to think of this as a generalized linear model is overkill. What you have is a plain old regression model. More specifically, because you have some categorical explanatory variables,
Assumptions of generalised linear model I think trying to think of this as a generalized linear model is overkill. What you have is a plain old regression model. More specifically, because you have some categorical explanatory variables, and a continuous EV, but no interactions between them, this could also be called a classic ANCOVA. I would say that #3 is not really an assumption here that you need to worry about. Nor, for that matter, do you need to really worry about #2. Instead, I would supplant these with two different assumptions: 2'. Homogeneity of variance 3'. Normality of residuals Furthermore, #4 is an important thing to check, but I don't really think of it as an assumption per se. Lets think about how assumptions can be checked. Independence is often 'checked' firstly by thinking about what the data stand for and how they were collected. In addition, it can be checked using things like a runs test, Durbin-Watson test, or examining the pattern of autocorrelations--you can also look at partial autocorrelations. (Note that, these can only be assessed relative to your continuous covariate.) With primarily categorical explanatory variables, homogeneity of variance can be checked by calculating the variance at each level of your factors. Having computed these, there are several tests used to check if they are about the same, primarily Levene's test, but also the Brown-Forsyth test. The $F_{max}$ test, also called Hartley's test is not recommended; if you would like a little more information about that I discuss it here. (Note that these tests can be applied to your categorical covariates unlike above.) For a continuous EV, I like to just plot my residuals against the continuous covariate and examine them visually to see if they spread out further to one side or the other. The normality of the residuals can be assessed via some tests, like the Shapiro-Wilk, or the Kolmogorov-Smirnov tests, but is often best assessed visually via a qq-plot. (Note that this assumption is generally the least important of the set; if it is not met, your beta estimates will still be unbiased, but your p-values will be inaccurate.) There are several ways to assess the influence of your individual observations. It is possible to get numerical values that index this, but my favorite way, if you can do it, is to jackknife your data. That is, you drop each data point in turn and re-fit your model. Then you can examine how much your betas bounce around if that observation were not a part of your dataset. This measure is called dfbeta. This requires a bit of programming, but there are standard ways that software can often compute for you automatically. These include leverage and Cook's distance. Regarding your question as originally stated, if you want to know more about link functions and the generalized linear model, I discussed that fairly extensively here. Basically, the most important thing to consider in order to select an appropriate link function is the nature of your response distribution; since you believe $Y$ is Gaussian, the identity link is appropriate, and you can just think of this situation using standard ideas about regression models. Concerning the "correct scale of measurement of explanatory variables", I take you to be referring to Steven's levels of measurement (i.e., categorical, ordinal, interval & ratio). The first thing to realize is that regression methods (including GLiM's) do not make assumptions about the explanatory variables, instead, the manner in which you use your explanatory variables in your model reflects your beliefs about them. Furthermore, I tend to think Steven's levels are overplayed; for a more theoretical treatment of that topic, see here.
Assumptions of generalised linear model I think trying to think of this as a generalized linear model is overkill. What you have is a plain old regression model. More specifically, because you have some categorical explanatory variables,
17,327
Random forest: how to handle new factor levels in test set?
If the test set has a lot of these points with new factor values then I'm not sure what the best approach is. If it is just a handful of points you might be able to get away with something fudgy like treating the errant factor levels as missing data and imputing them with whatever approach you see fit. The R implementation has a couple of ways to impute missing data, you just need to set these factor levels to NA to indicate they are missing.
Random forest: how to handle new factor levels in test set?
If the test set has a lot of these points with new factor values then I'm not sure what the best approach is. If it is just a handful of points you might be able to get away with something fudgy like
Random forest: how to handle new factor levels in test set? If the test set has a lot of these points with new factor values then I'm not sure what the best approach is. If it is just a handful of points you might be able to get away with something fudgy like treating the errant factor levels as missing data and imputing them with whatever approach you see fit. The R implementation has a couple of ways to impute missing data, you just need to set these factor levels to NA to indicate they are missing.
Random forest: how to handle new factor levels in test set? If the test set has a lot of these points with new factor values then I'm not sure what the best approach is. If it is just a handful of points you might be able to get away with something fudgy like
17,328
Random forest: how to handle new factor levels in test set?
King and Bonoit, this snippet can be useful to harmonize levels: for(attr in colnames(training)) { if (is.factor(training[[attr]])) { new.levels <- setdiff(levels(training[[attr]]), levels(testing[[attr]])) if ( length(new.levels) == 0 ) { print(paste(attr, '- no new levels')) } else { print(c(paste(attr, length(new.levels), 'of new levels, e.g.'), head(new.levels, 2))) levels(testing[[attr]]) <- union(levels(testing[[attr]]), levels(training[[attr]])) } } } It also prints which attributes are changed. I did not find a good way to write it more elegantly (with ldply or something). Any tips are appreciated.
Random forest: how to handle new factor levels in test set?
King and Bonoit, this snippet can be useful to harmonize levels: for(attr in colnames(training)) { if (is.factor(training[[attr]])) { new.levels <- setdiff(levels(training[[attr]]), levels(tes
Random forest: how to handle new factor levels in test set? King and Bonoit, this snippet can be useful to harmonize levels: for(attr in colnames(training)) { if (is.factor(training[[attr]])) { new.levels <- setdiff(levels(training[[attr]]), levels(testing[[attr]])) if ( length(new.levels) == 0 ) { print(paste(attr, '- no new levels')) } else { print(c(paste(attr, length(new.levels), 'of new levels, e.g.'), head(new.levels, 2))) levels(testing[[attr]]) <- union(levels(testing[[attr]]), levels(training[[attr]])) } } } It also prints which attributes are changed. I did not find a good way to write it more elegantly (with ldply or something). Any tips are appreciated.
Random forest: how to handle new factor levels in test set? King and Bonoit, this snippet can be useful to harmonize levels: for(attr in colnames(training)) { if (is.factor(training[[attr]])) { new.levels <- setdiff(levels(training[[attr]]), levels(tes
17,329
Random forest: how to handle new factor levels in test set?
Here's some code I wrote that addresses @King's response above. It fixed the error: # loops through factors and standardizes the levels for (f in 1:length(names(trainingDataSet))) { if (levels(testDataSet[,f]) > levels(trainingDataSet[,f])) { levels(testDataSet[,f]) = levels(trainingDataSet[,f]) } else { levels(trainingDataSetSMOTEpred[,f]) = levels(testDataSet[,f]) } }
Random forest: how to handle new factor levels in test set?
Here's some code I wrote that addresses @King's response above. It fixed the error: # loops through factors and standardizes the levels for (f in 1:length(names(trainingDataSet))) { if (levels(tes
Random forest: how to handle new factor levels in test set? Here's some code I wrote that addresses @King's response above. It fixed the error: # loops through factors and standardizes the levels for (f in 1:length(names(trainingDataSet))) { if (levels(testDataSet[,f]) > levels(trainingDataSet[,f])) { levels(testDataSet[,f]) = levels(trainingDataSet[,f]) } else { levels(trainingDataSetSMOTEpred[,f]) = levels(testDataSet[,f]) } }
Random forest: how to handle new factor levels in test set? Here's some code I wrote that addresses @King's response above. It fixed the error: # loops through factors and standardizes the levels for (f in 1:length(names(trainingDataSet))) { if (levels(tes
17,330
Random forest: how to handle new factor levels in test set?
Test and training set should be combined as one set and then change the levels of the training set. My codes are: totalData <- rbind(trainData, testData) for (f in 1:length(names(totalData))) { levels(trainData[, f]) <- levels(totalData[, f]) } This works in any cases where the number of levels in test are more or less than training.
Random forest: how to handle new factor levels in test set?
Test and training set should be combined as one set and then change the levels of the training set. My codes are: totalData <- rbind(trainData, testData) for (f in 1:length(names(totalData))) { lev
Random forest: how to handle new factor levels in test set? Test and training set should be combined as one set and then change the levels of the training set. My codes are: totalData <- rbind(trainData, testData) for (f in 1:length(names(totalData))) { levels(trainData[, f]) <- levels(totalData[, f]) } This works in any cases where the number of levels in test are more or less than training.
Random forest: how to handle new factor levels in test set? Test and training set should be combined as one set and then change the levels of the training set. My codes are: totalData <- rbind(trainData, testData) for (f in 1:length(names(totalData))) { lev
17,331
Random forest: how to handle new factor levels in test set?
I have a lousy workaround when I use randomForest in R. It's probably not theoretically sound, but it gets the thing running. levels(testSet$Cat_2) = levels(trainingSet$Cat_2) or the other way round. Basically, it just gives tells R that it's a valid value just that there are 0 cases; so stop bugging me about the error. I'm not smart enough to code it such that it automatically performs the action for all categorical features. Send me the code if you know how...
Random forest: how to handle new factor levels in test set?
I have a lousy workaround when I use randomForest in R. It's probably not theoretically sound, but it gets the thing running. levels(testSet$Cat_2) = levels(trainingSet$Cat_2) or the other way round.
Random forest: how to handle new factor levels in test set? I have a lousy workaround when I use randomForest in R. It's probably not theoretically sound, but it gets the thing running. levels(testSet$Cat_2) = levels(trainingSet$Cat_2) or the other way round. Basically, it just gives tells R that it's a valid value just that there are 0 cases; so stop bugging me about the error. I'm not smart enough to code it such that it automatically performs the action for all categorical features. Send me the code if you know how...
Random forest: how to handle new factor levels in test set? I have a lousy workaround when I use randomForest in R. It's probably not theoretically sound, but it gets the thing running. levels(testSet$Cat_2) = levels(trainingSet$Cat_2) or the other way round.
17,332
Random forest: how to handle new factor levels in test set?
If your test data has some levels that are an insignificant percentage of the population, but are just messing up your ability to make the model, here is an elegant way to remove the extraneous levels from the test set: uniquetrain <- unique( train$category) test <- test[test$category %in% uniquetrain,]
Random forest: how to handle new factor levels in test set?
If your test data has some levels that are an insignificant percentage of the population, but are just messing up your ability to make the model, here is an elegant way to remove the extraneous level
Random forest: how to handle new factor levels in test set? If your test data has some levels that are an insignificant percentage of the population, but are just messing up your ability to make the model, here is an elegant way to remove the extraneous levels from the test set: uniquetrain <- unique( train$category) test <- test[test$category %in% uniquetrain,]
Random forest: how to handle new factor levels in test set? If your test data has some levels that are an insignificant percentage of the population, but are just messing up your ability to make the model, here is an elegant way to remove the extraneous level
17,333
Random forest: how to handle new factor levels in test set?
I'm sure that you would have thought of this already if this were the case, but if the test set has actual values and you're using the test set for cross validation purposes, then re-splitting the dataframe into training and test datamframes where the two are balanced on these factors would avoid your problem. This method is popularly known as stratified cross-validation.
Random forest: how to handle new factor levels in test set?
I'm sure that you would have thought of this already if this were the case, but if the test set has actual values and you're using the test set for cross validation purposes, then re-splitting the dat
Random forest: how to handle new factor levels in test set? I'm sure that you would have thought of this already if this were the case, but if the test set has actual values and you're using the test set for cross validation purposes, then re-splitting the dataframe into training and test datamframes where the two are balanced on these factors would avoid your problem. This method is popularly known as stratified cross-validation.
Random forest: how to handle new factor levels in test set? I'm sure that you would have thought of this already if this were the case, but if the test set has actual values and you're using the test set for cross validation purposes, then re-splitting the dat
17,334
Minimum sample size for unpaired t-test
I'd recommend using the non-parametric Mann-Whitney U test rather than an unpaired t-test here. There's no absolute minimum sample size for the t-test, but as the sample sizes get smaller, the test becomes more sensitive to the assumption that both samples are drawn from populations with a normal distribution. With samples this small, especially with one sample of only two, you'd need to be very sure that the population distributions were normal -- and that has to be based on external knowledge, as such small samples gives very little information in themselves about the normality or otherwise of their distributions. But you say that "the population variances and distributions are not known" (my italics). The Mann-Whitney U test does not require any assumptions about the parametric form of the distributions, requiring only the assumption that the distributions of the two groups are the same under the null hypothesis.
Minimum sample size for unpaired t-test
I'd recommend using the non-parametric Mann-Whitney U test rather than an unpaired t-test here. There's no absolute minimum sample size for the t-test, but as the sample sizes get smaller, the test be
Minimum sample size for unpaired t-test I'd recommend using the non-parametric Mann-Whitney U test rather than an unpaired t-test here. There's no absolute minimum sample size for the t-test, but as the sample sizes get smaller, the test becomes more sensitive to the assumption that both samples are drawn from populations with a normal distribution. With samples this small, especially with one sample of only two, you'd need to be very sure that the population distributions were normal -- and that has to be based on external knowledge, as such small samples gives very little information in themselves about the normality or otherwise of their distributions. But you say that "the population variances and distributions are not known" (my italics). The Mann-Whitney U test does not require any assumptions about the parametric form of the distributions, requiring only the assumption that the distributions of the two groups are the same under the null hypothesis.
Minimum sample size for unpaired t-test I'd recommend using the non-parametric Mann-Whitney U test rather than an unpaired t-test here. There's no absolute minimum sample size for the t-test, but as the sample sizes get smaller, the test be
17,335
Minimum sample size for unpaired t-test
(disclaimer: I cannot type well today: my right hand is fractured!) Contrary to the advice to use a non-parametric test in other answers, you should consider that for extremely small sample sizes those methods are not very useful. It is easy to understand why: in studies with extremely small size, no difference between groups can be established unless a big effect size if observed. Non-parametric methods, however, do not care for the magnitude of the difference between the groups. Thus even if the difference between the two groups is huge, with a tiny sample size a non-parametric test will always fail to reject the null hypothesis. Consider this example: two groups, normal distribution, same variance. Group 1: average 1.0, 7 samples. Group 2: average 5, 2 samples. There is a big difference between the averages. wilcox.test(rnorm(7, 1), rnorm(2, 5)) Wilcoxon rank sum test data: rnorm(7, 1) and rnorm(2, 5) W = 0, p-value = 0.05556 The computed p-value is 0.05556 which does not reject the null hypothesis (at 0.05). Now, even if you increase the distance between the two means by a factor of 10, you will get the same p-value: wilcox.test(rnorm(7, 1), rnorm(2, 50)) Wilcoxon rank sum test data: rnorm(7, 1) and rnorm(2, 50) W = 0, p-value = 0.05556 Now I invite you to repeat the same simulation with t-test and observe the p-values in the case of large (average 5 vs 1) and huge (average 50 vs 1) differences.
Minimum sample size for unpaired t-test
(disclaimer: I cannot type well today: my right hand is fractured!) Contrary to the advice to use a non-parametric test in other answers, you should consider that for extremely small sample sizes thos
Minimum sample size for unpaired t-test (disclaimer: I cannot type well today: my right hand is fractured!) Contrary to the advice to use a non-parametric test in other answers, you should consider that for extremely small sample sizes those methods are not very useful. It is easy to understand why: in studies with extremely small size, no difference between groups can be established unless a big effect size if observed. Non-parametric methods, however, do not care for the magnitude of the difference between the groups. Thus even if the difference between the two groups is huge, with a tiny sample size a non-parametric test will always fail to reject the null hypothesis. Consider this example: two groups, normal distribution, same variance. Group 1: average 1.0, 7 samples. Group 2: average 5, 2 samples. There is a big difference between the averages. wilcox.test(rnorm(7, 1), rnorm(2, 5)) Wilcoxon rank sum test data: rnorm(7, 1) and rnorm(2, 5) W = 0, p-value = 0.05556 The computed p-value is 0.05556 which does not reject the null hypothesis (at 0.05). Now, even if you increase the distance between the two means by a factor of 10, you will get the same p-value: wilcox.test(rnorm(7, 1), rnorm(2, 50)) Wilcoxon rank sum test data: rnorm(7, 1) and rnorm(2, 50) W = 0, p-value = 0.05556 Now I invite you to repeat the same simulation with t-test and observe the p-values in the case of large (average 5 vs 1) and huge (average 50 vs 1) differences.
Minimum sample size for unpaired t-test (disclaimer: I cannot type well today: my right hand is fractured!) Contrary to the advice to use a non-parametric test in other answers, you should consider that for extremely small sample sizes thos
17,336
Minimum sample size for unpaired t-test
There is no minimum sample size for a t-test; the t-test was, in fact, designed for small samples. In the old days when tables were printed, you saw t-test tables for very small samples (as measured by df). Of course, as with other tests, if there is a small sample only quite a large effect will be statistically significant.
Minimum sample size for unpaired t-test
There is no minimum sample size for a t-test; the t-test was, in fact, designed for small samples. In the old days when tables were printed, you saw t-test tables for very small samples (as measured
Minimum sample size for unpaired t-test There is no minimum sample size for a t-test; the t-test was, in fact, designed for small samples. In the old days when tables were printed, you saw t-test tables for very small samples (as measured by df). Of course, as with other tests, if there is a small sample only quite a large effect will be statistically significant.
Minimum sample size for unpaired t-test There is no minimum sample size for a t-test; the t-test was, in fact, designed for small samples. In the old days when tables were printed, you saw t-test tables for very small samples (as measured
17,337
Minimum sample size for unpaired t-test
I assume you mean you have 7 data points from one group, and 2 data points from a second group, both of which are subsets of populations (e.g. subset of males and subset of females). The maths for the t-test can be obtained from this Wikipedia page. We will assume an independent two-sample t-test, with unequal sample sizes (7 vs. 2) and unequal variances, so about half-way down that page. You can see that the calculation is based on means and standard deviations. With only 7 subjects in one group and 2 subjects in another, you cannot assume you have good estimates for either the mean or the standard deviation. For the group with 2 subjects, the mean is simply the value that lies exactly in the middle of the two data points, so it is not well estimated. For the group with 7 subjects, sample size strongly affects variances (and therefore standard deviations, which are the square root of the variance) because extreme values exert a much stronger effect when you have a smaller sample. For example, if you look at the basic example on the Wikipedia page for standard deviation you will see that the standard deviation is 2, and the variance (square the standard deviation) is therefore 4. But if we only had the first two data points (the 9 and the 1), the variance would be 10/2 = 5 and the standard deviation would be 2.2 and if we only had the last two values (the 4 and the 16), the variance would be 20/2 = 10 and the standard deviation would be 3.2. We're still using the same values, just less of them, and we can see the effect on our estimates. That is the problem with using inferential statistics with small sample sizes, your results will be particularly strongly affected by sampling. Update: is there any reason why you can't simply report the results by subject and indicate that this is exploratory work? With only two cases, the data is very similar to a case study, and these are both (1) important to write up and (2) accepted practice.
Minimum sample size for unpaired t-test
I assume you mean you have 7 data points from one group, and 2 data points from a second group, both of which are subsets of populations (e.g. subset of males and subset of females). The maths for the
Minimum sample size for unpaired t-test I assume you mean you have 7 data points from one group, and 2 data points from a second group, both of which are subsets of populations (e.g. subset of males and subset of females). The maths for the t-test can be obtained from this Wikipedia page. We will assume an independent two-sample t-test, with unequal sample sizes (7 vs. 2) and unequal variances, so about half-way down that page. You can see that the calculation is based on means and standard deviations. With only 7 subjects in one group and 2 subjects in another, you cannot assume you have good estimates for either the mean or the standard deviation. For the group with 2 subjects, the mean is simply the value that lies exactly in the middle of the two data points, so it is not well estimated. For the group with 7 subjects, sample size strongly affects variances (and therefore standard deviations, which are the square root of the variance) because extreme values exert a much stronger effect when you have a smaller sample. For example, if you look at the basic example on the Wikipedia page for standard deviation you will see that the standard deviation is 2, and the variance (square the standard deviation) is therefore 4. But if we only had the first two data points (the 9 and the 1), the variance would be 10/2 = 5 and the standard deviation would be 2.2 and if we only had the last two values (the 4 and the 16), the variance would be 20/2 = 10 and the standard deviation would be 3.2. We're still using the same values, just less of them, and we can see the effect on our estimates. That is the problem with using inferential statistics with small sample sizes, your results will be particularly strongly affected by sampling. Update: is there any reason why you can't simply report the results by subject and indicate that this is exploratory work? With only two cases, the data is very similar to a case study, and these are both (1) important to write up and (2) accepted practice.
Minimum sample size for unpaired t-test I assume you mean you have 7 data points from one group, and 2 data points from a second group, both of which are subsets of populations (e.g. subset of males and subset of females). The maths for the
17,338
Minimum sample size for unpaired t-test
Interesting related article: 'Using the Student's t-test with extremely low samlpe sizes' J.C.F de Winter (in Practical Assesment, Research & Evaluation) http://goo.gl/ZAUmGW
Minimum sample size for unpaired t-test
Interesting related article: 'Using the Student's t-test with extremely low samlpe sizes' J.C.F de Winter (in Practical Assesment, Research & Evaluation) http://goo.gl/ZAUmGW
Minimum sample size for unpaired t-test Interesting related article: 'Using the Student's t-test with extremely low samlpe sizes' J.C.F de Winter (in Practical Assesment, Research & Evaluation) http://goo.gl/ZAUmGW
Minimum sample size for unpaired t-test Interesting related article: 'Using the Student's t-test with extremely low samlpe sizes' J.C.F de Winter (in Practical Assesment, Research & Evaluation) http://goo.gl/ZAUmGW
17,339
Minimum sample size for unpaired t-test
I would recommend to compare the conclusions that you get with both, the t-test and the Mann-Whitney test, and also take a look at boxplots and the profile likelihood of the mean of each population.
Minimum sample size for unpaired t-test
I would recommend to compare the conclusions that you get with both, the t-test and the Mann-Whitney test, and also take a look at boxplots and the profile likelihood of the mean of each population.
Minimum sample size for unpaired t-test I would recommend to compare the conclusions that you get with both, the t-test and the Mann-Whitney test, and also take a look at boxplots and the profile likelihood of the mean of each population.
Minimum sample size for unpaired t-test I would recommend to compare the conclusions that you get with both, the t-test and the Mann-Whitney test, and also take a look at boxplots and the profile likelihood of the mean of each population.
17,340
Minimum sample size for unpaired t-test
As a ttest performed on small samples probably does not fulfill the ttest requirements (mainly, the normality of the populations from which the two samples have bee drawn), I would recommend to perform a bootstrap ttest (with unequal variances), following Efron B, Tibshirani Rj. An Introdution to the Bootstrap. Boca Raton, FL: Chapman & Hall/CRC, 1993: 220-224. The code for a bootstrap ttest on the data provided by Johnny Puzzled in Stata 13/SE is reported in the image above.
Minimum sample size for unpaired t-test
As a ttest performed on small samples probably does not fulfill the ttest requirements (mainly, the normality of the populations from which the two samples have bee drawn), I would recommend to perfor
Minimum sample size for unpaired t-test As a ttest performed on small samples probably does not fulfill the ttest requirements (mainly, the normality of the populations from which the two samples have bee drawn), I would recommend to perform a bootstrap ttest (with unequal variances), following Efron B, Tibshirani Rj. An Introdution to the Bootstrap. Boca Raton, FL: Chapman & Hall/CRC, 1993: 220-224. The code for a bootstrap ttest on the data provided by Johnny Puzzled in Stata 13/SE is reported in the image above.
Minimum sample size for unpaired t-test As a ttest performed on small samples probably does not fulfill the ttest requirements (mainly, the normality of the populations from which the two samples have bee drawn), I would recommend to perfor
17,341
Minimum sample size for unpaired t-test
With a sample size of 2, the best thing to do may be to look at the individual numbers themselves and not even bother with statistical analysis.
Minimum sample size for unpaired t-test
With a sample size of 2, the best thing to do may be to look at the individual numbers themselves and not even bother with statistical analysis.
Minimum sample size for unpaired t-test With a sample size of 2, the best thing to do may be to look at the individual numbers themselves and not even bother with statistical analysis.
Minimum sample size for unpaired t-test With a sample size of 2, the best thing to do may be to look at the individual numbers themselves and not even bother with statistical analysis.
17,342
Increasing number of features results in accuracy drop but prec/recall increase
Accuracy vs F-measure First of all, when you use a metric you should know how to game it. Accuracy measures the ratio of correctly classified instances across all classes. That means, that if one class occurs more often than another, then the resulting accuracy is clearly dominated by the accuracy of the dominating class. In your case if one constructs a Model M which just predicts "neutral" for every instance, the resulting accuracy will be $acc=\frac{neutral}{(neutral + positive + negative)}=0.9188$ Good, but useless. So the addition of features clearly improved the power of NB to differentiate the classes, but by predicting "positive" and "negative" one missclassifies neutrals and hence the accuracy goes down (roughly spoken). This behavior is independent of NB. More or less Features ? In general it is not better to use more features, but to use the right features. More features is better insofar that a feature selection algorithm has more choices to find the optimal subset (I suggest to explore: feature-selection of crossvalidated). When it comes to NB, a fast and solid (but less than optimal) approach is to use InformationGain(Ratio) to sort the features in decreasing order and select the top k. Again, this advice (except InformationGain) is independent of the classification algorithm. EDIT 27.11.11 There has been a lot of confusion regarding bias and variance to select the correct number of features. I therefore recommend to read the first pages of this tutorial: Bias-Variance tradeoff. The key essence is: High Bias means, that the model is less than optimal, i.e. the test-error is high (underfitting, as Simone puts it) High Variance means, that the model is very sensitive to the sample used to build the model. That means, that the error highly depends on the training set used and hence the variance of the error (evaluated across different crossvalidation-folds) will extremely differ. (overfitting) The learning-curves plotted do indeed indicate the Bias, since the error is plotted. However, what you cannot see is the Variance, since the confidence-interval of the error is not plotted at all. Example: When performing a 3-fold Crossvalidation 6-times (yes, repetition with different data partitioning is recommended, Kohavi suggests 6 repetitions), you get 18 values. I now would expect that ... With a small number of features, the average error (bias) will be lower, however, the variance of the error (of the 18 values) will be higher. with a high number of features, the average error (bias) will be higher, but the variance of the error (of the 18 values) lower. This behavior of the error/bias is exactly what we see in your plots. We cannot make a statement about the variance. That the curves are close to each other can be an indication that the test-set is big enough to show the same characteristics as the training set and hence that the measured error may be reliable, but this is (at least as far as I understood it) not sufficient to make a statement about the variance (of the error !). When adding more and more training examples (keeping the size of test-set fixed), I would expect that the variance of both approaches (small and high number of features) decrease. Oh, and do not forget to calculate the infogain for feature selection using only the data in the training sample ! One is tempted to use the complete data for feature selection and then perform data partitioning and apply the crossvalidation, but this will lead to overfitting. I do not know what you did, this is just a warning one should never forget.
Increasing number of features results in accuracy drop but prec/recall increase
Accuracy vs F-measure First of all, when you use a metric you should know how to game it. Accuracy measures the ratio of correctly classified instances across all classes. That means, that if one cla
Increasing number of features results in accuracy drop but prec/recall increase Accuracy vs F-measure First of all, when you use a metric you should know how to game it. Accuracy measures the ratio of correctly classified instances across all classes. That means, that if one class occurs more often than another, then the resulting accuracy is clearly dominated by the accuracy of the dominating class. In your case if one constructs a Model M which just predicts "neutral" for every instance, the resulting accuracy will be $acc=\frac{neutral}{(neutral + positive + negative)}=0.9188$ Good, but useless. So the addition of features clearly improved the power of NB to differentiate the classes, but by predicting "positive" and "negative" one missclassifies neutrals and hence the accuracy goes down (roughly spoken). This behavior is independent of NB. More or less Features ? In general it is not better to use more features, but to use the right features. More features is better insofar that a feature selection algorithm has more choices to find the optimal subset (I suggest to explore: feature-selection of crossvalidated). When it comes to NB, a fast and solid (but less than optimal) approach is to use InformationGain(Ratio) to sort the features in decreasing order and select the top k. Again, this advice (except InformationGain) is independent of the classification algorithm. EDIT 27.11.11 There has been a lot of confusion regarding bias and variance to select the correct number of features. I therefore recommend to read the first pages of this tutorial: Bias-Variance tradeoff. The key essence is: High Bias means, that the model is less than optimal, i.e. the test-error is high (underfitting, as Simone puts it) High Variance means, that the model is very sensitive to the sample used to build the model. That means, that the error highly depends on the training set used and hence the variance of the error (evaluated across different crossvalidation-folds) will extremely differ. (overfitting) The learning-curves plotted do indeed indicate the Bias, since the error is plotted. However, what you cannot see is the Variance, since the confidence-interval of the error is not plotted at all. Example: When performing a 3-fold Crossvalidation 6-times (yes, repetition with different data partitioning is recommended, Kohavi suggests 6 repetitions), you get 18 values. I now would expect that ... With a small number of features, the average error (bias) will be lower, however, the variance of the error (of the 18 values) will be higher. with a high number of features, the average error (bias) will be higher, but the variance of the error (of the 18 values) lower. This behavior of the error/bias is exactly what we see in your plots. We cannot make a statement about the variance. That the curves are close to each other can be an indication that the test-set is big enough to show the same characteristics as the training set and hence that the measured error may be reliable, but this is (at least as far as I understood it) not sufficient to make a statement about the variance (of the error !). When adding more and more training examples (keeping the size of test-set fixed), I would expect that the variance of both approaches (small and high number of features) decrease. Oh, and do not forget to calculate the infogain for feature selection using only the data in the training sample ! One is tempted to use the complete data for feature selection and then perform data partitioning and apply the crossvalidation, but this will lead to overfitting. I do not know what you did, this is just a warning one should never forget.
Increasing number of features results in accuracy drop but prec/recall increase Accuracy vs F-measure First of all, when you use a metric you should know how to game it. Accuracy measures the ratio of correctly classified instances across all classes. That means, that if one cla
17,343
Increasing number of features results in accuracy drop but prec/recall increase
In order to know if it is useful to use more features I would plot learning curves. I think this is clearly explained in the 10th Unit of Stanford's Machine Learning class, named "Advise for applying machine learning", that you can find here: http://www.ml-class.org/course/video/preview_list. Plotting learning curves you can understand if your problem is either the high bias or the high variance. As long as you increase the number of training example you should plot the training error and the test error (ie 1-accuracy), the latter is the error of your classifier estimated on a different data set. If these curves are close to each other you have an high bias problem and it would probably be beneficial to insert more features. On the other hand, if your curves are quite separated as long as you increase the number of training examples you have a high variance problem. In this case you should decrease the number of features you are using. Edit I'm going to add some examples of learning curves. These are learning curves obtained with a regularized logistic regression. Different plots are related to different $\lambda$ to tune the power of regularization. With a small $\lambda$ we have overfitting, thus high variance. With a large $\lambda$ with have underfitting, thus high bias. A good result is obtained setting $\lambda=1$ as trade-off.
Increasing number of features results in accuracy drop but prec/recall increase
In order to know if it is useful to use more features I would plot learning curves. I think this is clearly explained in the 10th Unit of Stanford's Machine Learning class, named "Advise for applying
Increasing number of features results in accuracy drop but prec/recall increase In order to know if it is useful to use more features I would plot learning curves. I think this is clearly explained in the 10th Unit of Stanford's Machine Learning class, named "Advise for applying machine learning", that you can find here: http://www.ml-class.org/course/video/preview_list. Plotting learning curves you can understand if your problem is either the high bias or the high variance. As long as you increase the number of training example you should plot the training error and the test error (ie 1-accuracy), the latter is the error of your classifier estimated on a different data set. If these curves are close to each other you have an high bias problem and it would probably be beneficial to insert more features. On the other hand, if your curves are quite separated as long as you increase the number of training examples you have a high variance problem. In this case you should decrease the number of features you are using. Edit I'm going to add some examples of learning curves. These are learning curves obtained with a regularized logistic regression. Different plots are related to different $\lambda$ to tune the power of regularization. With a small $\lambda$ we have overfitting, thus high variance. With a large $\lambda$ with have underfitting, thus high bias. A good result is obtained setting $\lambda=1$ as trade-off.
Increasing number of features results in accuracy drop but prec/recall increase In order to know if it is useful to use more features I would plot learning curves. I think this is clearly explained in the 10th Unit of Stanford's Machine Learning class, named "Advise for applying
17,344
What is the correlation if the standard deviation of one variable is 0?
It's true that, if one of your SD's is 0, that equation is undefined. However, a better way to think about this is that if one of your SD's is 0, there is no correlation. In loose conceptual terms, a correlation is telling you about how one variable moves around as the other variable moves around. An SD of 0 implies that variable is not 'moving around'. You would have to have a vector of a constant, such as rep(constant, n_times).
What is the correlation if the standard deviation of one variable is 0?
It's true that, if one of your SD's is 0, that equation is undefined. However, a better way to think about this is that if one of your SD's is 0, there is no correlation. In loose conceptual terms,
What is the correlation if the standard deviation of one variable is 0? It's true that, if one of your SD's is 0, that equation is undefined. However, a better way to think about this is that if one of your SD's is 0, there is no correlation. In loose conceptual terms, a correlation is telling you about how one variable moves around as the other variable moves around. An SD of 0 implies that variable is not 'moving around'. You would have to have a vector of a constant, such as rep(constant, n_times).
What is the correlation if the standard deviation of one variable is 0? It's true that, if one of your SD's is 0, that equation is undefined. However, a better way to think about this is that if one of your SD's is 0, there is no correlation. In loose conceptual terms,
17,345
What is the correlation if the standard deviation of one variable is 0?
The other thing to think about are the underlying assumptions when we talk about means and standard deviations, and correlations. If we are talking about a data sample, one common assumption is that the data is (at least approximately) normally distributed, or can be transformed such that it is (e.g. via a log transform). If you observe a standard deviation of zero, there are two scenarios: either the standard deviation is in fact nonzero, but very small, and therefore the dataset you have has samples that are all on the mean value (this could, for example, happen if you are measuring data at a coarse level of precision); or the model is misspecified. In this second scenario, the standard deviation, and consequently the correlation, is a meaningless measure. More generally, the underlying distributions must both have finite second moments, and therefore non-zero standard deviations, for the correlation to be a valid concept.
What is the correlation if the standard deviation of one variable is 0?
The other thing to think about are the underlying assumptions when we talk about means and standard deviations, and correlations. If we are talking about a data sample, one common assumption is that
What is the correlation if the standard deviation of one variable is 0? The other thing to think about are the underlying assumptions when we talk about means and standard deviations, and correlations. If we are talking about a data sample, one common assumption is that the data is (at least approximately) normally distributed, or can be transformed such that it is (e.g. via a log transform). If you observe a standard deviation of zero, there are two scenarios: either the standard deviation is in fact nonzero, but very small, and therefore the dataset you have has samples that are all on the mean value (this could, for example, happen if you are measuring data at a coarse level of precision); or the model is misspecified. In this second scenario, the standard deviation, and consequently the correlation, is a meaningless measure. More generally, the underlying distributions must both have finite second moments, and therefore non-zero standard deviations, for the correlation to be a valid concept.
What is the correlation if the standard deviation of one variable is 0? The other thing to think about are the underlying assumptions when we talk about means and standard deviations, and correlations. If we are talking about a data sample, one common assumption is that
17,346
What is the correlation if the standard deviation of one variable is 0?
A correlation is the cosine of the angle between two vectors. To say that the standard deviation for Y is zero is the same as saying that the vector Y-mean(Y) is zero (or, more rigorously, that it represents zero in the appropriate vector space). So the question becomes "What can one say about the (cosine of the) angle between the zero vector and the vector X-mean(X)?". More generally, in any vector space with an inner product, what is meant by the angle between the zero vector and some other vector? There's only one answer to this, in my opinion, and that is that the concept of "angle" in this situation is meaningless, and so the concept of correlation in this situation is meaningless.
What is the correlation if the standard deviation of one variable is 0?
A correlation is the cosine of the angle between two vectors. To say that the standard deviation for Y is zero is the same as saying that the vector Y-mean(Y) is zero (or, more rigorously, that it rep
What is the correlation if the standard deviation of one variable is 0? A correlation is the cosine of the angle between two vectors. To say that the standard deviation for Y is zero is the same as saying that the vector Y-mean(Y) is zero (or, more rigorously, that it represents zero in the appropriate vector space). So the question becomes "What can one say about the (cosine of the) angle between the zero vector and the vector X-mean(X)?". More generally, in any vector space with an inner product, what is meant by the angle between the zero vector and some other vector? There's only one answer to this, in my opinion, and that is that the concept of "angle" in this situation is meaningless, and so the concept of correlation in this situation is meaningless.
What is the correlation if the standard deviation of one variable is 0? A correlation is the cosine of the angle between two vectors. To say that the standard deviation for Y is zero is the same as saying that the vector Y-mean(Y) is zero (or, more rigorously, that it rep
17,347
What is the correlation if the standard deviation of one variable is 0?
Disclaimer, I realize that there is already an accepted quality answer, so this should be a response, but I don't have the experience points to allow it. @Dilip mentioned that you can define the correlation as 0 for convention, but this seems problematic as it would have very different interpretation from a correlation that is truly zero (with non-zero SDs). The original question says "if the SD of one variable is zero". If we just stop and think of the definition of 'variable' then we get a much more direct path to the answer. A variable with 0 SD is not a variable at all, it is a constant. So in that case you don't have two variables, so it conceptually doesn't make sense to define a correlation at all.
What is the correlation if the standard deviation of one variable is 0?
Disclaimer, I realize that there is already an accepted quality answer, so this should be a response, but I don't have the experience points to allow it. @Dilip mentioned that you can define the corr
What is the correlation if the standard deviation of one variable is 0? Disclaimer, I realize that there is already an accepted quality answer, so this should be a response, but I don't have the experience points to allow it. @Dilip mentioned that you can define the correlation as 0 for convention, but this seems problematic as it would have very different interpretation from a correlation that is truly zero (with non-zero SDs). The original question says "if the SD of one variable is zero". If we just stop and think of the definition of 'variable' then we get a much more direct path to the answer. A variable with 0 SD is not a variable at all, it is a constant. So in that case you don't have two variables, so it conceptually doesn't make sense to define a correlation at all.
What is the correlation if the standard deviation of one variable is 0? Disclaimer, I realize that there is already an accepted quality answer, so this should be a response, but I don't have the experience points to allow it. @Dilip mentioned that you can define the corr
17,348
How can I improve my analysis of the effects of reputation on voting?
This is a brave try, but with these data alone, it will be difficult or impossible to answer your research question concerning the "effect of reputation on upvotes." The problem lies in separating the effects of other phenomena, which I list along with brief indications of how they might be addressed. Learning effects. As reputation goes up, experience goes up; as experience goes up, we would expect a person to post better questions and answers; as their quality improves, we expect more votes per post. Conceivably, one way to handle this in an analysis would be to identify people who are active on more than one SE site. On any given site their reputation would increase more slowly than the amount of their experience, thus providing a handle for teasing apart the reputation and learning effects. Temporal changes in context. These are myriad, but the obvious ones would include Changes in numbers of voters over time, including an overall upward trend, seasonal trends (often associated with academic cycles), and outliers (arising from external publicity such as links to specific threads). Any analysis would have to factor this in when evaluating trends in reputation for any individual. Changes in a community's mores over time. Communities, and how they interact, evolve and develop. Over time they may tend to vote more or less often. Any analysis would have to evaluate this effect and factor it in. Time itself. As time goes by, earlier posts remain available for searching and continue to garner votes. Thus, caeteris paribus, older posts ought to produce more votes than newer ones. (This is a strong effect: some people consistently high on the monthly reputation leagues have not visited this site all year!) This would mask or even invert any actual positive reputation effect. Any analysis needs to factor in the length of time each post has been present on the site. Subject popularity. Some tags (e.g., r) are far more popular than others. Thus, changes in the kinds of questions a person answers can be confounded with temporal changes, such as a reputation effect. Therefore, any analysis needs to factor in the nature of the questions being answered. Views [added as an edit]. Questions are viewed by different numbers of people for various reasons (filters, links, etc.). It's possible the number of votes received by answers are related to the number of views, although one would expect a declining proportion as the number of views increases. (It's a matter of how many people who are truly interested in the question actually view it, not the raw number. My own--anecdotal--experience is that roughly half the upvotes I receive on many questions come within the first 5-15 views, although eventually the questions are viewed hundreds of times.) Therefore, any analysis needs to factor in the number of views, but probably not in a linear way. Measurement difficulties. "Reputation" is the sum of votes received for different activities: initial reputation, answers, questions, approving questions, editing tag wikis, downvoting, and getting downvoted (in descending order of value). Because these components assess different things, and not all are under the control of the community voters, they should be separated for analysis. A "reputation effect" presumably is associated with upvotes on answers and, perhaps, on questions, but should not affect other sources of reputation. The starting reputation definitely should be subtracted (but perhaps could be used as a proxy for some initial amount of experience). Hidden factors. There can be many other confounding factors that are impossible to measure. For example, there are various forms of "burnout" in participation in forums. What do people do after an initial few weeks, months, or years of enthusiasm? Some possibilities include focusing on the rare, unusual, or difficult questions; providing answers only to unanswered questions; providing fewer answers but of higher quality; etc. Some of these could mask a reputation effect, whereas others could mistakenly be confused with one. A proxy for such factors might be changes in rates of participation by an individual: they could signal changes in the nature of that person's posts. Subcommunity phenomena. A hard look at the statistics, even on very active SE pages, shows that a relatively small number of people do most of the answering and voting. A clique as small as two or three people can have a profound influence on the growth of reputation. A two-person clique will be detected by the site's built-in monitors (and one such group exists on this site), but larger cliques probably won't be. (I'm not talking about formal collusion: people can be members of such cliques without even being aware of it.) How would we separate an apparent reputation effect from activities of these invisible, undetected, informal cliques? Detailed voting data could be used diagnostically, but I don't believe we have access to these data. Limited data. To detect a reputation effect, you will likely need to focus on individuals with dozens to hundreds of posts (at least). That drops the current population to less than 50 individuals. With all the possibility of variation and confounding, that is far too small to tease out significant effects unless they are very strong indeed. The cure is to augment the dataset with records from other SE sites. Given all these complications, it should be clear that the exploratory graphics in the blog article have little chance of revealing anything unless it is glaringly obvious. Nothing leaps out at us: as expected, the data are messy and complicated. It's premature to recommend improvements to the plots or to the analysis that has been presented: incremental changes and additional analysis won't help until these fundamental issues have been addressed.
How can I improve my analysis of the effects of reputation on voting?
This is a brave try, but with these data alone, it will be difficult or impossible to answer your research question concerning the "effect of reputation on upvotes." The problem lies in separating th
How can I improve my analysis of the effects of reputation on voting? This is a brave try, but with these data alone, it will be difficult or impossible to answer your research question concerning the "effect of reputation on upvotes." The problem lies in separating the effects of other phenomena, which I list along with brief indications of how they might be addressed. Learning effects. As reputation goes up, experience goes up; as experience goes up, we would expect a person to post better questions and answers; as their quality improves, we expect more votes per post. Conceivably, one way to handle this in an analysis would be to identify people who are active on more than one SE site. On any given site their reputation would increase more slowly than the amount of their experience, thus providing a handle for teasing apart the reputation and learning effects. Temporal changes in context. These are myriad, but the obvious ones would include Changes in numbers of voters over time, including an overall upward trend, seasonal trends (often associated with academic cycles), and outliers (arising from external publicity such as links to specific threads). Any analysis would have to factor this in when evaluating trends in reputation for any individual. Changes in a community's mores over time. Communities, and how they interact, evolve and develop. Over time they may tend to vote more or less often. Any analysis would have to evaluate this effect and factor it in. Time itself. As time goes by, earlier posts remain available for searching and continue to garner votes. Thus, caeteris paribus, older posts ought to produce more votes than newer ones. (This is a strong effect: some people consistently high on the monthly reputation leagues have not visited this site all year!) This would mask or even invert any actual positive reputation effect. Any analysis needs to factor in the length of time each post has been present on the site. Subject popularity. Some tags (e.g., r) are far more popular than others. Thus, changes in the kinds of questions a person answers can be confounded with temporal changes, such as a reputation effect. Therefore, any analysis needs to factor in the nature of the questions being answered. Views [added as an edit]. Questions are viewed by different numbers of people for various reasons (filters, links, etc.). It's possible the number of votes received by answers are related to the number of views, although one would expect a declining proportion as the number of views increases. (It's a matter of how many people who are truly interested in the question actually view it, not the raw number. My own--anecdotal--experience is that roughly half the upvotes I receive on many questions come within the first 5-15 views, although eventually the questions are viewed hundreds of times.) Therefore, any analysis needs to factor in the number of views, but probably not in a linear way. Measurement difficulties. "Reputation" is the sum of votes received for different activities: initial reputation, answers, questions, approving questions, editing tag wikis, downvoting, and getting downvoted (in descending order of value). Because these components assess different things, and not all are under the control of the community voters, they should be separated for analysis. A "reputation effect" presumably is associated with upvotes on answers and, perhaps, on questions, but should not affect other sources of reputation. The starting reputation definitely should be subtracted (but perhaps could be used as a proxy for some initial amount of experience). Hidden factors. There can be many other confounding factors that are impossible to measure. For example, there are various forms of "burnout" in participation in forums. What do people do after an initial few weeks, months, or years of enthusiasm? Some possibilities include focusing on the rare, unusual, or difficult questions; providing answers only to unanswered questions; providing fewer answers but of higher quality; etc. Some of these could mask a reputation effect, whereas others could mistakenly be confused with one. A proxy for such factors might be changes in rates of participation by an individual: they could signal changes in the nature of that person's posts. Subcommunity phenomena. A hard look at the statistics, even on very active SE pages, shows that a relatively small number of people do most of the answering and voting. A clique as small as two or three people can have a profound influence on the growth of reputation. A two-person clique will be detected by the site's built-in monitors (and one such group exists on this site), but larger cliques probably won't be. (I'm not talking about formal collusion: people can be members of such cliques without even being aware of it.) How would we separate an apparent reputation effect from activities of these invisible, undetected, informal cliques? Detailed voting data could be used diagnostically, but I don't believe we have access to these data. Limited data. To detect a reputation effect, you will likely need to focus on individuals with dozens to hundreds of posts (at least). That drops the current population to less than 50 individuals. With all the possibility of variation and confounding, that is far too small to tease out significant effects unless they are very strong indeed. The cure is to augment the dataset with records from other SE sites. Given all these complications, it should be clear that the exploratory graphics in the blog article have little chance of revealing anything unless it is glaringly obvious. Nothing leaps out at us: as expected, the data are messy and complicated. It's premature to recommend improvements to the plots or to the analysis that has been presented: incremental changes and additional analysis won't help until these fundamental issues have been addressed.
How can I improve my analysis of the effects of reputation on voting? This is a brave try, but with these data alone, it will be difficult or impossible to answer your research question concerning the "effect of reputation on upvotes." The problem lies in separating th
17,349
How can I improve my analysis of the effects of reputation on voting?
Econometricians have looked at similar issues within the framework of Granger causality. If you have two series, $Y_t$ and $Z_t$, you can run vector autoregressive models, which in the simplest form with a single lag look like $Y_t = a_0 + a_1 Y_{t-1} + a_2 Z_{t-1} + \epsilon_t$, $Z_t = b_0 + b_1 Y_{t-1} + b_2 Z_{t-1} + \delta_t$. If you see that say $a_2$ is significant, then you can claim that $Z$ (Granger-)causes $Y$: adding information about $Z$ improves the precision of your model for $Y$. Here, your time $t$ would be the post number, and the variables are obviously reputation and the score. Both are non-stationary, so a more serious fiddling with the data, like taking the increments $\Delta Y_t = Y_t - Y_{t-1}$ in place of $Y_t$ in the above equations will be called for. (Note that you may lose the normal and normal-based $F$ or $\chi^2$ distributions with non-stationary data, and the rate of convergence with trend variables, if you include them into analysis, may be $T^{-1}$ or even faster, rather than $T^{-1/2}$ that most of us are used to from the Central Limit Theorem. You need to be super-careful with these.) So I guess if $Y_t$ is the answer score, and $Z_t$ is reputation, then clearly $a_0$ is the average score, $a_1$ is how the person learns to write better answers, and $a_2$ is how their reputation precedes their word (provided the model assumptions are satisfied, etc.) On point 1: if you were doing fixed effects by hand, you should've centered both the response variable and the explanatory variables. The panel data regression package would've done this for you, but the official econometric way of looking at things is to subtract the "between" regression from the "pooled" regression (see Wooldridge's black book; I have not checked the second edition, but I generally view the first edition as the best textbook-type description of econometric panel data). On your point 2: of course Eicker/White standard errors won't affect your point estimates; if they did, that would indicate an incorrect implementation! In the context of time-series, an even more appropriate estimator is due to Newey and West (1987). Trying transformations might help. I am personally a big fan of the Box-Cox transformation, but in the context of the analysis that you are undertaking, it is difficult to do it cleanly. First, you would need a shift parameter on top of the shape parameter, and the shift parameters are notoriously difficult to identify in models like this. Second, you would probably need different shift/shape parameters for different people, and/or different posts, and/or... (all the hell breaking loose). Count data is an option, too, but in the context of mean modeling, a Poisson regression is just as good as the log transformation, yet it imposes an unwieldy assumption of variance = mean. P.S. You could probably tag this with "longitudinal-data" and "time-series".
How can I improve my analysis of the effects of reputation on voting?
Econometricians have looked at similar issues within the framework of Granger causality. If you have two series, $Y_t$ and $Z_t$, you can run vector autoregressive models, which in the simplest form w
How can I improve my analysis of the effects of reputation on voting? Econometricians have looked at similar issues within the framework of Granger causality. If you have two series, $Y_t$ and $Z_t$, you can run vector autoregressive models, which in the simplest form with a single lag look like $Y_t = a_0 + a_1 Y_{t-1} + a_2 Z_{t-1} + \epsilon_t$, $Z_t = b_0 + b_1 Y_{t-1} + b_2 Z_{t-1} + \delta_t$. If you see that say $a_2$ is significant, then you can claim that $Z$ (Granger-)causes $Y$: adding information about $Z$ improves the precision of your model for $Y$. Here, your time $t$ would be the post number, and the variables are obviously reputation and the score. Both are non-stationary, so a more serious fiddling with the data, like taking the increments $\Delta Y_t = Y_t - Y_{t-1}$ in place of $Y_t$ in the above equations will be called for. (Note that you may lose the normal and normal-based $F$ or $\chi^2$ distributions with non-stationary data, and the rate of convergence with trend variables, if you include them into analysis, may be $T^{-1}$ or even faster, rather than $T^{-1/2}$ that most of us are used to from the Central Limit Theorem. You need to be super-careful with these.) So I guess if $Y_t$ is the answer score, and $Z_t$ is reputation, then clearly $a_0$ is the average score, $a_1$ is how the person learns to write better answers, and $a_2$ is how their reputation precedes their word (provided the model assumptions are satisfied, etc.) On point 1: if you were doing fixed effects by hand, you should've centered both the response variable and the explanatory variables. The panel data regression package would've done this for you, but the official econometric way of looking at things is to subtract the "between" regression from the "pooled" regression (see Wooldridge's black book; I have not checked the second edition, but I generally view the first edition as the best textbook-type description of econometric panel data). On your point 2: of course Eicker/White standard errors won't affect your point estimates; if they did, that would indicate an incorrect implementation! In the context of time-series, an even more appropriate estimator is due to Newey and West (1987). Trying transformations might help. I am personally a big fan of the Box-Cox transformation, but in the context of the analysis that you are undertaking, it is difficult to do it cleanly. First, you would need a shift parameter on top of the shape parameter, and the shift parameters are notoriously difficult to identify in models like this. Second, you would probably need different shift/shape parameters for different people, and/or different posts, and/or... (all the hell breaking loose). Count data is an option, too, but in the context of mean modeling, a Poisson regression is just as good as the log transformation, yet it imposes an unwieldy assumption of variance = mean. P.S. You could probably tag this with "longitudinal-data" and "time-series".
How can I improve my analysis of the effects of reputation on voting? Econometricians have looked at similar issues within the framework of Granger causality. If you have two series, $Y_t$ and $Z_t$, you can run vector autoregressive models, which in the simplest form w
17,350
How can I improve my analysis of the effects of reputation on voting?
Several other changes to plots: Quantile bands for the answer score versus previous reputation. (Plots 1 & 3) Density plots for Skeet versus others, stratified by post # (Plot 3) Consider stratifying by # of competing posts Stratify by time (one may continue to gain points long after the question has been asked) Modeling this will be harder. You might consider Poisson regression. Frankly, though, developing good plots is a much better method of developing insights and skills. Begin modeling after you have a better understanding of the data.
How can I improve my analysis of the effects of reputation on voting?
Several other changes to plots: Quantile bands for the answer score versus previous reputation. (Plots 1 & 3) Density plots for Skeet versus others, stratified by post # (Plot 3) Consider stratifyin
How can I improve my analysis of the effects of reputation on voting? Several other changes to plots: Quantile bands for the answer score versus previous reputation. (Plots 1 & 3) Density plots for Skeet versus others, stratified by post # (Plot 3) Consider stratifying by # of competing posts Stratify by time (one may continue to gain points long after the question has been asked) Modeling this will be harder. You might consider Poisson regression. Frankly, though, developing good plots is a much better method of developing insights and skills. Begin modeling after you have a better understanding of the data.
How can I improve my analysis of the effects of reputation on voting? Several other changes to plots: Quantile bands for the answer score versus previous reputation. (Plots 1 & 3) Density plots for Skeet versus others, stratified by post # (Plot 3) Consider stratifyin
17,351
How can I improve my analysis of the effects of reputation on voting?
Whoa there. (And I mean that in a good way ;-)) Before going further with models, you need to address what's going on with the data. I don't see an explanation for the very peculiar curve in the middle of this plot: http://stats.blogoverflow.com/files/2011/07/Rep_Correlated_With_Upvotes.png Seeing such a curve makes me think that there's something very weird about those points - that they're not independent from each other and instead reflect some sequence of observations of the same source. (Minor note: titling that plot "Correlation..." is misleading.)
How can I improve my analysis of the effects of reputation on voting?
Whoa there. (And I mean that in a good way ;-)) Before going further with models, you need to address what's going on with the data. I don't see an explanation for the very peculiar curve in the mid
How can I improve my analysis of the effects of reputation on voting? Whoa there. (And I mean that in a good way ;-)) Before going further with models, you need to address what's going on with the data. I don't see an explanation for the very peculiar curve in the middle of this plot: http://stats.blogoverflow.com/files/2011/07/Rep_Correlated_With_Upvotes.png Seeing such a curve makes me think that there's something very weird about those points - that they're not independent from each other and instead reflect some sequence of observations of the same source. (Minor note: titling that plot "Correlation..." is misleading.)
How can I improve my analysis of the effects of reputation on voting? Whoa there. (And I mean that in a good way ;-)) Before going further with models, you need to address what's going on with the data. I don't see an explanation for the very peculiar curve in the mid
17,352
What does it mean for a study to be over-powered?
I think that your interpretation is incorrect. You say "These effect sizes are perhaps so small as are more likely result from slight biases in the sampling process than a (not necessarily direct) causal connection between the variables" which seems to imply that the P value in an 'over-powered' study is not the same sort of thing as a P value from a 'properly' powered study. That is wrong. In both cases the P value is the probability of obtaining data as extreme as those observed, or more extreme, if the null hypothesis is true. If you prefer the Neyman-Pearson approach, the rate of false positive errors obtained from the 'over-powered' study is the same as that of a 'properly' powered study if the same alpha value is used for both. The difference in interpretation that is needed is that there is a different relationship between statistical significance and scientific significance for over-powered studies. In effect, the over-powered study will give a large probability of obtaining significance even though the effect is, as you say, miniscule, and therefore of questionable importance. As long as results from an 'over-powered' study are appropriately interpreted (and confidence intervals for the effect size help such an interpretation) there is no statistical problem with an 'over-powered' study. In that light, the only criteria by which a study can actually be over-powered are the ethical and resource allocation issues raised in other answers.
What does it mean for a study to be over-powered?
I think that your interpretation is incorrect. You say "These effect sizes are perhaps so small as are more likely result from slight biases in the sampling process than a (not necessarily direct) cau
What does it mean for a study to be over-powered? I think that your interpretation is incorrect. You say "These effect sizes are perhaps so small as are more likely result from slight biases in the sampling process than a (not necessarily direct) causal connection between the variables" which seems to imply that the P value in an 'over-powered' study is not the same sort of thing as a P value from a 'properly' powered study. That is wrong. In both cases the P value is the probability of obtaining data as extreme as those observed, or more extreme, if the null hypothesis is true. If you prefer the Neyman-Pearson approach, the rate of false positive errors obtained from the 'over-powered' study is the same as that of a 'properly' powered study if the same alpha value is used for both. The difference in interpretation that is needed is that there is a different relationship between statistical significance and scientific significance for over-powered studies. In effect, the over-powered study will give a large probability of obtaining significance even though the effect is, as you say, miniscule, and therefore of questionable importance. As long as results from an 'over-powered' study are appropriately interpreted (and confidence intervals for the effect size help such an interpretation) there is no statistical problem with an 'over-powered' study. In that light, the only criteria by which a study can actually be over-powered are the ethical and resource allocation issues raised in other answers.
What does it mean for a study to be over-powered? I think that your interpretation is incorrect. You say "These effect sizes are perhaps so small as are more likely result from slight biases in the sampling process than a (not necessarily direct) cau
17,353
What does it mean for a study to be over-powered?
In medical research trials may be unethical if they recruit too many patients. For example if the goal is to decide which treatment is better it's not ethical any more to treat patients with the worse treatment after it was established to be inferior. Increasing the sample size would, of course, give you a more accurate estimate of the effect size, but you may have to stop well before the effects of factors like "slight biases in the sampling process" appear. It may also be unethical to spend public money of sufficiently confirmed research.
What does it mean for a study to be over-powered?
In medical research trials may be unethical if they recruit too many patients. For example if the goal is to decide which treatment is better it's not ethical any more to treat patients with the worse
What does it mean for a study to be over-powered? In medical research trials may be unethical if they recruit too many patients. For example if the goal is to decide which treatment is better it's not ethical any more to treat patients with the worse treatment after it was established to be inferior. Increasing the sample size would, of course, give you a more accurate estimate of the effect size, but you may have to stop well before the effects of factors like "slight biases in the sampling process" appear. It may also be unethical to spend public money of sufficiently confirmed research.
What does it mean for a study to be over-powered? In medical research trials may be unethical if they recruit too many patients. For example if the goal is to decide which treatment is better it's not ethical any more to treat patients with the worse
17,354
What does it mean for a study to be over-powered?
Everything you've said makes sense (although I don't know what "big deal" you're referring to), and I esp. like your point about effect sizes as opposed to statistical significance. One other consideration is that some studies require the allocation of scarce resources to obtain the participation of each case, and so one wouldn't want to overdo it.
What does it mean for a study to be over-powered?
Everything you've said makes sense (although I don't know what "big deal" you're referring to), and I esp. like your point about effect sizes as opposed to statistical significance. One other conside
What does it mean for a study to be over-powered? Everything you've said makes sense (although I don't know what "big deal" you're referring to), and I esp. like your point about effect sizes as opposed to statistical significance. One other consideration is that some studies require the allocation of scarce resources to obtain the participation of each case, and so one wouldn't want to overdo it.
What does it mean for a study to be over-powered? Everything you've said makes sense (although I don't know what "big deal" you're referring to), and I esp. like your point about effect sizes as opposed to statistical significance. One other conside
17,355
What does it mean for a study to be over-powered?
My experience comes from A/B experiments online, where the issue is usually underpowered studies or measuring the wrong things. But it seems to me an overpowered study produces narrower confidence intervals than comparable studies, lower p-values, and possibly different variance. I imagine this can make it harder to compare similar studies. For example, if I repeated an overpowered study using proper power, my p-value would be higher even if I exactly replicated the effect. Increased sample size can even out variability or introduce variability if there are outliers which might have a higher chance of showing up in a larger sample. Also, my simulations show that effects other than the ones you are interested in might become significant with a larger sample. So, while the p-value correctly tells you the probability that your results are real, they could be real for reasons other than what you think e.g., a combination of chance, some transient effect you didn't control for, and perhaps some other smaller effect you introduced without realizing it. If the study is just a bit overpowered, the risk of this is low. The problem is often it's hard to know the adequate power e.g., if the baseline metrics and minimum target effect are guesses or turn out different than expected. I've also come across an article that argues that too large of a sample can make a goodness-of-fit test too sensitive to inconsequential deviations, leading to potentially counter-intuitive results. That said, I believe it best to err on the side of high rather than low power.
What does it mean for a study to be over-powered?
My experience comes from A/B experiments online, where the issue is usually underpowered studies or measuring the wrong things. But it seems to me an overpowered study produces narrower confidence int
What does it mean for a study to be over-powered? My experience comes from A/B experiments online, where the issue is usually underpowered studies or measuring the wrong things. But it seems to me an overpowered study produces narrower confidence intervals than comparable studies, lower p-values, and possibly different variance. I imagine this can make it harder to compare similar studies. For example, if I repeated an overpowered study using proper power, my p-value would be higher even if I exactly replicated the effect. Increased sample size can even out variability or introduce variability if there are outliers which might have a higher chance of showing up in a larger sample. Also, my simulations show that effects other than the ones you are interested in might become significant with a larger sample. So, while the p-value correctly tells you the probability that your results are real, they could be real for reasons other than what you think e.g., a combination of chance, some transient effect you didn't control for, and perhaps some other smaller effect you introduced without realizing it. If the study is just a bit overpowered, the risk of this is low. The problem is often it's hard to know the adequate power e.g., if the baseline metrics and minimum target effect are guesses or turn out different than expected. I've also come across an article that argues that too large of a sample can make a goodness-of-fit test too sensitive to inconsequential deviations, leading to potentially counter-intuitive results. That said, I believe it best to err on the side of high rather than low power.
What does it mean for a study to be over-powered? My experience comes from A/B experiments online, where the issue is usually underpowered studies or measuring the wrong things. But it seems to me an overpowered study produces narrower confidence int
17,356
Clustering: Should I use the Jensen-Shannon Divergence or its square?
I think it depends on how it is to be used. Just for reference for other readers, if $P$ and $Q$ are probability measures, then the Jensen-Shannon Divergence is $$ J(P,Q) = \frac{1}{2} \big( D(P \mid\mid R) + D(Q\mid\mid R) \big) $$ where $R = \frac{1}{2} (P + Q)$ is the mid-point measure and $D(\cdot\mid\mid\cdot)$ is the Kullback-Leibler divergence. Now, I would be tempted to use the square root of the Jensen-Shannon Divergence since it is a metric, i.e. it satisfies all the "intuitive" properties of a distance measure. For more details on this, see Endres and Schindelin, A new metric for probability distributions, IEEE Trans. on Info. Thy., vol. 49, no. 3, Jul. 2003, pp. 1858-1860. Of course, in some sense, it depends on what you need it for. If all you are using it for is to evaluate some pairwise measure, then any monotonic transformation of JSD would work. If you're looking for something that's closest to a "squared-distance", then the JSD itself is the analogous quantity. Incidentally, you might also be interested in this previous question and the associated answers and discussions.
Clustering: Should I use the Jensen-Shannon Divergence or its square?
I think it depends on how it is to be used. Just for reference for other readers, if $P$ and $Q$ are probability measures, then the Jensen-Shannon Divergence is $$ J(P,Q) = \frac{1}{2} \big( D(P \mid\
Clustering: Should I use the Jensen-Shannon Divergence or its square? I think it depends on how it is to be used. Just for reference for other readers, if $P$ and $Q$ are probability measures, then the Jensen-Shannon Divergence is $$ J(P,Q) = \frac{1}{2} \big( D(P \mid\mid R) + D(Q\mid\mid R) \big) $$ where $R = \frac{1}{2} (P + Q)$ is the mid-point measure and $D(\cdot\mid\mid\cdot)$ is the Kullback-Leibler divergence. Now, I would be tempted to use the square root of the Jensen-Shannon Divergence since it is a metric, i.e. it satisfies all the "intuitive" properties of a distance measure. For more details on this, see Endres and Schindelin, A new metric for probability distributions, IEEE Trans. on Info. Thy., vol. 49, no. 3, Jul. 2003, pp. 1858-1860. Of course, in some sense, it depends on what you need it for. If all you are using it for is to evaluate some pairwise measure, then any monotonic transformation of JSD would work. If you're looking for something that's closest to a "squared-distance", then the JSD itself is the analogous quantity. Incidentally, you might also be interested in this previous question and the associated answers and discussions.
Clustering: Should I use the Jensen-Shannon Divergence or its square? I think it depends on how it is to be used. Just for reference for other readers, if $P$ and $Q$ are probability measures, then the Jensen-Shannon Divergence is $$ J(P,Q) = \frac{1}{2} \big( D(P \mid\
17,357
Why is the second derivative required for newton's method for back-propagation?
My guess at your confusion: Newton's method is often used to solve two different (but related) problems: Find $x$ such that $f(x) = 0$ Find $x$ to minimize $g(x)$ A connection between the two problems if $g'(x)=0$ solves the minimization problem If $g$ is continuous and differentiable, a necessary condition for an optimum to unconstrained minimization problem (2) is that the derivative $g'(x) = 0$. Let $f(x) = g'(x)$. If the first order condition $g'(x) = 0$ is also a sufficient condition for an optimum (eg. $g$ is convex), then (1) and (2) are the same problem. Applying Newton's method, the update step for problem (1) is: $$ x_{t+1} = x_{t} - \frac{f(x_{t})}{f'(x_{t})}$$ The update step for problem (2) is: $$ x_{t+1} = x_{t} - \frac{g'(x_{t})}{g''(x_{t})}$$ As written, the update step for problem (2) has a 2nd derivative while the update step for problem one (1) only has a first derivative, but these are exactly the same update step if $f = g'$. In the optimization context, the Newton update step can be interpreted as creating a quadratic approximation of $g$ around point $x_t$. For each step $t$, create a function $\hat{g}_t$ that's the step $t$ quadratic approximation of $g$: $$\hat{g}_t(x) = g(x_t) + g'(x_t)(x - x_t) + \frac{1}{2}g''(x_t)(x - x_t)^2$$ then choose $x_{t+1}$ to minimize $\hat{g}_t$. Approximating $g$ as a quadratic is equivalent to approximating $g'$ as a line. Let $f = g'$. Then update step $t$ above is exactly the same as the canonical description of Newton Method: approximate $f$ as $\hat{f}_t (x) = f(x_t) + f'(x_t)(x - x_t)$ and set $x_{t+1}$ to be the value of $x$ where $\hat{f}_t$ crosses $0$.
Why is the second derivative required for newton's method for back-propagation?
My guess at your confusion: Newton's method is often used to solve two different (but related) problems: Find $x$ such that $f(x) = 0$ Find $x$ to minimize $g(x)$ A connection between the two proble
Why is the second derivative required for newton's method for back-propagation? My guess at your confusion: Newton's method is often used to solve two different (but related) problems: Find $x$ such that $f(x) = 0$ Find $x$ to minimize $g(x)$ A connection between the two problems if $g'(x)=0$ solves the minimization problem If $g$ is continuous and differentiable, a necessary condition for an optimum to unconstrained minimization problem (2) is that the derivative $g'(x) = 0$. Let $f(x) = g'(x)$. If the first order condition $g'(x) = 0$ is also a sufficient condition for an optimum (eg. $g$ is convex), then (1) and (2) are the same problem. Applying Newton's method, the update step for problem (1) is: $$ x_{t+1} = x_{t} - \frac{f(x_{t})}{f'(x_{t})}$$ The update step for problem (2) is: $$ x_{t+1} = x_{t} - \frac{g'(x_{t})}{g''(x_{t})}$$ As written, the update step for problem (2) has a 2nd derivative while the update step for problem one (1) only has a first derivative, but these are exactly the same update step if $f = g'$. In the optimization context, the Newton update step can be interpreted as creating a quadratic approximation of $g$ around point $x_t$. For each step $t$, create a function $\hat{g}_t$ that's the step $t$ quadratic approximation of $g$: $$\hat{g}_t(x) = g(x_t) + g'(x_t)(x - x_t) + \frac{1}{2}g''(x_t)(x - x_t)^2$$ then choose $x_{t+1}$ to minimize $\hat{g}_t$. Approximating $g$ as a quadratic is equivalent to approximating $g'$ as a line. Let $f = g'$. Then update step $t$ above is exactly the same as the canonical description of Newton Method: approximate $f$ as $\hat{f}_t (x) = f(x_t) + f'(x_t)(x - x_t)$ and set $x_{t+1}$ to be the value of $x$ where $\hat{f}_t$ crosses $0$.
Why is the second derivative required for newton's method for back-propagation? My guess at your confusion: Newton's method is often used to solve two different (but related) problems: Find $x$ such that $f(x) = 0$ Find $x$ to minimize $g(x)$ A connection between the two proble
17,358
Why is the second derivative required for newton's method for back-propagation?
Newton method for optimization approximates the curve with parabola, or a second degree polynomial $$f(x)=a+b(x-x_t)+\frac c2(x-x_t)^2$$ around the current guess $x_t$. If you look at the derivatives, you get $f'(x_t)=b$ and $f''(x_t)=c$. You could argue that a parabola approximation itself is rooted in Taylor approximation $$f(x)=f(0)+f'(x)x+\frac{f''(x)} {2!}x^2+\dots$$ That's all to it, really. Now, let's see how does this help in our problem: $$x_{min}=\mathrm{argmin} f(x)$$ The minimum is where $f'(x_{min})=0$, i.e. $$f'(x_{min})=b+c(\hat x_{min}-x_t)=0$$ $$\hat x_{min}=x_t-b/c$$ Using the derivatives we get the next guess $$x_{t+1}=x_t-\frac{f'(x_t)}{f''(x_t)}$$
Why is the second derivative required for newton's method for back-propagation?
Newton method for optimization approximates the curve with parabola, or a second degree polynomial $$f(x)=a+b(x-x_t)+\frac c2(x-x_t)^2$$ around the current guess $x_t$. If you look at the derivatives,
Why is the second derivative required for newton's method for back-propagation? Newton method for optimization approximates the curve with parabola, or a second degree polynomial $$f(x)=a+b(x-x_t)+\frac c2(x-x_t)^2$$ around the current guess $x_t$. If you look at the derivatives, you get $f'(x_t)=b$ and $f''(x_t)=c$. You could argue that a parabola approximation itself is rooted in Taylor approximation $$f(x)=f(0)+f'(x)x+\frac{f''(x)} {2!}x^2+\dots$$ That's all to it, really. Now, let's see how does this help in our problem: $$x_{min}=\mathrm{argmin} f(x)$$ The minimum is where $f'(x_{min})=0$, i.e. $$f'(x_{min})=b+c(\hat x_{min}-x_t)=0$$ $$\hat x_{min}=x_t-b/c$$ Using the derivatives we get the next guess $$x_{t+1}=x_t-\frac{f'(x_t)}{f''(x_t)}$$
Why is the second derivative required for newton's method for back-propagation? Newton method for optimization approximates the curve with parabola, or a second degree polynomial $$f(x)=a+b(x-x_t)+\frac c2(x-x_t)^2$$ around the current guess $x_t$. If you look at the derivatives,
17,359
Why is a 0-1 loss function intractable?
The 0-1 loss function is non-convex and discontinuous, so (sub)gradient methods cannot be applied. For binary classification with a linear separator, this loss function can be formulated as finding the $\beta$ that minimizes the average value of the indicator function $\mathbf{1}(y_{i}\beta\mathbf{x}_{i} \leq 0)$ over all $i$ samples. This is exponential in the inputs, as since there are two possible values for each pair, there are $2^{n}$ possible configurations to check for $n$ total sample points. This is known to be NP-hard. Knowing the current value of your loss function doesn’t provide any clue as to how you should possibly modify your current solution to improve, as you could derive if gradient methods for convex or continuous functions were available.
Why is a 0-1 loss function intractable?
The 0-1 loss function is non-convex and discontinuous, so (sub)gradient methods cannot be applied. For binary classification with a linear separator, this loss function can be formulated as finding th
Why is a 0-1 loss function intractable? The 0-1 loss function is non-convex and discontinuous, so (sub)gradient methods cannot be applied. For binary classification with a linear separator, this loss function can be formulated as finding the $\beta$ that minimizes the average value of the indicator function $\mathbf{1}(y_{i}\beta\mathbf{x}_{i} \leq 0)$ over all $i$ samples. This is exponential in the inputs, as since there are two possible values for each pair, there are $2^{n}$ possible configurations to check for $n$ total sample points. This is known to be NP-hard. Knowing the current value of your loss function doesn’t provide any clue as to how you should possibly modify your current solution to improve, as you could derive if gradient methods for convex or continuous functions were available.
Why is a 0-1 loss function intractable? The 0-1 loss function is non-convex and discontinuous, so (sub)gradient methods cannot be applied. For binary classification with a linear separator, this loss function can be formulated as finding th
17,360
Why is a 0-1 loss function intractable?
The classification error is in fact sometimes tractable. It can be optimized efficiently - though not exactly - using the Nelder-Mead method, as shown in this article: https://www.computer.org/csdl/trans/tp/1994/04/i0420-abs.html "Dimension reduction is the process of transforming multidimensional vectors into a low-dimensional space. In pattern recognition, it is often desired that this task be performed without significant loss of classification information. The Bayes error is an ideal criterion for this purpose; however, it is known to be notoriously difficult for mathematical treatment. Consequently, suboptimal criteria have been used in practice. We propose an alternative criterion, based on the estimate of the Bayes error, that is hopefully closer to the optimal criterion than the criteria currently in use. An algorithm for linear dimension reduction, based on this criterion, is conceived and implemented. Experiments demonstrate its superior performance in comparison with conventional algorithms." The Bayes error mentioned here is basically the 0-1 loss. This work was done in the context of linear dimension reduction. I don't know how effective it would be for training deep learning networks. But the point is, and the answer to the question: 0-1 loss is not universally intractable. It can be optimized relatively well for at least some types of models.
Why is a 0-1 loss function intractable?
The classification error is in fact sometimes tractable. It can be optimized efficiently - though not exactly - using the Nelder-Mead method, as shown in this article: https://www.computer.org/csdl/tr
Why is a 0-1 loss function intractable? The classification error is in fact sometimes tractable. It can be optimized efficiently - though not exactly - using the Nelder-Mead method, as shown in this article: https://www.computer.org/csdl/trans/tp/1994/04/i0420-abs.html "Dimension reduction is the process of transforming multidimensional vectors into a low-dimensional space. In pattern recognition, it is often desired that this task be performed without significant loss of classification information. The Bayes error is an ideal criterion for this purpose; however, it is known to be notoriously difficult for mathematical treatment. Consequently, suboptimal criteria have been used in practice. We propose an alternative criterion, based on the estimate of the Bayes error, that is hopefully closer to the optimal criterion than the criteria currently in use. An algorithm for linear dimension reduction, based on this criterion, is conceived and implemented. Experiments demonstrate its superior performance in comparison with conventional algorithms." The Bayes error mentioned here is basically the 0-1 loss. This work was done in the context of linear dimension reduction. I don't know how effective it would be for training deep learning networks. But the point is, and the answer to the question: 0-1 loss is not universally intractable. It can be optimized relatively well for at least some types of models.
Why is a 0-1 loss function intractable? The classification error is in fact sometimes tractable. It can be optimized efficiently - though not exactly - using the Nelder-Mead method, as shown in this article: https://www.computer.org/csdl/tr
17,361
What is the intuition behind second order differencing?
Second-order differencing is the discrete analogy to the second-derivative. For a discrete time-series, the second-order difference represents the curvature of the series at a given point in time. If the second-order difference is positive then the time-series is curving upward at that time, and if it is negative then the time series is curving downward at that time. The second-order difference of a discrete time series $\{ X_t | t \in \mathbb{Z} \}$ at time $t$ is: $$\begin{equation} \begin{aligned} \Delta^2 X_t = \Delta (\Delta X_t) &= \Delta (X_t-X_{t-1}) \\[6pt] &= \Delta X_t - \Delta X_{t-1} \\[6pt] &= (X_t-X_{t-1})-(X_{t-1}-X_{t-2}) \\[6pt] &= X_t - 2X_{t-1} + X_{t-2}. \\[6pt] \end{aligned} \end{equation}$$ This is positive if $\Delta X_t > \Delta X_{t-1}$ and negative if $\Delta X_t < \Delta X_{t-1}$ (and zero if $\Delta X_t = \Delta X_{t-1}$). If there is more upward (less downward) change in the series at this time than in the previous time, there is positive curvature, and if there is less upward (more downward) change in the series at this time than in the previous time, there is negative curvature.
What is the intuition behind second order differencing?
Second-order differencing is the discrete analogy to the second-derivative. For a discrete time-series, the second-order difference represents the curvature of the series at a given point in time. I
What is the intuition behind second order differencing? Second-order differencing is the discrete analogy to the second-derivative. For a discrete time-series, the second-order difference represents the curvature of the series at a given point in time. If the second-order difference is positive then the time-series is curving upward at that time, and if it is negative then the time series is curving downward at that time. The second-order difference of a discrete time series $\{ X_t | t \in \mathbb{Z} \}$ at time $t$ is: $$\begin{equation} \begin{aligned} \Delta^2 X_t = \Delta (\Delta X_t) &= \Delta (X_t-X_{t-1}) \\[6pt] &= \Delta X_t - \Delta X_{t-1} \\[6pt] &= (X_t-X_{t-1})-(X_{t-1}-X_{t-2}) \\[6pt] &= X_t - 2X_{t-1} + X_{t-2}. \\[6pt] \end{aligned} \end{equation}$$ This is positive if $\Delta X_t > \Delta X_{t-1}$ and negative if $\Delta X_t < \Delta X_{t-1}$ (and zero if $\Delta X_t = \Delta X_{t-1}$). If there is more upward (less downward) change in the series at this time than in the previous time, there is positive curvature, and if there is less upward (more downward) change in the series at this time than in the previous time, there is negative curvature.
What is the intuition behind second order differencing? Second-order differencing is the discrete analogy to the second-derivative. For a discrete time-series, the second-order difference represents the curvature of the series at a given point in time. I
17,362
What is the intuition behind second order differencing?
Two thoughts: Recursion. After you first-order difference, what do you have? Another time series which is, under the right conditions, closer to stationary. If it's not close enough, you now have a time series that's not stationary and you want to move it closer to stationary, so you take a first-order difference. (Which happens to be a second-order difference of the original time series.) If the differenced time series isn't close enough to stationary, you ... [recurse] ... Derivatives. Imagine you record your car's GPS location every 10 minutes. If I could take the GPS points from any two days and show them to you and you couldn't figure out which day it might've been -- perhaps couldn't even really tell one day from another -- your location data would be stationary. But say you drove to a different nearby city each day for two weeks? You'd easily be able to tell the difference between the days -- perhaps even knowing exactly which day I was showing you. Not stationary. Perhaps if you instead recorded your distance from home every 10 minutes, it would make your data more stationary. Distance doesn't include direction, so perhaps now your data for those two weeks would pretty much look the same? (Average location is home, for example.) Say, instead, that you chose to drive from New York straight through to Los Angeles. The distance trick wouldn't work, since your distance would give you a pretty clear distinction between days. But you might then choose to record your speed every 10 minutes instead. Driving cross country on the interstate system, you days would tend to look an a lot alike, speed-wise. That is, your speed would be stationary. Say, location at time 0 is $L_0$, and 10 and 20 minutes later is $L_1$ and $L_2$, respectively. The distance traveled in each 10-minute interval would be $D_1 = L_1 - L_0$ and $D_2 = L_2 - L_1$, which, when divided by the time interval yields the velocity (same units as speed but with direction). The second differential, $A_2 = D_2 - D_1 = L_2 - 2 L_1 + L_0$ is the acceleration. If the speed is stationary, and the vehicle is perpetually moving, the differences in location would also be stationary.
What is the intuition behind second order differencing?
Two thoughts: Recursion. After you first-order difference, what do you have? Another time series which is, under the right conditions, closer to stationary. If it's not close enough, you now have a ti
What is the intuition behind second order differencing? Two thoughts: Recursion. After you first-order difference, what do you have? Another time series which is, under the right conditions, closer to stationary. If it's not close enough, you now have a time series that's not stationary and you want to move it closer to stationary, so you take a first-order difference. (Which happens to be a second-order difference of the original time series.) If the differenced time series isn't close enough to stationary, you ... [recurse] ... Derivatives. Imagine you record your car's GPS location every 10 minutes. If I could take the GPS points from any two days and show them to you and you couldn't figure out which day it might've been -- perhaps couldn't even really tell one day from another -- your location data would be stationary. But say you drove to a different nearby city each day for two weeks? You'd easily be able to tell the difference between the days -- perhaps even knowing exactly which day I was showing you. Not stationary. Perhaps if you instead recorded your distance from home every 10 minutes, it would make your data more stationary. Distance doesn't include direction, so perhaps now your data for those two weeks would pretty much look the same? (Average location is home, for example.) Say, instead, that you chose to drive from New York straight through to Los Angeles. The distance trick wouldn't work, since your distance would give you a pretty clear distinction between days. But you might then choose to record your speed every 10 minutes instead. Driving cross country on the interstate system, you days would tend to look an a lot alike, speed-wise. That is, your speed would be stationary. Say, location at time 0 is $L_0$, and 10 and 20 minutes later is $L_1$ and $L_2$, respectively. The distance traveled in each 10-minute interval would be $D_1 = L_1 - L_0$ and $D_2 = L_2 - L_1$, which, when divided by the time interval yields the velocity (same units as speed but with direction). The second differential, $A_2 = D_2 - D_1 = L_2 - 2 L_1 + L_0$ is the acceleration. If the speed is stationary, and the vehicle is perpetually moving, the differences in location would also be stationary.
What is the intuition behind second order differencing? Two thoughts: Recursion. After you first-order difference, what do you have? Another time series which is, under the right conditions, closer to stationary. If it's not close enough, you now have a ti
17,363
Approximation error of confidence interval for the mean when $n \geq 30$
Why use normal approximation? It's as simple as saying that it's always better to use more information than less. The equation (1) uses Chebyshev's theorem. Note, how it doesn't use any information about your distribution's shape, i.e. it works for any distribution with a given variance. Hence, if you use some information about your distribution's shape you must get a better approximation. If you knew that your distribution is Gaussian, then by using this knowledge you get a better estimate. Since, you're already applying the central limit theorem, why not use the Gaussian approximation of the bounds? They're going to be better, actually, tighter (or sharper) because these estimates are based on the knowledge of the shape which is an additional piece of information. The rule of thumb 30 is a myth, which benefits from the confirmation bias. It just keeps being copied from one book to another. Once I found a reference suggesting this rule in a paper in 1950s. It wasn't any kind of solid proof, as I recall. It was some sort of empirical study. Basically, the only reason it's used is because it sort of works. You don't see it violated badly often. UPDATE Look up the paper by Zachary R. Smith and Craig S. Wells "Central Limit Theorem and Sample Size". They present an empirical study of the convergence to CLT for different kinds of distributions. The magic number 30 doesn't work in many cases, of course.
Approximation error of confidence interval for the mean when $n \geq 30$
Why use normal approximation? It's as simple as saying that it's always better to use more information than less. The equation (1) uses Chebyshev's theorem. Note, how it doesn't use any information ab
Approximation error of confidence interval for the mean when $n \geq 30$ Why use normal approximation? It's as simple as saying that it's always better to use more information than less. The equation (1) uses Chebyshev's theorem. Note, how it doesn't use any information about your distribution's shape, i.e. it works for any distribution with a given variance. Hence, if you use some information about your distribution's shape you must get a better approximation. If you knew that your distribution is Gaussian, then by using this knowledge you get a better estimate. Since, you're already applying the central limit theorem, why not use the Gaussian approximation of the bounds? They're going to be better, actually, tighter (or sharper) because these estimates are based on the knowledge of the shape which is an additional piece of information. The rule of thumb 30 is a myth, which benefits from the confirmation bias. It just keeps being copied from one book to another. Once I found a reference suggesting this rule in a paper in 1950s. It wasn't any kind of solid proof, as I recall. It was some sort of empirical study. Basically, the only reason it's used is because it sort of works. You don't see it violated badly often. UPDATE Look up the paper by Zachary R. Smith and Craig S. Wells "Central Limit Theorem and Sample Size". They present an empirical study of the convergence to CLT for different kinds of distributions. The magic number 30 doesn't work in many cases, of course.
Approximation error of confidence interval for the mean when $n \geq 30$ Why use normal approximation? It's as simple as saying that it's always better to use more information than less. The equation (1) uses Chebyshev's theorem. Note, how it doesn't use any information ab
17,364
Approximation error of confidence interval for the mean when $n \geq 30$
The issue with using the Chebyshev inequality to obtain an interval for the true value, is that it only gives you a lower bound for the probability, which moreover is sometimes trivial, or, in order not to be trivial, it may give a very wide confidence interval. We have $$P( | \bar X - \mu| > \varepsilon) = 1 - P(\bar X-\varepsilon \leq \mu \leq \bar X+\varepsilon)$$ $$\implies P(\bar X-\varepsilon \leq \mu \leq \bar X+\varepsilon) \geq 1- \frac{1}{n \varepsilon^2}$$ We see that, depending also on sample size, if we decrease $\varepsilon$ "too much" we will get the trivial answer "the probability is greater than zero". Apart from that, what we get from this approach is a conclusion of the form ""the probability of $\mu$ falling in $[\bar X \pm \varepsilon]$ is equal or greater than..." But let's assume that we're good with this, and denote $p_{min}$ the minimum probability with which we are comfortable. So we want $$ 1- \frac{1}{n \varepsilon^2} = p_{min} \implies \varepsilon = \sqrt {\frac {1}{(1-p_{min})n}}$$ With small sample sizes and high desired minimum probability, this may give an unsatisfactorily wide confidence interval. E.g. for $p_{min} =0.9$ and $n=100$ we will get $\varepsilon \approx .316$, which, for example for the variable treated by the OP that is bounded in $[0,1]$ appears to be too big to be useful. But the approach is valid, and distribution-free, and so there may be instances where it can be useful. One may want to check also the Vysochanskij–Petunin inequality mentioned in another answer, which holds for continuous unimodal distributions and refines Chebyshev's inequality.
Approximation error of confidence interval for the mean when $n \geq 30$
The issue with using the Chebyshev inequality to obtain an interval for the true value, is that it only gives you a lower bound for the probability, which moreover is sometimes trivial, or, in order n
Approximation error of confidence interval for the mean when $n \geq 30$ The issue with using the Chebyshev inequality to obtain an interval for the true value, is that it only gives you a lower bound for the probability, which moreover is sometimes trivial, or, in order not to be trivial, it may give a very wide confidence interval. We have $$P( | \bar X - \mu| > \varepsilon) = 1 - P(\bar X-\varepsilon \leq \mu \leq \bar X+\varepsilon)$$ $$\implies P(\bar X-\varepsilon \leq \mu \leq \bar X+\varepsilon) \geq 1- \frac{1}{n \varepsilon^2}$$ We see that, depending also on sample size, if we decrease $\varepsilon$ "too much" we will get the trivial answer "the probability is greater than zero". Apart from that, what we get from this approach is a conclusion of the form ""the probability of $\mu$ falling in $[\bar X \pm \varepsilon]$ is equal or greater than..." But let's assume that we're good with this, and denote $p_{min}$ the minimum probability with which we are comfortable. So we want $$ 1- \frac{1}{n \varepsilon^2} = p_{min} \implies \varepsilon = \sqrt {\frac {1}{(1-p_{min})n}}$$ With small sample sizes and high desired minimum probability, this may give an unsatisfactorily wide confidence interval. E.g. for $p_{min} =0.9$ and $n=100$ we will get $\varepsilon \approx .316$, which, for example for the variable treated by the OP that is bounded in $[0,1]$ appears to be too big to be useful. But the approach is valid, and distribution-free, and so there may be instances where it can be useful. One may want to check also the Vysochanskij–Petunin inequality mentioned in another answer, which holds for continuous unimodal distributions and refines Chebyshev's inequality.
Approximation error of confidence interval for the mean when $n \geq 30$ The issue with using the Chebyshev inequality to obtain an interval for the true value, is that it only gives you a lower bound for the probability, which moreover is sometimes trivial, or, in order n
17,365
Approximation error of confidence interval for the mean when $n \geq 30$
The short answer is that it can go pretty badly, but only if one or both tails of the sampling distribution is really fat. This R code generate a million sets of 30 gamma-distributed variables and take their mean; it can be used to get a sense of what the sampling distribution of the mean looks like. If the normal approximation works as intended, the results should be approximately normal with mean 1 and variance 1/(30 * shape). f = function(shape){replicate(1E6, mean(rgamma(30, shape, shape)))} When shape is 1.0, the gamma distribution becomes an exponential distribution, which is pretty non-normal. Nevertheless, the non-Gaussian parts mostly average out and so Gaussian approximation isn't so bad: There's clearly some bias, and it would be good to avoid that when possible. But honestly, that level of bias probably won't be the biggest problem facing a typical study. That said, things can get much worse. With f(0.01), the histogram looks like this: Log-transforming the 30 sampled data points before averaging helps a lot, though: In general, distributions with long tails (on one or both sides of the distribution) will require the most samples before the Gaussian approximation starts to become reliable. There are even pathological cases where there will literally never be enough data for the Gaussian approximation to work, but you'll probably have more serious problems in that case (because the sampling distribution doesn't have a well-defined mean or variance to begin with).
Approximation error of confidence interval for the mean when $n \geq 30$
The short answer is that it can go pretty badly, but only if one or both tails of the sampling distribution is really fat. This R code generate a million sets of 30 gamma-distributed variables and tak
Approximation error of confidence interval for the mean when $n \geq 30$ The short answer is that it can go pretty badly, but only if one or both tails of the sampling distribution is really fat. This R code generate a million sets of 30 gamma-distributed variables and take their mean; it can be used to get a sense of what the sampling distribution of the mean looks like. If the normal approximation works as intended, the results should be approximately normal with mean 1 and variance 1/(30 * shape). f = function(shape){replicate(1E6, mean(rgamma(30, shape, shape)))} When shape is 1.0, the gamma distribution becomes an exponential distribution, which is pretty non-normal. Nevertheless, the non-Gaussian parts mostly average out and so Gaussian approximation isn't so bad: There's clearly some bias, and it would be good to avoid that when possible. But honestly, that level of bias probably won't be the biggest problem facing a typical study. That said, things can get much worse. With f(0.01), the histogram looks like this: Log-transforming the 30 sampled data points before averaging helps a lot, though: In general, distributions with long tails (on one or both sides of the distribution) will require the most samples before the Gaussian approximation starts to become reliable. There are even pathological cases where there will literally never be enough data for the Gaussian approximation to work, but you'll probably have more serious problems in that case (because the sampling distribution doesn't have a well-defined mean or variance to begin with).
Approximation error of confidence interval for the mean when $n \geq 30$ The short answer is that it can go pretty badly, but only if one or both tails of the sampling distribution is really fat. This R code generate a million sets of 30 gamma-distributed variables and tak
17,366
Approximation error of confidence interval for the mean when $n \geq 30$
Problem with the Chebyshev confidence interval As mentioned by Carlo, we have $\sigma^2 \le \frac{1}{4}$. This follows from $\text{Var}(X) \le \mu(1-\mu)$. Therefore a confidence interval for $\mu$ is given by $$ P(|\bar{X}-\mu| \geq \varepsilon) \le \frac{1}{4n\varepsilon^2}. $$ The problem is that the inequality is, in a certain sense, quite loose when $n$ gets large. An improvement is given by Hoeffding's bound and shown below. However, we can also demonstrate how bad it can get using the Berry-Esseen theorem, pointed out by Yves. Let $X_i$ have a variance $\tfrac{1}{4}$, the worst possible case. The theorem implies that $ P(|\bar X - \mu| \geq \tfrac{\varepsilon}{2\sqrt{n}}) \le 2\, \text{SF}(\varepsilon) + \tfrac{8}{\sqrt{n}}, $ where $\text{SF}$ is the survival function of the standard normal distribution. In particular, with $\varepsilon = 16$, we get $\text{SF}(16) \approx e^{-58}$ (according to Scipy), so that essentially $$ P(|\bar X - \mu| \geq \tfrac{8}{\sqrt{n}}) \le \tfrac{8}{\sqrt{n}} + 0, \qquad (*) $$ whereas the Chebyshev inequality implies $$ P(|\bar X - \mu| \geq \tfrac{8}{\sqrt{n}}) \le \tfrac{1}{256}. $$ Note that I did not try to optimize the bound given in $(*)$, the result here is only of conceptual interest. Comparing the lengths of the confidence intervals Consider the $(1-\alpha)$-level confidence interval lengths $\ell_Z(\alpha, n)$ and $\ell_C(\alpha, n)$ obtained using the normal approximation ($\sigma = \tfrac{1}{2}$) and the Chebyshev inequality, repectively. It turns out that $\ell_C(\alpha, n)$ is a constant times bigger than $\ell_Z(\alpha, n)$, independently of $n$. Precisely, for all $n$, $$ \ell_C(\alpha, n) = \kappa(\alpha) \ell_Z(\alpha, n), \quad \kappa(\alpha) = \left(\text{ISF}\left(\tfrac{\alpha}{2}\right) \sqrt{\alpha}\right)^{-1}, $$ where $\text{ISF}$ is the inverse survival function of the standard normal distribution. I plot below the multiplicative constant. $\hskip 1in$ In particular, the $95\%$ level confidence interval obtained using the Chebyshev inequality is about $2.3$ times bigger than the same level confidence interval obtained using the normal approximation. Using Hoeffding's bound Hoeffding's bound gives $$ P(|\bar X - \mu| \geq \varepsilon) \leq 2e^{-2n \varepsilon^2}. $$ Thus an $(1-\alpha)$-level confidence interval for $\mu$ is $$ (\bar X - \varepsilon, \bar X + \varepsilon), \quad \varepsilon = \sqrt{\frac{-\ln \tfrac{\alpha}{2}}{2n}}, $$ of length $\ell_H (\alpha, n) = 2\varepsilon$. I plot below the lengths of the different confidence intervals (Chebyshev inequality: $\ell_C$; normal approximation ($\sigma = 1/2$): $\ell_Z$; Hoeffding's inequality: $\ell_H$) for $\alpha = 0.05$. $\hskip 0.5in$
Approximation error of confidence interval for the mean when $n \geq 30$
Problem with the Chebyshev confidence interval As mentioned by Carlo, we have $\sigma^2 \le \frac{1}{4}$. This follows from $\text{Var}(X) \le \mu(1-\mu)$. Therefore a confidence interval for $\mu$ is
Approximation error of confidence interval for the mean when $n \geq 30$ Problem with the Chebyshev confidence interval As mentioned by Carlo, we have $\sigma^2 \le \frac{1}{4}$. This follows from $\text{Var}(X) \le \mu(1-\mu)$. Therefore a confidence interval for $\mu$ is given by $$ P(|\bar{X}-\mu| \geq \varepsilon) \le \frac{1}{4n\varepsilon^2}. $$ The problem is that the inequality is, in a certain sense, quite loose when $n$ gets large. An improvement is given by Hoeffding's bound and shown below. However, we can also demonstrate how bad it can get using the Berry-Esseen theorem, pointed out by Yves. Let $X_i$ have a variance $\tfrac{1}{4}$, the worst possible case. The theorem implies that $ P(|\bar X - \mu| \geq \tfrac{\varepsilon}{2\sqrt{n}}) \le 2\, \text{SF}(\varepsilon) + \tfrac{8}{\sqrt{n}}, $ where $\text{SF}$ is the survival function of the standard normal distribution. In particular, with $\varepsilon = 16$, we get $\text{SF}(16) \approx e^{-58}$ (according to Scipy), so that essentially $$ P(|\bar X - \mu| \geq \tfrac{8}{\sqrt{n}}) \le \tfrac{8}{\sqrt{n}} + 0, \qquad (*) $$ whereas the Chebyshev inequality implies $$ P(|\bar X - \mu| \geq \tfrac{8}{\sqrt{n}}) \le \tfrac{1}{256}. $$ Note that I did not try to optimize the bound given in $(*)$, the result here is only of conceptual interest. Comparing the lengths of the confidence intervals Consider the $(1-\alpha)$-level confidence interval lengths $\ell_Z(\alpha, n)$ and $\ell_C(\alpha, n)$ obtained using the normal approximation ($\sigma = \tfrac{1}{2}$) and the Chebyshev inequality, repectively. It turns out that $\ell_C(\alpha, n)$ is a constant times bigger than $\ell_Z(\alpha, n)$, independently of $n$. Precisely, for all $n$, $$ \ell_C(\alpha, n) = \kappa(\alpha) \ell_Z(\alpha, n), \quad \kappa(\alpha) = \left(\text{ISF}\left(\tfrac{\alpha}{2}\right) \sqrt{\alpha}\right)^{-1}, $$ where $\text{ISF}$ is the inverse survival function of the standard normal distribution. I plot below the multiplicative constant. $\hskip 1in$ In particular, the $95\%$ level confidence interval obtained using the Chebyshev inequality is about $2.3$ times bigger than the same level confidence interval obtained using the normal approximation. Using Hoeffding's bound Hoeffding's bound gives $$ P(|\bar X - \mu| \geq \varepsilon) \leq 2e^{-2n \varepsilon^2}. $$ Thus an $(1-\alpha)$-level confidence interval for $\mu$ is $$ (\bar X - \varepsilon, \bar X + \varepsilon), \quad \varepsilon = \sqrt{\frac{-\ln \tfrac{\alpha}{2}}{2n}}, $$ of length $\ell_H (\alpha, n) = 2\varepsilon$. I plot below the lengths of the different confidence intervals (Chebyshev inequality: $\ell_C$; normal approximation ($\sigma = 1/2$): $\ell_Z$; Hoeffding's inequality: $\ell_H$) for $\alpha = 0.05$. $\hskip 0.5in$
Approximation error of confidence interval for the mean when $n \geq 30$ Problem with the Chebyshev confidence interval As mentioned by Carlo, we have $\sigma^2 \le \frac{1}{4}$. This follows from $\text{Var}(X) \le \mu(1-\mu)$. Therefore a confidence interval for $\mu$ is
17,367
Approximation error of confidence interval for the mean when $n \geq 30$
let's start with the number 30: it's, as anyone will say, a rule of thumb. but how can we find a number that fits better to our data? It's actually mostly a matter of skewness: even the strangest distribution will fast converge to normal if they are simmetric and continuous, skewed data will be much slower. I remember learning that a binomial distribution can be properly approximated to normal when its variance is greater than 9; for this example it's to be considered that discrete distribution also have the problem that they need great numbers to simulate continuity, but think to this: a simmetric binomial distribution will reach that variance with n = 36, if p = 0.1 instead, n must go up to 100 (variabile trasformation, however, would help a lot)! If you only want to use variance instead, dropping gaussian approximation, consider Vysochanskij–Petunin inequality over Chebichev's, it needs the assumption of unimodal distribution of the mean, but this is a very safe one with any sample size, I'd say, greater than 2.
Approximation error of confidence interval for the mean when $n \geq 30$
let's start with the number 30: it's, as anyone will say, a rule of thumb. but how can we find a number that fits better to our data? It's actually mostly a matter of skewness: even the strangest dist
Approximation error of confidence interval for the mean when $n \geq 30$ let's start with the number 30: it's, as anyone will say, a rule of thumb. but how can we find a number that fits better to our data? It's actually mostly a matter of skewness: even the strangest distribution will fast converge to normal if they are simmetric and continuous, skewed data will be much slower. I remember learning that a binomial distribution can be properly approximated to normal when its variance is greater than 9; for this example it's to be considered that discrete distribution also have the problem that they need great numbers to simulate continuity, but think to this: a simmetric binomial distribution will reach that variance with n = 36, if p = 0.1 instead, n must go up to 100 (variabile trasformation, however, would help a lot)! If you only want to use variance instead, dropping gaussian approximation, consider Vysochanskij–Petunin inequality over Chebichev's, it needs the assumption of unimodal distribution of the mean, but this is a very safe one with any sample size, I'd say, greater than 2.
Approximation error of confidence interval for the mean when $n \geq 30$ let's start with the number 30: it's, as anyone will say, a rule of thumb. but how can we find a number that fits better to our data? It's actually mostly a matter of skewness: even the strangest dist
17,368
Difference between preprocessing train and test set before and after splitting
No, Both approaches are not equivalent. StandardScaler() standardize features by removing the mean and scaling to unit variance If you fit the scaler after splitting: Suppose, if there are any outliers in the test set(after Splitting), the Scaler would not consider those in computing mean and Variance. If you fit the scaler on whole dataset and then split, Scaler would consider all values while computing mean and Variance. Since, the mean and variance are different in both cases, the fits and transform functions would perform differently.
Difference between preprocessing train and test set before and after splitting
No, Both approaches are not equivalent. StandardScaler() standardize features by removing the mean and scaling to unit variance If you fit the scaler after splitting: Suppose, if there are any outlie
Difference between preprocessing train and test set before and after splitting No, Both approaches are not equivalent. StandardScaler() standardize features by removing the mean and scaling to unit variance If you fit the scaler after splitting: Suppose, if there are any outliers in the test set(after Splitting), the Scaler would not consider those in computing mean and Variance. If you fit the scaler on whole dataset and then split, Scaler would consider all values while computing mean and Variance. Since, the mean and variance are different in both cases, the fits and transform functions would perform differently.
Difference between preprocessing train and test set before and after splitting No, Both approaches are not equivalent. StandardScaler() standardize features by removing the mean and scaling to unit variance If you fit the scaler after splitting: Suppose, if there are any outlie
17,369
Difference between preprocessing train and test set before and after splitting
To add to phanny's answer - you should do the preprocessing on your training set separately, otherwise information from the test set will "leak" into your training data. For preprocessing the test set, I do not see why you shouldn't preprocess it together with your training data.
Difference between preprocessing train and test set before and after splitting
To add to phanny's answer - you should do the preprocessing on your training set separately, otherwise information from the test set will "leak" into your training data. For preprocessing the test set
Difference between preprocessing train and test set before and after splitting To add to phanny's answer - you should do the preprocessing on your training set separately, otherwise information from the test set will "leak" into your training data. For preprocessing the test set, I do not see why you shouldn't preprocess it together with your training data.
Difference between preprocessing train and test set before and after splitting To add to phanny's answer - you should do the preprocessing on your training set separately, otherwise information from the test set will "leak" into your training data. For preprocessing the test set
17,370
Difference between preprocessing train and test set before and after splitting
The test set should ideally not be preprocessed with the training data. This will ensure no 'peeking ahead'. Train data should be preprocessed separately and once the model is created we can apply the same preprocessing parameters used for the train set, onto the test set as though the test set didn't exist before.
Difference between preprocessing train and test set before and after splitting
The test set should ideally not be preprocessed with the training data. This will ensure no 'peeking ahead'. Train data should be preprocessed separately and once the model is created we can apply the
Difference between preprocessing train and test set before and after splitting The test set should ideally not be preprocessed with the training data. This will ensure no 'peeking ahead'. Train data should be preprocessed separately and once the model is created we can apply the same preprocessing parameters used for the train set, onto the test set as though the test set didn't exist before.
Difference between preprocessing train and test set before and after splitting The test set should ideally not be preprocessed with the training data. This will ensure no 'peeking ahead'. Train data should be preprocessed separately and once the model is created we can apply the
17,371
Difference between preprocessing train and test set before and after splitting
You can also use the method below will preprocess your data separately but similar parameter used for training data set. norm = preprocessing.Normalizer().fit(xtrain) then x_train_norm = norm.transform(xtrain) x_test_norm = norm.transform(Xtest)
Difference between preprocessing train and test set before and after splitting
You can also use the method below will preprocess your data separately but similar parameter used for training data set. norm = preprocessing.Normalizer().fit(xtrain) then x_train_norm = norm.trans
Difference between preprocessing train and test set before and after splitting You can also use the method below will preprocess your data separately but similar parameter used for training data set. norm = preprocessing.Normalizer().fit(xtrain) then x_train_norm = norm.transform(xtrain) x_test_norm = norm.transform(Xtest)
Difference between preprocessing train and test set before and after splitting You can also use the method below will preprocess your data separately but similar parameter used for training data set. norm = preprocessing.Normalizer().fit(xtrain) then x_train_norm = norm.trans
17,372
If "Standard error" and "Confidence intervals" measure precision of measurement, then what are the measurements of accuracy?
Precision can be estimated directly from your data points, but accuracy is related to the experimental design. Suppose I want to find the average height of American males. Given a sample of heights, I can estimate my precision. If my sample is taken from all basketball players, however, my estimate will be biased and inaccurate, and this inaccuracy cannot be identified from the sample itself. One way of measuring accuracy is by performing calibration of your measurement platform. By using your platform to measure a known quantity, you can reliably test the accuracy of your method. This could help you find measurement bias, e.g., if your tape measure for the height example was missing an inch, you would recognize that all your calibration samples read an inch too short. It wouldn't help fix your experimental design problem, though.
If "Standard error" and "Confidence intervals" measure precision of measurement, then what are the m
Precision can be estimated directly from your data points, but accuracy is related to the experimental design. Suppose I want to find the average height of American males. Given a sample of heights, I
If "Standard error" and "Confidence intervals" measure precision of measurement, then what are the measurements of accuracy? Precision can be estimated directly from your data points, but accuracy is related to the experimental design. Suppose I want to find the average height of American males. Given a sample of heights, I can estimate my precision. If my sample is taken from all basketball players, however, my estimate will be biased and inaccurate, and this inaccuracy cannot be identified from the sample itself. One way of measuring accuracy is by performing calibration of your measurement platform. By using your platform to measure a known quantity, you can reliably test the accuracy of your method. This could help you find measurement bias, e.g., if your tape measure for the height example was missing an inch, you would recognize that all your calibration samples read an inch too short. It wouldn't help fix your experimental design problem, though.
If "Standard error" and "Confidence intervals" measure precision of measurement, then what are the m Precision can be estimated directly from your data points, but accuracy is related to the experimental design. Suppose I want to find the average height of American males. Given a sample of heights, I
17,373
If "Standard error" and "Confidence intervals" measure precision of measurement, then what are the measurements of accuracy?
The presicion is driven by the random errors, and accuracy is defined by systematic errors. The precision often can be increased by repeated trials increasing the sample size. Accuracy cannot be fixed by collecting more data of the same measurement because systematic error won't go away. Systematic error leads to bias of the mean and cannot be determined or fixed within the same experiment. Consider this: the whole point of your experiment is often in detecting the effect, such as deviation from zero. You measure the significance by comparing the deviation to the standard error, but that deviation may itself be a bias (systematic error)! That's why the systematic error is the worst kind of error in physical science. In physics, for instance, you're supposed to determine the bias (systematic error) outside your experiment, then correct for it in your measurements. Interestingly, in economic forecasting field the biggest problem is the shifts of the mean, which basically an equivalent of systematic error or bias in physical sciences. You may remember how much embarrassment the systematic error caused to the OPERA guys who "detected" neutrinos moving faster than light! They didn't account for a bunch of sources of systematic errors, and had to rescind the conclusion. After all, neutrino do not breach the speed of light, bummer!
If "Standard error" and "Confidence intervals" measure precision of measurement, then what are the m
The presicion is driven by the random errors, and accuracy is defined by systematic errors. The precision often can be increased by repeated trials increasing the sample size. Accuracy cannot be fixed
If "Standard error" and "Confidence intervals" measure precision of measurement, then what are the measurements of accuracy? The presicion is driven by the random errors, and accuracy is defined by systematic errors. The precision often can be increased by repeated trials increasing the sample size. Accuracy cannot be fixed by collecting more data of the same measurement because systematic error won't go away. Systematic error leads to bias of the mean and cannot be determined or fixed within the same experiment. Consider this: the whole point of your experiment is often in detecting the effect, such as deviation from zero. You measure the significance by comparing the deviation to the standard error, but that deviation may itself be a bias (systematic error)! That's why the systematic error is the worst kind of error in physical science. In physics, for instance, you're supposed to determine the bias (systematic error) outside your experiment, then correct for it in your measurements. Interestingly, in economic forecasting field the biggest problem is the shifts of the mean, which basically an equivalent of systematic error or bias in physical sciences. You may remember how much embarrassment the systematic error caused to the OPERA guys who "detected" neutrinos moving faster than light! They didn't account for a bunch of sources of systematic errors, and had to rescind the conclusion. After all, neutrino do not breach the speed of light, bummer!
If "Standard error" and "Confidence intervals" measure precision of measurement, then what are the m The presicion is driven by the random errors, and accuracy is defined by systematic errors. The precision often can be increased by repeated trials increasing the sample size. Accuracy cannot be fixed
17,374
Non-linearity before final Softmax layer in a convolutional neural network
You should not use a non-linearity for the last layer before the softmax classification. The ReLU non-linearity (used now almost exclusively) will in this case simply throw away information without adding any additional benefit. You can look at the caffe implementation of the well-known AlexNet for a reference of what's done in practice.
Non-linearity before final Softmax layer in a convolutional neural network
You should not use a non-linearity for the last layer before the softmax classification. The ReLU non-linearity (used now almost exclusively) will in this case simply throw away information without ad
Non-linearity before final Softmax layer in a convolutional neural network You should not use a non-linearity for the last layer before the softmax classification. The ReLU non-linearity (used now almost exclusively) will in this case simply throw away information without adding any additional benefit. You can look at the caffe implementation of the well-known AlexNet for a reference of what's done in practice.
Non-linearity before final Softmax layer in a convolutional neural network You should not use a non-linearity for the last layer before the softmax classification. The ReLU non-linearity (used now almost exclusively) will in this case simply throw away information without ad
17,375
Non-linearity before final Softmax layer in a convolutional neural network
You might want to send a negative value into the softmax function, to indicate that an event has low probability. If you pass the input values into a relu, then the network isn't going to pass any gradient through the units where the input to the relu is negative. So while the expressive power of the softmax isn't changed, it will probably make learning a lot harder.
Non-linearity before final Softmax layer in a convolutional neural network
You might want to send a negative value into the softmax function, to indicate that an event has low probability. If you pass the input values into a relu, then the network isn't going to pass any gr
Non-linearity before final Softmax layer in a convolutional neural network You might want to send a negative value into the softmax function, to indicate that an event has low probability. If you pass the input values into a relu, then the network isn't going to pass any gradient through the units where the input to the relu is negative. So while the expressive power of the softmax isn't changed, it will probably make learning a lot harder.
Non-linearity before final Softmax layer in a convolutional neural network You might want to send a negative value into the softmax function, to indicate that an event has low probability. If you pass the input values into a relu, then the network isn't going to pass any gr
17,376
Non-linearity before final Softmax layer in a convolutional neural network
The answer is not yes or no. It strongly depends on your expectation you have about your network. I assume that you want to have a good classifier, possibly applicable to a wide range of problems. Therefore, the non-linearity can be helpful to capture non-trivial classes. The non-linearity might be included either in the last layer before the soft-max layer or it can be in the preceding layer.
Non-linearity before final Softmax layer in a convolutional neural network
The answer is not yes or no. It strongly depends on your expectation you have about your network. I assume that you want to have a good classifier, possibly applicable to a wide range of problems. The
Non-linearity before final Softmax layer in a convolutional neural network The answer is not yes or no. It strongly depends on your expectation you have about your network. I assume that you want to have a good classifier, possibly applicable to a wide range of problems. Therefore, the non-linearity can be helpful to capture non-trivial classes. The non-linearity might be included either in the last layer before the soft-max layer or it can be in the preceding layer.
Non-linearity before final Softmax layer in a convolutional neural network The answer is not yes or no. It strongly depends on your expectation you have about your network. I assume that you want to have a good classifier, possibly applicable to a wide range of problems. The
17,377
Chi-squared test with scipy: what's the difference between chi2_contingency and chisquare?
Probably you have solved it, but I let this here to help anyone that is lost, like I was. The difference is the Null Hypothesis. scipy.stats.chi2_contingency, from Scipy: "Chi-square test of independence of variables in a contingency table" In this test you are testing if there is there is relationship between two or more variable. This is called chi-square test for independence, also called Pearson's chi-square test or the chi-square test of association. In this test you are testing the association between two or more variable. The null hupothesis, in your example, is "there is no effect of group in choosing the equipment to use". In scipy.stats.chisquare from Scipy "The chi square test tests the null hypothesis that the categorical data has the given frequencies." Here you are comparing if there is difference between an observation and an expected frequency. So, the null hupothesis, is that "there isn't any difference between observed and the expected". Here, the test is used to compare the observed sample distribution with the expected probability distribution. This is named Chi-Square goodness of fit test
Chi-squared test with scipy: what's the difference between chi2_contingency and chisquare?
Probably you have solved it, but I let this here to help anyone that is lost, like I was. The difference is the Null Hypothesis. scipy.stats.chi2_contingency, from Scipy: "Chi-square test of independ
Chi-squared test with scipy: what's the difference between chi2_contingency and chisquare? Probably you have solved it, but I let this here to help anyone that is lost, like I was. The difference is the Null Hypothesis. scipy.stats.chi2_contingency, from Scipy: "Chi-square test of independence of variables in a contingency table" In this test you are testing if there is there is relationship between two or more variable. This is called chi-square test for independence, also called Pearson's chi-square test or the chi-square test of association. In this test you are testing the association between two or more variable. The null hupothesis, in your example, is "there is no effect of group in choosing the equipment to use". In scipy.stats.chisquare from Scipy "The chi square test tests the null hypothesis that the categorical data has the given frequencies." Here you are comparing if there is difference between an observation and an expected frequency. So, the null hupothesis, is that "there isn't any difference between observed and the expected". Here, the test is used to compare the observed sample distribution with the expected probability distribution. This is named Chi-Square goodness of fit test
Chi-squared test with scipy: what's the difference between chi2_contingency and chisquare? Probably you have solved it, but I let this here to help anyone that is lost, like I was. The difference is the Null Hypothesis. scipy.stats.chi2_contingency, from Scipy: "Chi-square test of independ
17,378
Chi-squared test with scipy: what's the difference between chi2_contingency and chisquare?
Your code is valid. You use chi2_contingency when you want to test whether two (or more) groups have the save distribution. Null hypothesis: the two groups have no significant difference. You use chisquare when you want to test whether one (discrete) random variable has a specific distribution. Null hypothesis: the random variable is not significantly different from the specified distribution. For example, you toss a coin 1100 times and get 553 heads 547 tails. You hypothesize it has a probability of 0.5 to get a head. >> _, pvalue = chisquare([553, 547], [1100 * 0.5, 1100 * 0.5]) >> print(pvalue) 0.8564407259982999 So p > 0.1, it's not significant, you don't reject the hypothesis. In summary, you use chi2_contingency when you don't know the underlying distribution but you want to test whether two (or more) groups have the same distribution. You use chisquare when you have a distribution in mind and you want to test whether a group matches that distribution.
Chi-squared test with scipy: what's the difference between chi2_contingency and chisquare?
Your code is valid. You use chi2_contingency when you want to test whether two (or more) groups have the save distribution. Null hypothesis: the two groups have no significant difference. You use chis
Chi-squared test with scipy: what's the difference between chi2_contingency and chisquare? Your code is valid. You use chi2_contingency when you want to test whether two (or more) groups have the save distribution. Null hypothesis: the two groups have no significant difference. You use chisquare when you want to test whether one (discrete) random variable has a specific distribution. Null hypothesis: the random variable is not significantly different from the specified distribution. For example, you toss a coin 1100 times and get 553 heads 547 tails. You hypothesize it has a probability of 0.5 to get a head. >> _, pvalue = chisquare([553, 547], [1100 * 0.5, 1100 * 0.5]) >> print(pvalue) 0.8564407259982999 So p > 0.1, it's not significant, you don't reject the hypothesis. In summary, you use chi2_contingency when you don't know the underlying distribution but you want to test whether two (or more) groups have the same distribution. You use chisquare when you have a distribution in mind and you want to test whether a group matches that distribution.
Chi-squared test with scipy: what's the difference between chi2_contingency and chisquare? Your code is valid. You use chi2_contingency when you want to test whether two (or more) groups have the save distribution. Null hypothesis: the two groups have no significant difference. You use chis
17,379
what does an actual vs fitted graph tell us?
Scatter plots of Actual vs Predicted are one of the richest form of data visualization. You can tell pretty much everything from it. Ideally, all your points should be close to a regressed diagonal line. So, if the Actual is 5, your predicted should be reasonably close to 5 to. If the Actual is 30, your predicted should also be reasonably close to 30. So, just draw such a diagonal line within your graph and check out where the points lie. If your model had a high R Square, all the points would be close to this diagonal line. The lower the R Square, the weaker the Goodness of fit of your model, the more foggy or dispersed your points are (away from this diagonal line). You will see that your model seems to have three subsections of performance. The first one is where Actuals have values between 0 and 10. Within this zone, your model does not seem too bad. The second one is when Actuals are between 10 and 20, within this zone your model is essentially random. There is virtually no relationship between your model's predicted values and Actuals. The third zone is for Actuals >20. Within this zone, your model steadily greatly underestimates the Actual values. From this scatter plot, you can tell other issues related to your model. The residuals are heteroskedastic. This means the variance of the error is not constant across various levels of your dependent variable. As a result, the standard errors of your regression coefficients are unreliable and may be understated. In turn, this means that the statistical significance of your independent variables may be overstated. In other words, they may not be statistically significant. Because of the heteroskedastic issue, you actually can't tell. Although you can't be sure from this scatter plot, it appears likely that your residuals are autocorrelated. If your dependent variable is a time series that grows over time, they definitely are. You can see that between 10 and 20 the vast majority of your residuals are positive. And, >20 they are all negative. If your independent variable is indeed a time series that grows over time it has a Unit Root issue, meaning it is trending ever upward and is nonstationary. You have to transform it to build a robust model.
what does an actual vs fitted graph tell us?
Scatter plots of Actual vs Predicted are one of the richest form of data visualization. You can tell pretty much everything from it. Ideally, all your points should be close to a regressed diagonal
what does an actual vs fitted graph tell us? Scatter plots of Actual vs Predicted are one of the richest form of data visualization. You can tell pretty much everything from it. Ideally, all your points should be close to a regressed diagonal line. So, if the Actual is 5, your predicted should be reasonably close to 5 to. If the Actual is 30, your predicted should also be reasonably close to 30. So, just draw such a diagonal line within your graph and check out where the points lie. If your model had a high R Square, all the points would be close to this diagonal line. The lower the R Square, the weaker the Goodness of fit of your model, the more foggy or dispersed your points are (away from this diagonal line). You will see that your model seems to have three subsections of performance. The first one is where Actuals have values between 0 and 10. Within this zone, your model does not seem too bad. The second one is when Actuals are between 10 and 20, within this zone your model is essentially random. There is virtually no relationship between your model's predicted values and Actuals. The third zone is for Actuals >20. Within this zone, your model steadily greatly underestimates the Actual values. From this scatter plot, you can tell other issues related to your model. The residuals are heteroskedastic. This means the variance of the error is not constant across various levels of your dependent variable. As a result, the standard errors of your regression coefficients are unreliable and may be understated. In turn, this means that the statistical significance of your independent variables may be overstated. In other words, they may not be statistically significant. Because of the heteroskedastic issue, you actually can't tell. Although you can't be sure from this scatter plot, it appears likely that your residuals are autocorrelated. If your dependent variable is a time series that grows over time, they definitely are. You can see that between 10 and 20 the vast majority of your residuals are positive. And, >20 they are all negative. If your independent variable is indeed a time series that grows over time it has a Unit Root issue, meaning it is trending ever upward and is nonstationary. You have to transform it to build a robust model.
what does an actual vs fitted graph tell us? Scatter plots of Actual vs Predicted are one of the richest form of data visualization. You can tell pretty much everything from it. Ideally, all your points should be close to a regressed diagonal
17,380
what does an actual vs fitted graph tell us?
For perfect prediction, you would have Predicted=Actual, or $x=y$, so when you draw that line through this graph you see how much the prediction deviated from actual value (the prediction error). In the graph, the prediction was mostly overestimating the actual outcome $(y>x)$.
what does an actual vs fitted graph tell us?
For perfect prediction, you would have Predicted=Actual, or $x=y$, so when you draw that line through this graph you see how much the prediction deviated from actual value (the prediction error). In t
what does an actual vs fitted graph tell us? For perfect prediction, you would have Predicted=Actual, or $x=y$, so when you draw that line through this graph you see how much the prediction deviated from actual value (the prediction error). In the graph, the prediction was mostly overestimating the actual outcome $(y>x)$.
what does an actual vs fitted graph tell us? For perfect prediction, you would have Predicted=Actual, or $x=y$, so when you draw that line through this graph you see how much the prediction deviated from actual value (the prediction error). In t
17,381
what does an actual vs fitted graph tell us?
In the linear regression, you want the predicted values to be close to the actual values. So to have a good fit, that plot should resemble a straight line at 45 degrees. However, here the predicted values are larger than the actual values over the range of 10-20. This means that you are over-estimating. Therefore, the model does not seem to provide an adequate fit and should be revised.
what does an actual vs fitted graph tell us?
In the linear regression, you want the predicted values to be close to the actual values. So to have a good fit, that plot should resemble a straight line at 45 degrees. However, here the predicted va
what does an actual vs fitted graph tell us? In the linear regression, you want the predicted values to be close to the actual values. So to have a good fit, that plot should resemble a straight line at 45 degrees. However, here the predicted values are larger than the actual values over the range of 10-20. This means that you are over-estimating. Therefore, the model does not seem to provide an adequate fit and should be revised.
what does an actual vs fitted graph tell us? In the linear regression, you want the predicted values to be close to the actual values. So to have a good fit, that plot should resemble a straight line at 45 degrees. However, here the predicted va
17,382
What is the time complexity of Lasso regression?
Recall that lasso is a linear model with a $l_1$ regularization. Finding the parameters can be formulated as a unconstrained optimization problem, where the parameters are given by $\arg \min_\beta ||y - X\beta||^2 + \alpha||\beta||_1$. In the constrained formuation the parameters are given by $\arg \min_\beta ||y - X\beta||^2 s.t.||\beta||_1 < \alpha$ Which is a quadratic programming problem and thus polynomial. Almost all convex optimization routines, even for flexible nonlinear things like neural networks, rely on computing the derivative of your target w.r.t. parameters. You cannot take the derivative of $\alpha||w||_1$ though. As such you rely on different techniques. There are many methods for finding the parameters. Here's a review paper on the subject, Least Squares Optimization with L1-Norm Regularization. Time-complexity of iterative convex optimization is kind of tricky to analyze, as it depends on a convergence criterion. Generally, iterative problems converge in fewer epochs as the observations increase.
What is the time complexity of Lasso regression?
Recall that lasso is a linear model with a $l_1$ regularization. Finding the parameters can be formulated as a unconstrained optimization problem, where the parameters are given by $\arg \min_\beta |
What is the time complexity of Lasso regression? Recall that lasso is a linear model with a $l_1$ regularization. Finding the parameters can be formulated as a unconstrained optimization problem, where the parameters are given by $\arg \min_\beta ||y - X\beta||^2 + \alpha||\beta||_1$. In the constrained formuation the parameters are given by $\arg \min_\beta ||y - X\beta||^2 s.t.||\beta||_1 < \alpha$ Which is a quadratic programming problem and thus polynomial. Almost all convex optimization routines, even for flexible nonlinear things like neural networks, rely on computing the derivative of your target w.r.t. parameters. You cannot take the derivative of $\alpha||w||_1$ though. As such you rely on different techniques. There are many methods for finding the parameters. Here's a review paper on the subject, Least Squares Optimization with L1-Norm Regularization. Time-complexity of iterative convex optimization is kind of tricky to analyze, as it depends on a convergence criterion. Generally, iterative problems converge in fewer epochs as the observations increase.
What is the time complexity of Lasso regression? Recall that lasso is a linear model with a $l_1$ regularization. Finding the parameters can be formulated as a unconstrained optimization problem, where the parameters are given by $\arg \min_\beta |
17,383
What is the time complexity of Lasso regression?
While @JacobMick provides a broader overview and a link to a review paper, let me give a "shortcut answer" (which may be considered a special case of his answer). Let the number of candidate variables (features, columns) be $K$ and the sample size (number of observations, rows) be $n$. Consider LASSO implemented using LARS algorithm (Efron et al., 2004). The computational complexity of LASSO is $\mathcal{O}(K^3 + K^2 n)$ (ibid.) For $K<n$, $K^3 < K^2 n$ and the computational complexity of LASSO is $\mathcal{O}(K^2 n)$, which is the same as that of a regression with $K$ variables (Efron et al., 2004, p. 443-444; also cited in Schmidt, 2005, section 2.4; for computational complexity of a regression, see this post). For $K \geqslant n$, $K^3 \geqslant K^2 n$ and the computational complexity of LASSO is $\mathcal{O}(K^3)$ (Efron et al., 2004). References: Efron, Bradley, et al. "Least angle regression." The Annals of Statistics 32.2 (2004): 407-499. Schmidt, Mark. "Least squares optimization with l1-norm regularization." CS542B Project Report (2005).
What is the time complexity of Lasso regression?
While @JacobMick provides a broader overview and a link to a review paper, let me give a "shortcut answer" (which may be considered a special case of his answer). Let the number of candidate variable
What is the time complexity of Lasso regression? While @JacobMick provides a broader overview and a link to a review paper, let me give a "shortcut answer" (which may be considered a special case of his answer). Let the number of candidate variables (features, columns) be $K$ and the sample size (number of observations, rows) be $n$. Consider LASSO implemented using LARS algorithm (Efron et al., 2004). The computational complexity of LASSO is $\mathcal{O}(K^3 + K^2 n)$ (ibid.) For $K<n$, $K^3 < K^2 n$ and the computational complexity of LASSO is $\mathcal{O}(K^2 n)$, which is the same as that of a regression with $K$ variables (Efron et al., 2004, p. 443-444; also cited in Schmidt, 2005, section 2.4; for computational complexity of a regression, see this post). For $K \geqslant n$, $K^3 \geqslant K^2 n$ and the computational complexity of LASSO is $\mathcal{O}(K^3)$ (Efron et al., 2004). References: Efron, Bradley, et al. "Least angle regression." The Annals of Statistics 32.2 (2004): 407-499. Schmidt, Mark. "Least squares optimization with l1-norm regularization." CS542B Project Report (2005).
What is the time complexity of Lasso regression? While @JacobMick provides a broader overview and a link to a review paper, let me give a "shortcut answer" (which may be considered a special case of his answer). Let the number of candidate variable
17,384
One-class SVM vs. exemplar SVM
(You may want to look at the "table" below first) Let's start with the "classic" support vector machines. These learn to discriminate between two categories. You collect some examples of category A, some of category B and pass them both to the SVM training algorithm, which finds the line/plane/hyperplane that best separates A from B. This works--and it often works quite well--when you want to distinguish between well-defined and mutually exclusive classes: men vs. women, the letters of the alphabet, and so on. However, suppose you want to identify "A"s instead. You could treat this as a classification problem: How do I distinguish "A"s from "not-A"s. It is fairly easy to gather up a training set consisting of pictures of dogs, but what should go into your training set of not-dogs? Since there are an infinite number of things that are not dogs, you might have a difficult time constructing a comprehensive and yet representative training set of all non-canine things. Instead, you might consider using a one-class classifier. The traditional, two-class classifier finds a (hyper)plane that separates A from B. The one-class SVM instead finds the line/plane/hyperplane that separates all of the in-class points (the "A"s) from origin; it is essentially a two-class SVM where the origin is the only member of the second class (finding the maximum margin from the origin is pretty similar to finding the smallest sphere that contains all As, which might make more conceptual sense). The Ensemble SVM "system" is actually a collection of many two-class SVM "subunits". Each subunit is trained using a single positive example for one class and an enormous collection of negative examples for the other. Thus, instead of discriminating dogs vs. not-dog examples (standard two-class SVM), or dogs vs. origin (one-class SVM), each subunit discriminates between specific dog (e.g., "Rex") and many not-dog examples. Individual subunit SVMs are trained for each example of the positive class, so you would have one SVM for Rex, another for Fido, yet another for your neighbour’s dog that barks at 6am, and so on. The outputs of these subunit SVMs are calibrated and combined to determine whether a dog, not just one of the specific exemplars, appears in the test data. I guess you could also think of the individual subnits as somewhat like one-class SVMs, where the coordinate space is shifted so that the single positive example lies at the origin. In summary, the key differences are: Training Data Two class SVM: Positive and negative examples One class SVM: Positive examples only Ensemble SVM "system": Positive and negative examples. Each subunit is trained on a single positive example and many negative examples. Number of Machines Two class SVM: one One class SVM: one Ensemble SVM "system": many (one subunit machine per positive example) Examples per class (per machine) Two class SVM: many/many One class SVM: many/one (fixed at the origin) Ensemble SVM "system": many/many Ensemble SVM "subunit": one/many Post-processing Two class SVM: Not necessary One class SVM: Not necessary Ensemble SVM: Needed to fuse each SVM's output into a class-level prediction. Postscript: You had asked what they mean by "[other approaches] require mapping the exemplars into a common feature space over which a similarity kernel can be computed." I think they mean that a traditional two-class SVM operates under the assumption that all members of class are somehow similar, and so you want to find a kernel that places great danes and dachsunds near each other, but far away from everything else. By contrast, the ensemble SVM system sidesteps this by calling something a dog if it's sufficiently great dane-like OR dachsund-like OR poodle-like, without worrying about the relationship between those exemplars.
One-class SVM vs. exemplar SVM
(You may want to look at the "table" below first) Let's start with the "classic" support vector machines. These learn to discriminate between two categories. You collect some examples of category A, s
One-class SVM vs. exemplar SVM (You may want to look at the "table" below first) Let's start with the "classic" support vector machines. These learn to discriminate between two categories. You collect some examples of category A, some of category B and pass them both to the SVM training algorithm, which finds the line/plane/hyperplane that best separates A from B. This works--and it often works quite well--when you want to distinguish between well-defined and mutually exclusive classes: men vs. women, the letters of the alphabet, and so on. However, suppose you want to identify "A"s instead. You could treat this as a classification problem: How do I distinguish "A"s from "not-A"s. It is fairly easy to gather up a training set consisting of pictures of dogs, but what should go into your training set of not-dogs? Since there are an infinite number of things that are not dogs, you might have a difficult time constructing a comprehensive and yet representative training set of all non-canine things. Instead, you might consider using a one-class classifier. The traditional, two-class classifier finds a (hyper)plane that separates A from B. The one-class SVM instead finds the line/plane/hyperplane that separates all of the in-class points (the "A"s) from origin; it is essentially a two-class SVM where the origin is the only member of the second class (finding the maximum margin from the origin is pretty similar to finding the smallest sphere that contains all As, which might make more conceptual sense). The Ensemble SVM "system" is actually a collection of many two-class SVM "subunits". Each subunit is trained using a single positive example for one class and an enormous collection of negative examples for the other. Thus, instead of discriminating dogs vs. not-dog examples (standard two-class SVM), or dogs vs. origin (one-class SVM), each subunit discriminates between specific dog (e.g., "Rex") and many not-dog examples. Individual subunit SVMs are trained for each example of the positive class, so you would have one SVM for Rex, another for Fido, yet another for your neighbour’s dog that barks at 6am, and so on. The outputs of these subunit SVMs are calibrated and combined to determine whether a dog, not just one of the specific exemplars, appears in the test data. I guess you could also think of the individual subnits as somewhat like one-class SVMs, where the coordinate space is shifted so that the single positive example lies at the origin. In summary, the key differences are: Training Data Two class SVM: Positive and negative examples One class SVM: Positive examples only Ensemble SVM "system": Positive and negative examples. Each subunit is trained on a single positive example and many negative examples. Number of Machines Two class SVM: one One class SVM: one Ensemble SVM "system": many (one subunit machine per positive example) Examples per class (per machine) Two class SVM: many/many One class SVM: many/one (fixed at the origin) Ensemble SVM "system": many/many Ensemble SVM "subunit": one/many Post-processing Two class SVM: Not necessary One class SVM: Not necessary Ensemble SVM: Needed to fuse each SVM's output into a class-level prediction. Postscript: You had asked what they mean by "[other approaches] require mapping the exemplars into a common feature space over which a similarity kernel can be computed." I think they mean that a traditional two-class SVM operates under the assumption that all members of class are somehow similar, and so you want to find a kernel that places great danes and dachsunds near each other, but far away from everything else. By contrast, the ensemble SVM system sidesteps this by calling something a dog if it's sufficiently great dane-like OR dachsund-like OR poodle-like, without worrying about the relationship between those exemplars.
One-class SVM vs. exemplar SVM (You may want to look at the "table" below first) Let's start with the "classic" support vector machines. These learn to discriminate between two categories. You collect some examples of category A, s
17,385
One-class SVM vs. exemplar SVM
In short, ESVM model is an ensemble of SVMs trained to distinguish each single training set element from all the rest, while OSVM is an ensemble of SVMs trained to distinguish each subset of training elements that belong to one class. So, if you have 300 cat and 300 dog examples in the training set, ESVM will make 600 SVMs, each for one pet while OSVM will make two SVMs (first for all cats, second for all dogs). This way, ESVM does not need to find a space in which the whole class clusters but rather a space in which this single element is an outlier, which is likely simpler and leads to a high precision. Recall is said to be provided by the ensemble.
One-class SVM vs. exemplar SVM
In short, ESVM model is an ensemble of SVMs trained to distinguish each single training set element from all the rest, while OSVM is an ensemble of SVMs trained to distinguish each subset of training
One-class SVM vs. exemplar SVM In short, ESVM model is an ensemble of SVMs trained to distinguish each single training set element from all the rest, while OSVM is an ensemble of SVMs trained to distinguish each subset of training elements that belong to one class. So, if you have 300 cat and 300 dog examples in the training set, ESVM will make 600 SVMs, each for one pet while OSVM will make two SVMs (first for all cats, second for all dogs). This way, ESVM does not need to find a space in which the whole class clusters but rather a space in which this single element is an outlier, which is likely simpler and leads to a high precision. Recall is said to be provided by the ensemble.
One-class SVM vs. exemplar SVM In short, ESVM model is an ensemble of SVMs trained to distinguish each single training set element from all the rest, while OSVM is an ensemble of SVMs trained to distinguish each subset of training
17,386
KNN imputation R packages
You could also try the following package: DMwR. It failed on the case of 3 NN, giving 'Error in knnImputation(x, k = 3) : Not sufficient complete cases for computing neighbors.' However, trying 2 gives. > knnImputation(x,k=2) [,1] [,2] [,3] [,4] [,5] [,6] [1,] -0.59091360 -1.2698175 0.5556009 -0.1327224 -0.8325065 0.71664000 [2,] -1.27255074 -0.7853602 0.7261897 0.2969900 0.2969556 -0.44612831 [3,] 0.55473981 0.4748735 0.5158498 -0.9493917 -1.5187722 -0.99377854 [4,] -0.47797654 0.1647818 0.6167311 -0.5149731 0.5240514 -0.46027809 [5,] -1.08767831 -0.3785608 0.6659499 -0.7223724 -0.9512409 -1.60547053 [6,] -0.06153279 0.9486815 -0.5464601 0.1544475 0.2835521 -0.82250221 [7,] -0.82536029 -0.2906253 -3.0284281 -0.8473210 0.7985286 -0.09751927 [8,] -1.15366189 0.5341000 -1.0109258 -1.5900281 0.2742328 0.29039928 [9,] -1.49504465 -0.5419533 0.5766574 -1.2412777 -1.4089572 -0.71069839 [10,] -0.35935440 -0.2622265 0.4048126 -2.0869817 0.2682486 0.16904559 [,7] [,8] [,9] [,10] [1,] 0.58027159 -1.0669137 0.48670802 0.5824858 [2,] -0.48314440 -1.0532693 -0.34030385 -1.1041681 [3,] -2.81996446 0.3191438 -0.48117020 -0.0352633 [4,] -0.55080515 -1.0620243 -0.51383557 0.3161907 [5,] -0.56808769 -0.3696951 0.35549191 0.3202675 [6,] -0.25043479 -1.0389393 0.07810902 0.5251606 [7,] -0.41667318 0.8809541 -0.04613332 -1.1586756 [8,] -0.06898363 -1.0736161 0.62698065 -1.0373835 [9,] 0.30051583 -0.2936140 0.31417921 -1.4155193 [10,] -0.68180034 -1.0789745 0.58290920 -1.0197956 You can test for sufficient observations using complete.cases(x), where that value must be at least k. One way to overcome this problem is to relax your requirements (i.e. less incomplete rows), by 1) increasing the NA threshold, or alternatively, 2) increasing your number of observations. Here is the first: > x = matrix(rnorm(100),10,10) > x.missing = x > 2 > x[x.missing] = NA > complete.cases(x) [1] TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE > knnImputation(x,k=3) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 0.86882569 -0.2409922 0.3859031 0.5818927 -1.50310330 0.8752261 -0.5173105 -2.18244988 -0.28817656 -0.63941237 [2,] 1.54114079 0.7227511 0.7856277 0.8512048 -1.32442954 -2.1668744 0.7017532 -0.40086348 -0.41251883 0.42924986 [3,] 0.60062917 -0.5955623 0.6192783 -0.3836310 0.06871570 1.7804657 0.5965411 -1.62625036 1.27706937 0.72860273 [4,] -0.07328279 -0.1738157 1.4965579 -1.1686115 -0.06954318 -1.0171604 -0.3283916 0.63493884 0.72039689 -0.20889111 [5,] 0.78747874 -0.8607320 0.4828322 0.6558960 -0.22064430 0.2001473 0.7725701 0.06155196 0.09011719 -1.01902968 [6,] 0.17988720 -0.8520000 -0.5911523 1.8100573 -0.56108621 0.0151522 -0.2484345 -0.80695513 -0.18532984 -1.75115335 [7,] 1.03943492 0.4880532 -2.7588922 -0.1336166 -1.28424057 1.2871333 0.7595750 -0.55615677 -1.67765572 -0.05440992 [8,] 1.12394474 1.4890366 -1.6034648 -1.4315445 -0.23052386 -0.3536677 -0.8694188 -0.53689507 -1.11510406 -1.39108817 [9,] -0.30393916 0.6216156 0.1559639 1.2297105 -0.29439390 1.8224512 -0.4457441 -0.32814665 0.55487894 -0.22602598 [10,] 1.18424722 -0.1816049 -2.2975095 -0.7537477 0.86647524 -0.8710603 0.3351710 -0.79632184 -0.56254688 -0.77449398 > x [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 0.86882569 -0.2409922 0.3859031 0.5818927 -1.5031033 0.8752261 -0.5173105 -2.18244988 -0.28817656 -0.63941237 [2,] 1.54114079 0.7227511 0.7856277 0.8512048 -1.3244295 -2.1668744 0.7017532 -0.40086348 -0.41251883 0.42924986 [3,] 0.60062917 -0.5955623 0.6192783 -0.3836310 0.0687157 1.7804657 0.5965411 -1.62625036 1.27706937 0.72860273 [4,] -0.07328279 -0.1738157 1.4965579 -1.1686115 NA -1.0171604 -0.3283916 0.63493884 0.72039689 -0.20889111 [5,] 0.78747874 -0.8607320 0.4828322 NA -0.2206443 0.2001473 0.7725701 0.06155196 0.09011719 -1.01902968 [6,] 0.17988720 -0.8520000 -0.5911523 1.8100573 -0.5610862 0.0151522 -0.2484345 -0.80695513 -0.18532984 -1.75115335 [7,] 1.03943492 0.4880532 -2.7588922 -0.1336166 -1.2842406 1.2871333 0.7595750 -0.55615677 -1.67765572 -0.05440992 [8,] 1.12394474 1.4890366 -1.6034648 -1.4315445 -0.2305239 -0.3536677 -0.8694188 -0.53689507 -1.11510406 -1.39108817 [9,] -0.30393916 0.6216156 0.1559639 1.2297105 -0.2943939 1.8224512 -0.4457441 -0.32814665 0.55487894 -0.22602598 [10,] 1.18424722 -0.1816049 -2.2975095 -0.7537477 0.8664752 -0.8710603 0.3351710 -0.79632184 -0.56254688 -0.77449398 here is an example of the 2nd... x = matrix(rnorm(1000),100,10) x.missing = x > 1 x[x.missing] = NA complete.cases(x) [1] TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE [22] FALSE FALSE TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [43] TRUE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [64] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE [85] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE FALSE At least k=3 complete rows are satisfied, thus it is able to impute for k=3. > head(knnImputation(x,k=3)) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 0.01817557 -2.8141502 0.3929944 0.1495092 -1.7218396 0.4159133 -0.8438809 0.6599224 -0.02451113 -1.14541016 [2,] 0.51969964 -0.4976021 -0.1495392 -0.6448184 -0.6066386 -1.6210476 -0.3118440 0.2477855 -0.30986749 0.32424673 ...
KNN imputation R packages
You could also try the following package: DMwR. It failed on the case of 3 NN, giving 'Error in knnImputation(x, k = 3) : Not sufficient complete cases for computing neighbors.' However, trying 2 g
KNN imputation R packages You could also try the following package: DMwR. It failed on the case of 3 NN, giving 'Error in knnImputation(x, k = 3) : Not sufficient complete cases for computing neighbors.' However, trying 2 gives. > knnImputation(x,k=2) [,1] [,2] [,3] [,4] [,5] [,6] [1,] -0.59091360 -1.2698175 0.5556009 -0.1327224 -0.8325065 0.71664000 [2,] -1.27255074 -0.7853602 0.7261897 0.2969900 0.2969556 -0.44612831 [3,] 0.55473981 0.4748735 0.5158498 -0.9493917 -1.5187722 -0.99377854 [4,] -0.47797654 0.1647818 0.6167311 -0.5149731 0.5240514 -0.46027809 [5,] -1.08767831 -0.3785608 0.6659499 -0.7223724 -0.9512409 -1.60547053 [6,] -0.06153279 0.9486815 -0.5464601 0.1544475 0.2835521 -0.82250221 [7,] -0.82536029 -0.2906253 -3.0284281 -0.8473210 0.7985286 -0.09751927 [8,] -1.15366189 0.5341000 -1.0109258 -1.5900281 0.2742328 0.29039928 [9,] -1.49504465 -0.5419533 0.5766574 -1.2412777 -1.4089572 -0.71069839 [10,] -0.35935440 -0.2622265 0.4048126 -2.0869817 0.2682486 0.16904559 [,7] [,8] [,9] [,10] [1,] 0.58027159 -1.0669137 0.48670802 0.5824858 [2,] -0.48314440 -1.0532693 -0.34030385 -1.1041681 [3,] -2.81996446 0.3191438 -0.48117020 -0.0352633 [4,] -0.55080515 -1.0620243 -0.51383557 0.3161907 [5,] -0.56808769 -0.3696951 0.35549191 0.3202675 [6,] -0.25043479 -1.0389393 0.07810902 0.5251606 [7,] -0.41667318 0.8809541 -0.04613332 -1.1586756 [8,] -0.06898363 -1.0736161 0.62698065 -1.0373835 [9,] 0.30051583 -0.2936140 0.31417921 -1.4155193 [10,] -0.68180034 -1.0789745 0.58290920 -1.0197956 You can test for sufficient observations using complete.cases(x), where that value must be at least k. One way to overcome this problem is to relax your requirements (i.e. less incomplete rows), by 1) increasing the NA threshold, or alternatively, 2) increasing your number of observations. Here is the first: > x = matrix(rnorm(100),10,10) > x.missing = x > 2 > x[x.missing] = NA > complete.cases(x) [1] TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE > knnImputation(x,k=3) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 0.86882569 -0.2409922 0.3859031 0.5818927 -1.50310330 0.8752261 -0.5173105 -2.18244988 -0.28817656 -0.63941237 [2,] 1.54114079 0.7227511 0.7856277 0.8512048 -1.32442954 -2.1668744 0.7017532 -0.40086348 -0.41251883 0.42924986 [3,] 0.60062917 -0.5955623 0.6192783 -0.3836310 0.06871570 1.7804657 0.5965411 -1.62625036 1.27706937 0.72860273 [4,] -0.07328279 -0.1738157 1.4965579 -1.1686115 -0.06954318 -1.0171604 -0.3283916 0.63493884 0.72039689 -0.20889111 [5,] 0.78747874 -0.8607320 0.4828322 0.6558960 -0.22064430 0.2001473 0.7725701 0.06155196 0.09011719 -1.01902968 [6,] 0.17988720 -0.8520000 -0.5911523 1.8100573 -0.56108621 0.0151522 -0.2484345 -0.80695513 -0.18532984 -1.75115335 [7,] 1.03943492 0.4880532 -2.7588922 -0.1336166 -1.28424057 1.2871333 0.7595750 -0.55615677 -1.67765572 -0.05440992 [8,] 1.12394474 1.4890366 -1.6034648 -1.4315445 -0.23052386 -0.3536677 -0.8694188 -0.53689507 -1.11510406 -1.39108817 [9,] -0.30393916 0.6216156 0.1559639 1.2297105 -0.29439390 1.8224512 -0.4457441 -0.32814665 0.55487894 -0.22602598 [10,] 1.18424722 -0.1816049 -2.2975095 -0.7537477 0.86647524 -0.8710603 0.3351710 -0.79632184 -0.56254688 -0.77449398 > x [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 0.86882569 -0.2409922 0.3859031 0.5818927 -1.5031033 0.8752261 -0.5173105 -2.18244988 -0.28817656 -0.63941237 [2,] 1.54114079 0.7227511 0.7856277 0.8512048 -1.3244295 -2.1668744 0.7017532 -0.40086348 -0.41251883 0.42924986 [3,] 0.60062917 -0.5955623 0.6192783 -0.3836310 0.0687157 1.7804657 0.5965411 -1.62625036 1.27706937 0.72860273 [4,] -0.07328279 -0.1738157 1.4965579 -1.1686115 NA -1.0171604 -0.3283916 0.63493884 0.72039689 -0.20889111 [5,] 0.78747874 -0.8607320 0.4828322 NA -0.2206443 0.2001473 0.7725701 0.06155196 0.09011719 -1.01902968 [6,] 0.17988720 -0.8520000 -0.5911523 1.8100573 -0.5610862 0.0151522 -0.2484345 -0.80695513 -0.18532984 -1.75115335 [7,] 1.03943492 0.4880532 -2.7588922 -0.1336166 -1.2842406 1.2871333 0.7595750 -0.55615677 -1.67765572 -0.05440992 [8,] 1.12394474 1.4890366 -1.6034648 -1.4315445 -0.2305239 -0.3536677 -0.8694188 -0.53689507 -1.11510406 -1.39108817 [9,] -0.30393916 0.6216156 0.1559639 1.2297105 -0.2943939 1.8224512 -0.4457441 -0.32814665 0.55487894 -0.22602598 [10,] 1.18424722 -0.1816049 -2.2975095 -0.7537477 0.8664752 -0.8710603 0.3351710 -0.79632184 -0.56254688 -0.77449398 here is an example of the 2nd... x = matrix(rnorm(1000),100,10) x.missing = x > 1 x[x.missing] = NA complete.cases(x) [1] TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE [22] FALSE FALSE TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [43] TRUE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [64] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE [85] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE FALSE At least k=3 complete rows are satisfied, thus it is able to impute for k=3. > head(knnImputation(x,k=3)) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 0.01817557 -2.8141502 0.3929944 0.1495092 -1.7218396 0.4159133 -0.8438809 0.6599224 -0.02451113 -1.14541016 [2,] 0.51969964 -0.4976021 -0.1495392 -0.6448184 -0.6066386 -1.6210476 -0.3118440 0.2477855 -0.30986749 0.32424673 ...
KNN imputation R packages You could also try the following package: DMwR. It failed on the case of 3 NN, giving 'Error in knnImputation(x, k = 3) : Not sufficient complete cases for computing neighbors.' However, trying 2 g
17,387
KNN imputation R packages
The imputation package isn't on CRAN any more. One package other than DMwR that offers a kNN imputation function is VIM. Also easy to use: library("VIM") kNN(x, k=3)
KNN imputation R packages
The imputation package isn't on CRAN any more. One package other than DMwR that offers a kNN imputation function is VIM. Also easy to use: library("VIM") kNN(x, k=3)
KNN imputation R packages The imputation package isn't on CRAN any more. One package other than DMwR that offers a kNN imputation function is VIM. Also easy to use: library("VIM") kNN(x, k=3)
KNN imputation R packages The imputation package isn't on CRAN any more. One package other than DMwR that offers a kNN imputation function is VIM. Also easy to use: library("VIM") kNN(x, k=3)
17,388
KNN imputation R packages
require(imputation) x = matrix(rnorm(100),10,10) x.missing = x > 1 x[x.missing] = NA y <- kNNImpute(x, 3) attributes(y) $names [1] "x" "missing.matrix" y$x > x (original matrix) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 0.38515909 0.52661156 0.6164138 0.3095225 0.55909716 -1.16543168 -0.70714440 [2,] -0.39222402 -1.29703536 0.4429824 -1.3950116 NA -0.46841443 -0.57563472 [3,] -2.04467869 -0.52022405 NA 0.7219057 -0.93573417 -1.51490638 0.62356689 [4,] -1.08684345 0.63083074 NA 0.5603603 0.48583414 NA -0.69447183 [5,] 0.30116921 0.25127476 -0.2132160 NA -1.63484823 -0.58266488 0.34432576 [6,] 0.82152305 -0.12900915 -1.8498997 0.8012059 NA -0.14987133 -1.11232289 [7,] 0.27912763 -0.68923032 -0.2355762 -0.2541675 -0.14181344 -0.08519797 0.13061823 [8,] 0.06653984 -0.87521539 -0.0980306 -0.4350224 0.05021324 -1.66963624 -0.09204772 [9,] 0.12687240 -0.62717646 -0.1258722 NA -0.86913445 0.68365036 NA [10,] 0.56680502 0.03318012 0.1411861 0.6573134 -0.14747073 NA -1.37949278 [,8] [,9] [,10] [1,] -2.67066748 NA -0.64370528 [2,] -1.26864936 -1.95692064 0.28917897 [3,] -0.27816124 -0.20332695 -1.29456054 [4,] -1.10917662 -0.59598910 -0.32475962 [5,] -0.15448822 0.71667444 -1.60827152 [6,] -0.66691445 0.05396037 0.04074923 [7,] 0.05644956 0.99416556 -0.77808427 [8,] -0.32294266 NA -2.50933697 [9,] -0.67226044 NA NA [10,] -0.84866945 -0.54318570 NA > y$x (imputed matrix) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 0.38515909 0.52661156 0.61641378 0.30952251 0.55909716 -1.16543168 -0.70714440 [2,] -0.39222402 -1.29703536 0.44298237 -1.39501160 -0.22157531 -0.46841443 -0.57563472 [3,] -2.04467869 -0.52022405 0.08298882 0.72190573 -0.93573417 -1.51490638 0.62356689 [4,] -1.08684345 0.63083074 -0.66707695 0.56036034 0.48583414 -0.98956026 -0.69447183 [5,] 0.30116921 0.25127476 -0.21321600 -0.02480909 -1.63484823 -0.58266488 0.34432576 [6,] 0.82152305 -0.12900915 -1.84989965 0.80120592 -0.76323053 -0.14987133 -1.11232289 [7,] 0.27912763 -0.68923032 -0.23557619 -0.25416751 -0.14181344 -0.08519797 0.13061823 [8,] 0.06653984 -0.87521539 -0.09803060 -0.43502238 0.05021324 -1.66963624 -0.09204772 [9,] 0.12687240 -0.62717646 -0.12587221 0.00000000 -0.86913445 0.68365036 0.00000000 [10,] 0.56680502 0.03318012 0.14118610 0.65731337 -0.14747073 0.00000000 -1.37949278 [,8] [,9] [,10] [1,] -2.67066748 0.04286260 -0.64370528 [2,] -1.26864936 -1.95692064 0.28917897 [3,] -0.27816124 -0.20332695 -1.29456054 [4,] -1.10917662 -0.59598910 -0.32475962 [5,] -0.15448822 0.71667444 -1.60827152 [6,] -0.66691445 0.05396037 0.04074923 [7,] 0.05644956 0.99416556 -0.77808427 [8,] -0.32294266 0.00000000 -2.50933697 [9,] -0.67226044 0.00000000 0.00000000 [10,] -0.84866945 -0.54318570 0.00000000 It's imputed the values that it can. Those that can't be imputed are set to zero.
KNN imputation R packages
require(imputation) x = matrix(rnorm(100),10,10) x.missing = x > 1 x[x.missing] = NA y <- kNNImpute(x, 3) attributes(y) $names [1] "x" "missing.matrix" y$x > x (original matrix)
KNN imputation R packages require(imputation) x = matrix(rnorm(100),10,10) x.missing = x > 1 x[x.missing] = NA y <- kNNImpute(x, 3) attributes(y) $names [1] "x" "missing.matrix" y$x > x (original matrix) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 0.38515909 0.52661156 0.6164138 0.3095225 0.55909716 -1.16543168 -0.70714440 [2,] -0.39222402 -1.29703536 0.4429824 -1.3950116 NA -0.46841443 -0.57563472 [3,] -2.04467869 -0.52022405 NA 0.7219057 -0.93573417 -1.51490638 0.62356689 [4,] -1.08684345 0.63083074 NA 0.5603603 0.48583414 NA -0.69447183 [5,] 0.30116921 0.25127476 -0.2132160 NA -1.63484823 -0.58266488 0.34432576 [6,] 0.82152305 -0.12900915 -1.8498997 0.8012059 NA -0.14987133 -1.11232289 [7,] 0.27912763 -0.68923032 -0.2355762 -0.2541675 -0.14181344 -0.08519797 0.13061823 [8,] 0.06653984 -0.87521539 -0.0980306 -0.4350224 0.05021324 -1.66963624 -0.09204772 [9,] 0.12687240 -0.62717646 -0.1258722 NA -0.86913445 0.68365036 NA [10,] 0.56680502 0.03318012 0.1411861 0.6573134 -0.14747073 NA -1.37949278 [,8] [,9] [,10] [1,] -2.67066748 NA -0.64370528 [2,] -1.26864936 -1.95692064 0.28917897 [3,] -0.27816124 -0.20332695 -1.29456054 [4,] -1.10917662 -0.59598910 -0.32475962 [5,] -0.15448822 0.71667444 -1.60827152 [6,] -0.66691445 0.05396037 0.04074923 [7,] 0.05644956 0.99416556 -0.77808427 [8,] -0.32294266 NA -2.50933697 [9,] -0.67226044 NA NA [10,] -0.84866945 -0.54318570 NA > y$x (imputed matrix) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 0.38515909 0.52661156 0.61641378 0.30952251 0.55909716 -1.16543168 -0.70714440 [2,] -0.39222402 -1.29703536 0.44298237 -1.39501160 -0.22157531 -0.46841443 -0.57563472 [3,] -2.04467869 -0.52022405 0.08298882 0.72190573 -0.93573417 -1.51490638 0.62356689 [4,] -1.08684345 0.63083074 -0.66707695 0.56036034 0.48583414 -0.98956026 -0.69447183 [5,] 0.30116921 0.25127476 -0.21321600 -0.02480909 -1.63484823 -0.58266488 0.34432576 [6,] 0.82152305 -0.12900915 -1.84989965 0.80120592 -0.76323053 -0.14987133 -1.11232289 [7,] 0.27912763 -0.68923032 -0.23557619 -0.25416751 -0.14181344 -0.08519797 0.13061823 [8,] 0.06653984 -0.87521539 -0.09803060 -0.43502238 0.05021324 -1.66963624 -0.09204772 [9,] 0.12687240 -0.62717646 -0.12587221 0.00000000 -0.86913445 0.68365036 0.00000000 [10,] 0.56680502 0.03318012 0.14118610 0.65731337 -0.14747073 0.00000000 -1.37949278 [,8] [,9] [,10] [1,] -2.67066748 0.04286260 -0.64370528 [2,] -1.26864936 -1.95692064 0.28917897 [3,] -0.27816124 -0.20332695 -1.29456054 [4,] -1.10917662 -0.59598910 -0.32475962 [5,] -0.15448822 0.71667444 -1.60827152 [6,] -0.66691445 0.05396037 0.04074923 [7,] 0.05644956 0.99416556 -0.77808427 [8,] -0.32294266 0.00000000 -2.50933697 [9,] -0.67226044 0.00000000 0.00000000 [10,] -0.84866945 -0.54318570 0.00000000 It's imputed the values that it can. Those that can't be imputed are set to zero.
KNN imputation R packages require(imputation) x = matrix(rnorm(100),10,10) x.missing = x > 1 x[x.missing] = NA y <- kNNImpute(x, 3) attributes(y) $names [1] "x" "missing.matrix" y$x > x (original matrix)
17,389
KNN imputation R packages
install.packages("DMwR")* # for use of knnImputation. require(DMwR) x = matrix(rnorm(100), 10, 10) x.missing= x >1 x[x.missing] = NA complete.cases(x) y <- knnImputation(x, 3)
KNN imputation R packages
install.packages("DMwR")* # for use of knnImputation. require(DMwR) x = matrix(rnorm(100), 10, 10) x.missing= x >1 x[x.missing] = NA complete.cases(x) y <- knnImputation(x, 3)
KNN imputation R packages install.packages("DMwR")* # for use of knnImputation. require(DMwR) x = matrix(rnorm(100), 10, 10) x.missing= x >1 x[x.missing] = NA complete.cases(x) y <- knnImputation(x, 3)
KNN imputation R packages install.packages("DMwR")* # for use of knnImputation. require(DMwR) x = matrix(rnorm(100), 10, 10) x.missing= x >1 x[x.missing] = NA complete.cases(x) y <- knnImputation(x, 3)
17,390
KNN imputation R packages
The reason for R not being able to impute is because in many instances, more than one attribute in a row is missing and hence it cannot compute the nearest neighbor. What you can do alternatively is either impute interval variables with projected probabilities from a normal distribution ( or if its skewed use a Gamma distribution which have similar skew). and use a decision tree to predict missing values in case of a class variable.
KNN imputation R packages
The reason for R not being able to impute is because in many instances, more than one attribute in a row is missing and hence it cannot compute the nearest neighbor. What you can do alternatively is e
KNN imputation R packages The reason for R not being able to impute is because in many instances, more than one attribute in a row is missing and hence it cannot compute the nearest neighbor. What you can do alternatively is either impute interval variables with projected probabilities from a normal distribution ( or if its skewed use a Gamma distribution which have similar skew). and use a decision tree to predict missing values in case of a class variable.
KNN imputation R packages The reason for R not being able to impute is because in many instances, more than one attribute in a row is missing and hence it cannot compute the nearest neighbor. What you can do alternatively is e
17,391
Where do the assumptions for linear regression come from? [duplicate]
Why cannot I just simply use least square method without these assumptions ? You can. However, inference - such as calculation of standard errors, confidence intervals and p-values - rely on those assumptions. You can compute a least squares line without them holding... it just won't necessarily be the best thing to do. You can break each of those assumptions and derive something else than least squares which might make more sense. e.g. dependence might lead you to ARIMA models or mixed effects models (for example) non-normal errors might lead you to GLMs (or a number of other things) heteroscedasticity might lead you to GLMs, or weighted regression, or heterocsedasticity-consistent inference As for where they come from - The independence assumption is basically something that holds approximately in many cases, and assuming exact independence makes life (much) easier. normality is a good approximation to errors in some cases (if you have many sources of small, independent errors, where none dominate, for example, the overall error will tend to be approximately normal), and again makes life easier (least squares is maximum likelihood there). The Gauss-Markov theorem is relevant, and - at least for cases where not all linear estimators are bad - encourages us that we might consider it when those assumptions don't all hold. constant variance is another simplifying assumption that is sometimes true. When you take all three together, the kinds of inference mentioned above becomes very tractable. And sometimes, those assumptions are reasonable. If sample sizes are large and no points are unduly influential, normality is probably the least critical; inference-wise you can get by with a little non-normality quite happily, as long as you're not trying to construct prediction intervals. Historically speaking you might find this: http://en.wikipedia.org/wiki/Least_squares#History and perhaps this interesting (if you can access it). --- Edit: whether slope, p-value, or R2 is still valid if some assumption is invalid I'll have to make some assumptions about what you mean by 'valid' The wikipedia article on OLS mentions some details on consistency and optimality in the second paragraph. Later in the same article it discusses various assumptions and their violation. This paper discusses the consistency of least squares slope estimates under various conditions, but if you don't know things like the difference between the different types of convergence it might not help much. For the effect of contravening the assumption of equal variances, see here. The distribution of p-values relies on all the assumptions, but as the sample sizes get very large then (under some conditions I'm not going to essay here), the CLT gives you normality of the parameter estimates when the errors aren't normal; as a result, mild non-normality in particular won't necessarily be an issue if teh samples are reasonably large. The p-values do rely on the equal variance assumption (see the above link on heteroskedasticity), and on the independence assumption. On $R^2$ - if you think of $R^2$ as estimating a population quantity, then being based on variance it's critically impacted by violation of the equal variance and independence assumptions. On the other hand $R^2$ isn't generally a particularly important quantity. --- Major Edit 2: Sorry for unclear question. I want to know some conclusion like "if the independent error assumption is false, the p-value is less then its true value." Or whether these kind of conclusion exists The problem with breaking independence is there are infinitely many ways that errors can be dependent and the direction of effects on things like p-values can be complex. There's no single simple rule unless the domain is restricted somewhat. If you specify particular forms and directions of dependence, some conclusions are possible. For example, when the errors are positively autocorrelated, the regression slope standard errors tend to be reduced, making t-ratios biased away from 0, and hence p-values lower (more significant). Similarly, the direction of effect of heteroskedasticity depends on specific details of the nature of the departure. If you have particular kinds of deviation from assumptions in mind you can investigate the impact on variances/standard errors and hence on things like p-values and $R^2$ very easily via the use of simulation (though in many cases you can also get a fair way with algebra). (Just as a general piece of advice, you may notice that many of your questions have been directly answered in the relevant stats articles on wikipedia. It would be worth your time to read through these articles and some of the articles they link to.)
Where do the assumptions for linear regression come from? [duplicate]
Why cannot I just simply use least square method without these assumptions ? You can. However, inference - such as calculation of standard errors, confidence intervals and p-values - rely on those as
Where do the assumptions for linear regression come from? [duplicate] Why cannot I just simply use least square method without these assumptions ? You can. However, inference - such as calculation of standard errors, confidence intervals and p-values - rely on those assumptions. You can compute a least squares line without them holding... it just won't necessarily be the best thing to do. You can break each of those assumptions and derive something else than least squares which might make more sense. e.g. dependence might lead you to ARIMA models or mixed effects models (for example) non-normal errors might lead you to GLMs (or a number of other things) heteroscedasticity might lead you to GLMs, or weighted regression, or heterocsedasticity-consistent inference As for where they come from - The independence assumption is basically something that holds approximately in many cases, and assuming exact independence makes life (much) easier. normality is a good approximation to errors in some cases (if you have many sources of small, independent errors, where none dominate, for example, the overall error will tend to be approximately normal), and again makes life easier (least squares is maximum likelihood there). The Gauss-Markov theorem is relevant, and - at least for cases where not all linear estimators are bad - encourages us that we might consider it when those assumptions don't all hold. constant variance is another simplifying assumption that is sometimes true. When you take all three together, the kinds of inference mentioned above becomes very tractable. And sometimes, those assumptions are reasonable. If sample sizes are large and no points are unduly influential, normality is probably the least critical; inference-wise you can get by with a little non-normality quite happily, as long as you're not trying to construct prediction intervals. Historically speaking you might find this: http://en.wikipedia.org/wiki/Least_squares#History and perhaps this interesting (if you can access it). --- Edit: whether slope, p-value, or R2 is still valid if some assumption is invalid I'll have to make some assumptions about what you mean by 'valid' The wikipedia article on OLS mentions some details on consistency and optimality in the second paragraph. Later in the same article it discusses various assumptions and their violation. This paper discusses the consistency of least squares slope estimates under various conditions, but if you don't know things like the difference between the different types of convergence it might not help much. For the effect of contravening the assumption of equal variances, see here. The distribution of p-values relies on all the assumptions, but as the sample sizes get very large then (under some conditions I'm not going to essay here), the CLT gives you normality of the parameter estimates when the errors aren't normal; as a result, mild non-normality in particular won't necessarily be an issue if teh samples are reasonably large. The p-values do rely on the equal variance assumption (see the above link on heteroskedasticity), and on the independence assumption. On $R^2$ - if you think of $R^2$ as estimating a population quantity, then being based on variance it's critically impacted by violation of the equal variance and independence assumptions. On the other hand $R^2$ isn't generally a particularly important quantity. --- Major Edit 2: Sorry for unclear question. I want to know some conclusion like "if the independent error assumption is false, the p-value is less then its true value." Or whether these kind of conclusion exists The problem with breaking independence is there are infinitely many ways that errors can be dependent and the direction of effects on things like p-values can be complex. There's no single simple rule unless the domain is restricted somewhat. If you specify particular forms and directions of dependence, some conclusions are possible. For example, when the errors are positively autocorrelated, the regression slope standard errors tend to be reduced, making t-ratios biased away from 0, and hence p-values lower (more significant). Similarly, the direction of effect of heteroskedasticity depends on specific details of the nature of the departure. If you have particular kinds of deviation from assumptions in mind you can investigate the impact on variances/standard errors and hence on things like p-values and $R^2$ very easily via the use of simulation (though in many cases you can also get a fair way with algebra). (Just as a general piece of advice, you may notice that many of your questions have been directly answered in the relevant stats articles on wikipedia. It would be worth your time to read through these articles and some of the articles they link to.)
Where do the assumptions for linear regression come from? [duplicate] Why cannot I just simply use least square method without these assumptions ? You can. However, inference - such as calculation of standard errors, confidence intervals and p-values - rely on those as
17,392
How does ggplot compute confidence intervals for regressions?
From the Details section of the help Calculation is performed by the (currently undocumented) predictdf generic function and its methods. For most methods the confidence bounds are computed using the predict method - the exceptions are loess which uses a t-based approximation, and for glm where the normal confidence interval is constructed on the link scale, and then back-transformed to the response scale. So predictdf will generally call stats::predict, which in turn will call the correct predict method for the smoothing method. Other functions involving stat_smooth are also useful to consider. Most model fitting functions will have predict method associated with the class of the model. These will usually take a newdata object and an argument se.fit that will denote whether the standard errors will be fitted. (see ?predict) for further details. se display confidence interval around smooth? (TRUE by default, see level to control This is passed directy to the predict method to return the appropriate standard errors (method dependant) fullrange should the fit span the full range of the plot, or just the data This defines the newdata values for x at which the predictions will be evaluated level level of confidence interval to use (0.95 by default) Passed directly to the predict method so that the confidence interval can define the appropriate critical value (eg predict.lm uses qt((1 - level)/2, df) for the standard errors to be multiplied by n number of points to evaluate smoother at Used in conjunction with fullrange to define the x values in the newdata object. Within a call to stat_smooth you can define se which is what is partially matched to se.fit (or se), and will define the interval argument if necessary. level will give level of the confidence interval (defaults 0.95). The newdata object is defined within the processing, depending on your setting of fullrange to a sequence of length n within the full range of the plot or the data. In your case, using rlm, this will use predict.rlm, which is defined as predict.rlm <- function (object, newdata = NULL, scale = NULL, ...) { ## problems with using predict.lm are the scale and ## the QR decomp which has been done on down-weighted values. object$qr <- qr(sqrt(object$weights) * object$x) predict.lm(object, newdata = newdata, scale = object$s, ...) } So it is internally calling predict.lm with an appropriate scaling of the qr decomposition and scale argument.
How does ggplot compute confidence intervals for regressions?
From the Details section of the help Calculation is performed by the (currently undocumented) predictdf generic function and its methods. For most methods the confidence bounds are computed using
How does ggplot compute confidence intervals for regressions? From the Details section of the help Calculation is performed by the (currently undocumented) predictdf generic function and its methods. For most methods the confidence bounds are computed using the predict method - the exceptions are loess which uses a t-based approximation, and for glm where the normal confidence interval is constructed on the link scale, and then back-transformed to the response scale. So predictdf will generally call stats::predict, which in turn will call the correct predict method for the smoothing method. Other functions involving stat_smooth are also useful to consider. Most model fitting functions will have predict method associated with the class of the model. These will usually take a newdata object and an argument se.fit that will denote whether the standard errors will be fitted. (see ?predict) for further details. se display confidence interval around smooth? (TRUE by default, see level to control This is passed directy to the predict method to return the appropriate standard errors (method dependant) fullrange should the fit span the full range of the plot, or just the data This defines the newdata values for x at which the predictions will be evaluated level level of confidence interval to use (0.95 by default) Passed directly to the predict method so that the confidence interval can define the appropriate critical value (eg predict.lm uses qt((1 - level)/2, df) for the standard errors to be multiplied by n number of points to evaluate smoother at Used in conjunction with fullrange to define the x values in the newdata object. Within a call to stat_smooth you can define se which is what is partially matched to se.fit (or se), and will define the interval argument if necessary. level will give level of the confidence interval (defaults 0.95). The newdata object is defined within the processing, depending on your setting of fullrange to a sequence of length n within the full range of the plot or the data. In your case, using rlm, this will use predict.rlm, which is defined as predict.rlm <- function (object, newdata = NULL, scale = NULL, ...) { ## problems with using predict.lm are the scale and ## the QR decomp which has been done on down-weighted values. object$qr <- qr(sqrt(object$weights) * object$x) predict.lm(object, newdata = newdata, scale = object$s, ...) } So it is internally calling predict.lm with an appropriate scaling of the qr decomposition and scale argument.
How does ggplot compute confidence intervals for regressions? From the Details section of the help Calculation is performed by the (currently undocumented) predictdf generic function and its methods. For most methods the confidence bounds are computed using
17,393
What is data blending?
http://www.cs.cornell.edu/~caruana/ctp/ct.papers/caruana.icml04.icdm06long.pdf Some papers to help you further understand what blending is. I think you can also google for ensemble selection/learning, and stacking as well. Your general understanding of 'mixing up outcomes from many models and resulting in a better result' is correct though.
What is data blending?
http://www.cs.cornell.edu/~caruana/ctp/ct.papers/caruana.icml04.icdm06long.pdf Some papers to help you further understand what blending is. I think you can also google for ensemble selection/learning,
What is data blending? http://www.cs.cornell.edu/~caruana/ctp/ct.papers/caruana.icml04.icdm06long.pdf Some papers to help you further understand what blending is. I think you can also google for ensemble selection/learning, and stacking as well. Your general understanding of 'mixing up outcomes from many models and resulting in a better result' is correct though.
What is data blending? http://www.cs.cornell.edu/~caruana/ctp/ct.papers/caruana.icml04.icdm06long.pdf Some papers to help you further understand what blending is. I think you can also google for ensemble selection/learning,
17,394
What is data blending?
Boosting (as mentioned in the linked discussion) is a method that combines a set of algorithms to get a result that is better than what you can get from any single algorithm. For example random forests is a method for combining various classification trees for a classification algorithm. This approach is formally called ensemble averaging (although the algoithm usually applies majority rule). Blending seems to be a word some people use to describe a boosting approach to classification.
What is data blending?
Boosting (as mentioned in the linked discussion) is a method that combines a set of algorithms to get a result that is better than what you can get from any single algorithm. For example random fores
What is data blending? Boosting (as mentioned in the linked discussion) is a method that combines a set of algorithms to get a result that is better than what you can get from any single algorithm. For example random forests is a method for combining various classification trees for a classification algorithm. This approach is formally called ensemble averaging (although the algoithm usually applies majority rule). Blending seems to be a word some people use to describe a boosting approach to classification.
What is data blending? Boosting (as mentioned in the linked discussion) is a method that combines a set of algorithms to get a result that is better than what you can get from any single algorithm. For example random fores
17,395
What is data blending?
In industry data blending is not about models but about preprocessing: It is the when data is merged that comes from different sources, like one from a database and other data from CSV files.
What is data blending?
In industry data blending is not about models but about preprocessing: It is the when data is merged that comes from different sources, like one from a database and other data from CSV files.
What is data blending? In industry data blending is not about models but about preprocessing: It is the when data is merged that comes from different sources, like one from a database and other data from CSV files.
What is data blending? In industry data blending is not about models but about preprocessing: It is the when data is merged that comes from different sources, like one from a database and other data from CSV files.
17,396
What is data blending?
It seems blending is mixing up outcomes from many models and resulting in a better result. Is there any resource that helps me knowing more about it? Indeed, this is how they work. They try to give an optimal weight to (or directly learn from) the outputs of other learners. They usually achieve state of the art performance (after careful tuning) over almost all the datasets. These weights are actually given to the "out of folds" predictions over cross validated models (to avoid giving the highest weights for models who have a perfect accuracy on the training set, such as random forests) As the resources were quite scarce, I wrote these two articles: Introduction to blending in Python (method and implementation oriented) Why does blending works ? (theoretical arguments about the success of this method)
What is data blending?
It seems blending is mixing up outcomes from many models and resulting in a better result. Is there any resource that helps me knowing more about it? Indeed, this is how they work. They try to give a
What is data blending? It seems blending is mixing up outcomes from many models and resulting in a better result. Is there any resource that helps me knowing more about it? Indeed, this is how they work. They try to give an optimal weight to (or directly learn from) the outputs of other learners. They usually achieve state of the art performance (after careful tuning) over almost all the datasets. These weights are actually given to the "out of folds" predictions over cross validated models (to avoid giving the highest weights for models who have a perfect accuracy on the training set, such as random forests) As the resources were quite scarce, I wrote these two articles: Introduction to blending in Python (method and implementation oriented) Why does blending works ? (theoretical arguments about the success of this method)
What is data blending? It seems blending is mixing up outcomes from many models and resulting in a better result. Is there any resource that helps me knowing more about it? Indeed, this is how they work. They try to give a
17,397
Understanding proof of a lemma used in Hoeffding inequality
I’m not sure I understood your question correctly. I’ll try to answer: try to write $$-\frac{a}{b-a} e^{tb} + \frac{b}{b-a} e^{ta}$$ as a function of $u = t(b-a)$ : this is natural as you want a bound in $e^{u^2 \over 8}$. Helped by the experience, you will know that it is better to chose to write it in the form $e^{g(u)}$. Then $$e^{g(u)} = -\frac{a}{b-a} e^{tb} + \frac{b}{b-a} e^{ta}$$ leads to $$\begin{align*} g(u) &= \log\left( -\frac{a}{b-a} e^{tb} + \frac{b}{b-a} e^{ta} \right)\\ &= \log\left( e^{ta} \left( -\frac{a}{b-a} e^{t(b-a)} + \frac{b}{b-a} \right)\right)\\ &= ta + \log\left( \gamma e^u + (1-\gamma) \right)\\ &= -\gamma u + \log\left( \gamma e^u + (1-\gamma) \right),\\ \end{align*}$$ with $\gamma = - {a \over b-a}$. Is that the kind of thing you were asking for? Edit: a few comments on the proof The first trick deserves to be looked at carefully: if $\phi$ is a convex function, and $a\le X\le b$ is a centered random variable, then $$\mathbb{E}(\phi(X)) \le -{a\over b-a} \phi(b) + {b \over b-a} \phi(a) = \mathbb{E}(\phi(X_0)),$$ where $X_0$ is the discrete variable defined by $$\begin{align*} \mathbb P(X_0=a) &= {b \over b-a}\\ \mathbb P(X_0=b) &= -{a \over b-a}.\end{align*}$$ As a consequence, you get that $X_0$ is the centered variable with support in $[a,b]$ which has the highest variance: $$\mathsf{Var} (X) = \mathbb{E}(X^2) \le \mathbb{E}(X_0^2) = {ba^2 - ab^2 \over b-a } = - ab.$$ Note that if we fix a support width $(b-a)$, this is less than $(b-a)^2\over 4$ as Dilip says in the comments, this is because $(b-a)^2 + 4ab \ge 0$; the bound is attained for $a=-b$. Now turn to our problem. Why is it possible to get a bound depending only on $u = t(b-a)$? Intuitively, it is just a matter of rescaling of $X$: if you have a bound $\mathbb{E}\left( e^{tX} \right) \le s(t)$ for the case $b-a=1$, then the general bound can be obtained by taking $s( t(b-a) )$. Now think to the set of centered variables with support of width 1: there isn’t so much freedom, so a bound like $s(t)$ should exist. An other approach is to say simply that by the above lemma on $\mathbb{E}(\phi(X))$, then more generally $\mathbb{E}(\phi(tX)) \le \mathbb{E}(\phi(tX_0))$, which depends only on $u$ and $\gamma$: if you fix $u = u_0 = t_0 (b_0 - a_0)$ and $\gamma = \gamma_0 = - {a_0 \over b_0-a_0}$, and let $t, a, b$ vary, there is only one degree of freedom, and $t = {t_0 \over \alpha}$, $a = \alpha a_0$, $b = \alpha a_0$. We get $$-{a\over b-a} \phi(tb) + {b \over b-a} \phi(ta) = -{a_0\over b_0-a_0} \phi(tb_0) + {b_0 \over b_0-a_0} \phi(a_0).$$ You just have to find a bound involving only $u$. Now we are convinced that it can be done, it must be much easier! You don’t necessarily think to $g$ to begin with. The point is that you must write everything as a function of $u$ and $\gamma$. First note that $\gamma = -{a\over b-a}$, $1 -\gamma = {b\over b-a}$, $at = -\gamma u$ and $bt = (1-\gamma)u$. Then $$\begin{align*} \mathbb{E}(\phi(tX)) \le &-{a\over b-a} \phi(tb) + {b \over b-a} \phi(ta) \\ = & \gamma \phi((1-\gamma)u) + (1-\gamma) \phi(-\gamma u) \end{align*}$$ Now we are in the particular case $\phi=\exp$... I think you can finish. I hope I clarified it a little bit.
Understanding proof of a lemma used in Hoeffding inequality
I’m not sure I understood your question correctly. I’ll try to answer: try to write $$-\frac{a}{b-a} e^{tb} + \frac{b}{b-a} e^{ta}$$ as a function of $u = t(b-a)$ : this is natural as you want a bound
Understanding proof of a lemma used in Hoeffding inequality I’m not sure I understood your question correctly. I’ll try to answer: try to write $$-\frac{a}{b-a} e^{tb} + \frac{b}{b-a} e^{ta}$$ as a function of $u = t(b-a)$ : this is natural as you want a bound in $e^{u^2 \over 8}$. Helped by the experience, you will know that it is better to chose to write it in the form $e^{g(u)}$. Then $$e^{g(u)} = -\frac{a}{b-a} e^{tb} + \frac{b}{b-a} e^{ta}$$ leads to $$\begin{align*} g(u) &= \log\left( -\frac{a}{b-a} e^{tb} + \frac{b}{b-a} e^{ta} \right)\\ &= \log\left( e^{ta} \left( -\frac{a}{b-a} e^{t(b-a)} + \frac{b}{b-a} \right)\right)\\ &= ta + \log\left( \gamma e^u + (1-\gamma) \right)\\ &= -\gamma u + \log\left( \gamma e^u + (1-\gamma) \right),\\ \end{align*}$$ with $\gamma = - {a \over b-a}$. Is that the kind of thing you were asking for? Edit: a few comments on the proof The first trick deserves to be looked at carefully: if $\phi$ is a convex function, and $a\le X\le b$ is a centered random variable, then $$\mathbb{E}(\phi(X)) \le -{a\over b-a} \phi(b) + {b \over b-a} \phi(a) = \mathbb{E}(\phi(X_0)),$$ where $X_0$ is the discrete variable defined by $$\begin{align*} \mathbb P(X_0=a) &= {b \over b-a}\\ \mathbb P(X_0=b) &= -{a \over b-a}.\end{align*}$$ As a consequence, you get that $X_0$ is the centered variable with support in $[a,b]$ which has the highest variance: $$\mathsf{Var} (X) = \mathbb{E}(X^2) \le \mathbb{E}(X_0^2) = {ba^2 - ab^2 \over b-a } = - ab.$$ Note that if we fix a support width $(b-a)$, this is less than $(b-a)^2\over 4$ as Dilip says in the comments, this is because $(b-a)^2 + 4ab \ge 0$; the bound is attained for $a=-b$. Now turn to our problem. Why is it possible to get a bound depending only on $u = t(b-a)$? Intuitively, it is just a matter of rescaling of $X$: if you have a bound $\mathbb{E}\left( e^{tX} \right) \le s(t)$ for the case $b-a=1$, then the general bound can be obtained by taking $s( t(b-a) )$. Now think to the set of centered variables with support of width 1: there isn’t so much freedom, so a bound like $s(t)$ should exist. An other approach is to say simply that by the above lemma on $\mathbb{E}(\phi(X))$, then more generally $\mathbb{E}(\phi(tX)) \le \mathbb{E}(\phi(tX_0))$, which depends only on $u$ and $\gamma$: if you fix $u = u_0 = t_0 (b_0 - a_0)$ and $\gamma = \gamma_0 = - {a_0 \over b_0-a_0}$, and let $t, a, b$ vary, there is only one degree of freedom, and $t = {t_0 \over \alpha}$, $a = \alpha a_0$, $b = \alpha a_0$. We get $$-{a\over b-a} \phi(tb) + {b \over b-a} \phi(ta) = -{a_0\over b_0-a_0} \phi(tb_0) + {b_0 \over b_0-a_0} \phi(a_0).$$ You just have to find a bound involving only $u$. Now we are convinced that it can be done, it must be much easier! You don’t necessarily think to $g$ to begin with. The point is that you must write everything as a function of $u$ and $\gamma$. First note that $\gamma = -{a\over b-a}$, $1 -\gamma = {b\over b-a}$, $at = -\gamma u$ and $bt = (1-\gamma)u$. Then $$\begin{align*} \mathbb{E}(\phi(tX)) \le &-{a\over b-a} \phi(tb) + {b \over b-a} \phi(ta) \\ = & \gamma \phi((1-\gamma)u) + (1-\gamma) \phi(-\gamma u) \end{align*}$$ Now we are in the particular case $\phi=\exp$... I think you can finish. I hope I clarified it a little bit.
Understanding proof of a lemma used in Hoeffding inequality I’m not sure I understood your question correctly. I’ll try to answer: try to write $$-\frac{a}{b-a} e^{tb} + \frac{b}{b-a} e^{ta}$$ as a function of $u = t(b-a)$ : this is natural as you want a bound
17,398
Understanding proof of a lemma used in Hoeffding inequality
I would like to add a more compact answer that expands on @JBD's and @DilipSarwate's ideas that is taken entirely from "Concentration Inequalities" by Boucheron, Lugosi, and Massart. In summary, the idea is that we examine the second order Taylor expansion of the logarithm of the left hand side of Hoeffding's lemma. This allows us to make quick use of the well-known variance upper bound for bounded random variables. Let $\psi_X(t)$ denote the logarithmic MGF ($\log\mathbb{E}[e^{tX}]$). We have $$\psi''_X(t)=e^{-\psi_X(t)}\mathbb{E}\left[X^2e^{tX}\right]-e^{-2\psi_X(t)}\left(\mathbb{E}\left[Xe^{tX}\right]\right)^2$$ $$=\mathbb{V}[X]\leq \frac{(b-a)^2}{4}.$$ Then as $\psi_X(0)=\psi'_X(0)=0$, we have by Taylor's theorem for some $\theta\in[0,t]$ that $$\psi_X(t)=\psi_X(0)+\psi'_X(0)+\frac{t^2}{2}\psi_X''(\theta)=\frac{t^2}{2}\mathbb{V}[X]$$ $$\leq \frac{t^2(b-a)^2}{8}$$ $$\iff e^{\psi_X(t)}=\mathbb{E}[e^{tX}]\leq e^{\frac{t^2(b-a)^2}{8}}.$$
Understanding proof of a lemma used in Hoeffding inequality
I would like to add a more compact answer that expands on @JBD's and @DilipSarwate's ideas that is taken entirely from "Concentration Inequalities" by Boucheron, Lugosi, and Massart. In summary, the i
Understanding proof of a lemma used in Hoeffding inequality I would like to add a more compact answer that expands on @JBD's and @DilipSarwate's ideas that is taken entirely from "Concentration Inequalities" by Boucheron, Lugosi, and Massart. In summary, the idea is that we examine the second order Taylor expansion of the logarithm of the left hand side of Hoeffding's lemma. This allows us to make quick use of the well-known variance upper bound for bounded random variables. Let $\psi_X(t)$ denote the logarithmic MGF ($\log\mathbb{E}[e^{tX}]$). We have $$\psi''_X(t)=e^{-\psi_X(t)}\mathbb{E}\left[X^2e^{tX}\right]-e^{-2\psi_X(t)}\left(\mathbb{E}\left[Xe^{tX}\right]\right)^2$$ $$=\mathbb{V}[X]\leq \frac{(b-a)^2}{4}.$$ Then as $\psi_X(0)=\psi'_X(0)=0$, we have by Taylor's theorem for some $\theta\in[0,t]$ that $$\psi_X(t)=\psi_X(0)+\psi'_X(0)+\frac{t^2}{2}\psi_X''(\theta)=\frac{t^2}{2}\mathbb{V}[X]$$ $$\leq \frac{t^2(b-a)^2}{8}$$ $$\iff e^{\psi_X(t)}=\mathbb{E}[e^{tX}]\leq e^{\frac{t^2(b-a)^2}{8}}.$$
Understanding proof of a lemma used in Hoeffding inequality I would like to add a more compact answer that expands on @JBD's and @DilipSarwate's ideas that is taken entirely from "Concentration Inequalities" by Boucheron, Lugosi, and Massart. In summary, the i
17,399
Understanding proof of a lemma used in Hoeffding inequality
As @DilipSarwate noticed we effectively have \begin{equation} E[e^{tX}] \leq e^{\sigma_{\max}^2t^2/2}, \end{equation} which seems to be more than a mere coincidence and can leads us to think that there is a probabilistic argument to derive the result. And it is the case. The gist of the demonstration goes as follow : We want to prove that if X is a bounded random variable then it is a $\frac{(b-a)^2}{4}-$ sub-gaussian random variable. To do so we will first consider the logarithmic moment-generating function $g(t) = \log\mathbb{E}[e^{t\eta}]$. This function is indeed well-defined on $R$ as $\forall t \in R, e^{t\eta} > 0$ and therefore $\mathbb{E}[e^{t\eta}]>0$. We also have that g is differentiable as $\mathbb{E}[e^{t\eta}] >0 $ and $t\mapsto \mathbb{E}[e^{t\eta}]$ is differentiable (because $\forall t \in R,\: |\mathbb{E}[\eta e^{t\eta}]| \leqslant (|a| + |b|)e^{(|a|+|b|)t} < \infty$). We then have : \begin{align*} \forall t \in R,\: g'(t) = \frac{\mathbb{E}[\eta e^{t\eta}]}{\mathbb{E}[e^{t\eta}]} \end{align*} Showing with similar arguments that g' is in turn differentiable we get : \begin{equation} \begin{split} \forall t \in R,\: g''(t) & = \frac{\mathbb{E}[\eta^2 e^{t\eta}]\mathbb{E}[e^{t\eta}] - \mathbb{E}[\eta e^{t\eta}]^2}{\mathbb{E}[e^{t\eta}]^2} & = \mathbb{E}[\eta^2\frac{e^{t\eta}}{\mathbb{E}[e^{t\eta}]}] - \mathbb{E}[\eta\frac{e^{t\eta}}{\mathbb{E}[e^{t\eta}]}]^2 \end{split} \end{equation} We can now notice that $g''$ is the variance of the random variable Y of density $dy(t) = \frac{e^{t\eta}}{\mathbb{E}[e^{t\eta}]}dP_{\eta}(t)$. The law of Y being absolutely continuous with X's one we know that Y's support is [a,b]. We also know that for any real-valued random variable $Var(U) \leqslant \mathbb{E}[(U-c)^2] \: \forall c \in R$ which when we take $c=\frac{a+b}{2}$ yields $Var(U) \leqslant \mathbb{E}[(U - \frac{a+b}{2})^2] \leqslant (\frac{b-a}{2})^2$ We thus get $\forall t \in R, \: g''(t) \leqslant (\frac{b-a}{2})^2 $ We can also remark that $g(0) = 0 = \mathbb{E} \eta = g'(0)$ \begin{equation} \begin{split} \forall t \in R,\: g(t) & = g(t) - g(0) = \int_{0}^{t} g'(s) \,ds = \int_{0}^{t}\int_{0}^{s} g''(u) \,du\,ds & \leqslant \int_{0}^{t}\int_{0}^{s} (\frac{b-a}{2})^2 \,du\,ds \leqslant (\frac{b-a}{2})^2 \int_{0}^{t} s \,ds & \leqslant \frac{(b-a)^2}{4}\frac{t^{2}}{2} \leqslant \frac{(b-a)^2t^{2}}{8} \end{split} \end{equation} At last by composing this inequality with the exponential we get the desired result.
Understanding proof of a lemma used in Hoeffding inequality
As @DilipSarwate noticed we effectively have \begin{equation} E[e^{tX}] \leq e^{\sigma_{\max}^2t^2/2}, \end{equation} which seems to be more than a mere coincidence and can leads us to think that ther
Understanding proof of a lemma used in Hoeffding inequality As @DilipSarwate noticed we effectively have \begin{equation} E[e^{tX}] \leq e^{\sigma_{\max}^2t^2/2}, \end{equation} which seems to be more than a mere coincidence and can leads us to think that there is a probabilistic argument to derive the result. And it is the case. The gist of the demonstration goes as follow : We want to prove that if X is a bounded random variable then it is a $\frac{(b-a)^2}{4}-$ sub-gaussian random variable. To do so we will first consider the logarithmic moment-generating function $g(t) = \log\mathbb{E}[e^{t\eta}]$. This function is indeed well-defined on $R$ as $\forall t \in R, e^{t\eta} > 0$ and therefore $\mathbb{E}[e^{t\eta}]>0$. We also have that g is differentiable as $\mathbb{E}[e^{t\eta}] >0 $ and $t\mapsto \mathbb{E}[e^{t\eta}]$ is differentiable (because $\forall t \in R,\: |\mathbb{E}[\eta e^{t\eta}]| \leqslant (|a| + |b|)e^{(|a|+|b|)t} < \infty$). We then have : \begin{align*} \forall t \in R,\: g'(t) = \frac{\mathbb{E}[\eta e^{t\eta}]}{\mathbb{E}[e^{t\eta}]} \end{align*} Showing with similar arguments that g' is in turn differentiable we get : \begin{equation} \begin{split} \forall t \in R,\: g''(t) & = \frac{\mathbb{E}[\eta^2 e^{t\eta}]\mathbb{E}[e^{t\eta}] - \mathbb{E}[\eta e^{t\eta}]^2}{\mathbb{E}[e^{t\eta}]^2} & = \mathbb{E}[\eta^2\frac{e^{t\eta}}{\mathbb{E}[e^{t\eta}]}] - \mathbb{E}[\eta\frac{e^{t\eta}}{\mathbb{E}[e^{t\eta}]}]^2 \end{split} \end{equation} We can now notice that $g''$ is the variance of the random variable Y of density $dy(t) = \frac{e^{t\eta}}{\mathbb{E}[e^{t\eta}]}dP_{\eta}(t)$. The law of Y being absolutely continuous with X's one we know that Y's support is [a,b]. We also know that for any real-valued random variable $Var(U) \leqslant \mathbb{E}[(U-c)^2] \: \forall c \in R$ which when we take $c=\frac{a+b}{2}$ yields $Var(U) \leqslant \mathbb{E}[(U - \frac{a+b}{2})^2] \leqslant (\frac{b-a}{2})^2$ We thus get $\forall t \in R, \: g''(t) \leqslant (\frac{b-a}{2})^2 $ We can also remark that $g(0) = 0 = \mathbb{E} \eta = g'(0)$ \begin{equation} \begin{split} \forall t \in R,\: g(t) & = g(t) - g(0) = \int_{0}^{t} g'(s) \,ds = \int_{0}^{t}\int_{0}^{s} g''(u) \,du\,ds & \leqslant \int_{0}^{t}\int_{0}^{s} (\frac{b-a}{2})^2 \,du\,ds \leqslant (\frac{b-a}{2})^2 \int_{0}^{t} s \,ds & \leqslant \frac{(b-a)^2}{4}\frac{t^{2}}{2} \leqslant \frac{(b-a)^2t^{2}}{8} \end{split} \end{equation} At last by composing this inequality with the exponential we get the desired result.
Understanding proof of a lemma used in Hoeffding inequality As @DilipSarwate noticed we effectively have \begin{equation} E[e^{tX}] \leq e^{\sigma_{\max}^2t^2/2}, \end{equation} which seems to be more than a mere coincidence and can leads us to think that ther
17,400
Which statistical classification algorithm can predict true/false for a sequence of inputs?
You could try probabilistic approaches similar to the naive Bayes classifier but with weaker assumptions. For example, instead of making the strong independence assumption, make a Markov assumption: $$ p(x \mid c) = p(x_0 \mid c)\prod_t p(x_t \mid x_{t - 1}, c) $$ $c$ is your class label, $x$ is your sequence. You need to estimate two conditional distributions, one for $c = 1$ and one for $c = 0$. By Bayes' rule: $$ p(c = 1 \mid x) = \frac{p(x \mid c = 1) p(c = 1)}{p(x \mid c = 1) p(c = 1) + p(x \mid c = 0) p(c = 0)}. $$ Which distributions to pick for $p(x_t \mid x_{t - 1}, c)$ depends on which other assumptions you can make about the sequences and how much data you have available. For example, you could use: $$ p(x_t \mid x_{t - 1}, c) = \frac{\pi(x_t, x_{t - 1}, c)}{\sum_i \pi(x_i, x_{t - 1}, c)} $$ With distributions like this, if there are 21 different numbers occurring in your sequences, you would have to estimate $21 \cdot 21 \cdot 2 = 882$ parameters $\pi(x_t, x_t, c)$ plus $21 \cdot 2 = 42$ parameters for $p(x_0 \mid c)$ plus $2$ parameters for $p(c)$. If the assumptions of your model are not met, it can help to fine-tune the parameters directly with respect to the classification performance, for example by minimizing the average log-loss $$ -\frac{1}{\#\mathcal{D}} \sum_{(x, c) \in \mathcal{D}} \log p(c \mid x) $$ using gradient-descent.
Which statistical classification algorithm can predict true/false for a sequence of inputs?
You could try probabilistic approaches similar to the naive Bayes classifier but with weaker assumptions. For example, instead of making the strong independence assumption, make a Markov assumption: $
Which statistical classification algorithm can predict true/false for a sequence of inputs? You could try probabilistic approaches similar to the naive Bayes classifier but with weaker assumptions. For example, instead of making the strong independence assumption, make a Markov assumption: $$ p(x \mid c) = p(x_0 \mid c)\prod_t p(x_t \mid x_{t - 1}, c) $$ $c$ is your class label, $x$ is your sequence. You need to estimate two conditional distributions, one for $c = 1$ and one for $c = 0$. By Bayes' rule: $$ p(c = 1 \mid x) = \frac{p(x \mid c = 1) p(c = 1)}{p(x \mid c = 1) p(c = 1) + p(x \mid c = 0) p(c = 0)}. $$ Which distributions to pick for $p(x_t \mid x_{t - 1}, c)$ depends on which other assumptions you can make about the sequences and how much data you have available. For example, you could use: $$ p(x_t \mid x_{t - 1}, c) = \frac{\pi(x_t, x_{t - 1}, c)}{\sum_i \pi(x_i, x_{t - 1}, c)} $$ With distributions like this, if there are 21 different numbers occurring in your sequences, you would have to estimate $21 \cdot 21 \cdot 2 = 882$ parameters $\pi(x_t, x_t, c)$ plus $21 \cdot 2 = 42$ parameters for $p(x_0 \mid c)$ plus $2$ parameters for $p(c)$. If the assumptions of your model are not met, it can help to fine-tune the parameters directly with respect to the classification performance, for example by minimizing the average log-loss $$ -\frac{1}{\#\mathcal{D}} \sum_{(x, c) \in \mathcal{D}} \log p(c \mid x) $$ using gradient-descent.
Which statistical classification algorithm can predict true/false for a sequence of inputs? You could try probabilistic approaches similar to the naive Bayes classifier but with weaker assumptions. For example, instead of making the strong independence assumption, make a Markov assumption: $