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
33,501
Does the posterior necessarily follow the same conditional dependence structure as the prior?
No, it doesn't: Under the assumption that $a \ \bot \ b$, the right-hand-side of your last equation is: $$p(x|a,b) \cdot p(a) \cdot p(b) = p(x,a,b) \overset{a,b}{\propto} p(a,b|x).$$ Thus, you are effectively asking whether or not: $$a \ \bot \ b \quad \quad \implies \quad \quad p(a|x) \cdot p(b|x) \propto p(a,b|x).$$ That is, you are asking whether prior independence of $a$ and $b$ implies posterior independence of these random variables. Generally speaking, no it doesn't --- many statistical models involve data $x$ that give information about both prior variables, in such a way that they exhibit statistical dependence a posteriori.
Does the posterior necessarily follow the same conditional dependence structure as the prior?
No, it doesn't: Under the assumption that $a \ \bot \ b$, the right-hand-side of your last equation is: $$p(x|a,b) \cdot p(a) \cdot p(b) = p(x,a,b) \overset{a,b}{\propto} p(a,b|x).$$ Thus, you are ef
Does the posterior necessarily follow the same conditional dependence structure as the prior? No, it doesn't: Under the assumption that $a \ \bot \ b$, the right-hand-side of your last equation is: $$p(x|a,b) \cdot p(a) \cdot p(b) = p(x,a,b) \overset{a,b}{\propto} p(a,b|x).$$ Thus, you are effectively asking whether or not: $$a \ \bot \ b \quad \quad \implies \quad \quad p(a|x) \cdot p(b|x) \propto p(a,b|x).$$ That is, you are asking whether prior independence of $a$ and $b$ implies posterior independence of these random variables. Generally speaking, no it doesn't --- many statistical models involve data $x$ that give information about both prior variables, in such a way that they exhibit statistical dependence a posteriori.
Does the posterior necessarily follow the same conditional dependence structure as the prior? No, it doesn't: Under the assumption that $a \ \bot \ b$, the right-hand-side of your last equation is: $$p(x|a,b) \cdot p(a) \cdot p(b) = p(x,a,b) \overset{a,b}{\propto} p(a,b|x).$$ Thus, you are ef
33,502
Random walk: kings on a chessboard
Let's exploit the symmetry to simplify the calculations. The chessboard and its moves remain the same when the board is reflected vertically, horizontally, or diagonally. This decomposes its nine squares into three types, their orbits under this symmetry group. Correspondingly, each king can be in one of three "states": a corner square ($C$), an edge square ($E$), or the central ("middle") square ($M$). (A state ignores which particular square a king is on and tracks only its equivalence class under the group of symmetries.) The following results are immediate: From a corner square, there are two transitions to edge squares and one transition to a middle square. Because the three transitions are equiprobable, $$\Pr(C \to E) = 2/3,\quad \Pr(C \to M) = 1/3.$$ This gives a row $(0, 2/3, 1/3)$ in a transition matrix for the states $(C, E, M)$. From an edge square there are two transitions to corner squares, two to other edge squares, and one to the middle square. This gives a second row $(2/5, 2/5, 1/5)$ in a transition matrix. From the middle square there are four transitions to corner squares and four to middle squares. The third row of a transition matrix therefore is $(4/8, 4/8, 0) = (1/2, 1/2, 0)$. In this graph representing this Markov chain, transition probabilities are represented both by edge thickness and color: By inspection or otherwise, we find that a left eigenvector of its transition matrix $$\mathbb{P} = \left( \begin{array}{ccc} 0 & \frac{2}{3} & \frac{1}{3} \\ \frac{2}{5} & \frac{2}{5} & \frac{1}{5} \\ \frac{1}{2} & \frac{1}{2} & 0 \\ \end{array} \right)$$ is $\omega = (3, 5, 2)^\prime$. This claim is easily checked by performing the multiplication: $\omega \mathbb{P} = 1 \omega.$ The eigenvalue manifestly is $1$. Because all states are connected, $\omega$ gives the limiting probabilities of each king being in each state; we only need to rescale its components to sum to unity: $$\omega = (\omega_C, \omega_E, \omega_M) = (3/10, 5/10, 2/10).$$ (This is where we reap the benefits of exploiting the symmetry: instead of working with a nine by nine matrix of $81$ elements we only have to compute with a three by three matrix of $9$ elements. The reduction of the problem from nine states to three paid off quadratically by reducing the computational effort by a factor of $(9/3)^2 = 9$.) The (limiting) chance that both kings are in a state $s$ of (limiting) probability $\omega_s$ is $\omega_s^2$ because the kings move independently. The chance that both kings are in the same cell is found by conditioning on the state: by symmetry, each cell in a given state has the same limiting probability, so if both kings are found in a state $s$ having $k_s$ cells, the chance they are both in the same cell is $1/k_s$. Whence the solution is $$\sum_{s\in \{C,E,M\}}\frac{ \omega_s^2 }{k_s} = \left(\frac{3}{10}\right)^2\frac{1}{4} + \left(\frac{5}{10}\right)^2\frac{1}{4} + \left(\frac{2}{10}\right)^2\frac{1}{1} = \frac{9}{400} + \frac{25}{400} + \frac{16}{400} = \frac{1}{8}.$$
Random walk: kings on a chessboard
Let's exploit the symmetry to simplify the calculations. The chessboard and its moves remain the same when the board is reflected vertically, horizontally, or diagonally. This decomposes its nine squ
Random walk: kings on a chessboard Let's exploit the symmetry to simplify the calculations. The chessboard and its moves remain the same when the board is reflected vertically, horizontally, or diagonally. This decomposes its nine squares into three types, their orbits under this symmetry group. Correspondingly, each king can be in one of three "states": a corner square ($C$), an edge square ($E$), or the central ("middle") square ($M$). (A state ignores which particular square a king is on and tracks only its equivalence class under the group of symmetries.) The following results are immediate: From a corner square, there are two transitions to edge squares and one transition to a middle square. Because the three transitions are equiprobable, $$\Pr(C \to E) = 2/3,\quad \Pr(C \to M) = 1/3.$$ This gives a row $(0, 2/3, 1/3)$ in a transition matrix for the states $(C, E, M)$. From an edge square there are two transitions to corner squares, two to other edge squares, and one to the middle square. This gives a second row $(2/5, 2/5, 1/5)$ in a transition matrix. From the middle square there are four transitions to corner squares and four to middle squares. The third row of a transition matrix therefore is $(4/8, 4/8, 0) = (1/2, 1/2, 0)$. In this graph representing this Markov chain, transition probabilities are represented both by edge thickness and color: By inspection or otherwise, we find that a left eigenvector of its transition matrix $$\mathbb{P} = \left( \begin{array}{ccc} 0 & \frac{2}{3} & \frac{1}{3} \\ \frac{2}{5} & \frac{2}{5} & \frac{1}{5} \\ \frac{1}{2} & \frac{1}{2} & 0 \\ \end{array} \right)$$ is $\omega = (3, 5, 2)^\prime$. This claim is easily checked by performing the multiplication: $\omega \mathbb{P} = 1 \omega.$ The eigenvalue manifestly is $1$. Because all states are connected, $\omega$ gives the limiting probabilities of each king being in each state; we only need to rescale its components to sum to unity: $$\omega = (\omega_C, \omega_E, \omega_M) = (3/10, 5/10, 2/10).$$ (This is where we reap the benefits of exploiting the symmetry: instead of working with a nine by nine matrix of $81$ elements we only have to compute with a three by three matrix of $9$ elements. The reduction of the problem from nine states to three paid off quadratically by reducing the computational effort by a factor of $(9/3)^2 = 9$.) The (limiting) chance that both kings are in a state $s$ of (limiting) probability $\omega_s$ is $\omega_s^2$ because the kings move independently. The chance that both kings are in the same cell is found by conditioning on the state: by symmetry, each cell in a given state has the same limiting probability, so if both kings are found in a state $s$ having $k_s$ cells, the chance they are both in the same cell is $1/k_s$. Whence the solution is $$\sum_{s\in \{C,E,M\}}\frac{ \omega_s^2 }{k_s} = \left(\frac{3}{10}\right)^2\frac{1}{4} + \left(\frac{5}{10}\right)^2\frac{1}{4} + \left(\frac{2}{10}\right)^2\frac{1}{1} = \frac{9}{400} + \frac{25}{400} + \frac{16}{400} = \frac{1}{8}.$$
Random walk: kings on a chessboard Let's exploit the symmetry to simplify the calculations. The chessboard and its moves remain the same when the board is reflected vertically, horizontally, or diagonally. This decomposes its nine squ
33,503
Random walk: kings on a chessboard
Since the two kings are moving independently, you can consider them separately. If the board is of finite size, and doesn't have any closed subsections, this is one of those cases where the stationary distribution can be found by solving the detailed balance equation. In this case, as $n$ goes to infinity, the probability of a king being in a square becomes proportional to the number of squares adjacent to it, i.e. three for each corner square, five for each edge square, and eight for the middle square. This sums to $40$, so the chance of being in the middle square is $8/40$, in any corner square is $3/40$, and in any edge square is $5/40$. Since this is true for both kings independently, the chance of them both being in the middle square is $(8/40)^2 = 64/1600$, of both being in any corner square is $(3/40)^2=9/1600$, and in any edge square is $(5/40)^2=25/1600$. So the chance of them being in the same square approaches $\frac{64+4\times9+4\times25}{1600} = \frac{200}{1600} = \frac{1}{8}$ as $n$ approaches infinity.
Random walk: kings on a chessboard
Since the two kings are moving independently, you can consider them separately. If the board is of finite size, and doesn't have any closed subsections, this is one of those cases where the stationary
Random walk: kings on a chessboard Since the two kings are moving independently, you can consider them separately. If the board is of finite size, and doesn't have any closed subsections, this is one of those cases where the stationary distribution can be found by solving the detailed balance equation. In this case, as $n$ goes to infinity, the probability of a king being in a square becomes proportional to the number of squares adjacent to it, i.e. three for each corner square, five for each edge square, and eight for the middle square. This sums to $40$, so the chance of being in the middle square is $8/40$, in any corner square is $3/40$, and in any edge square is $5/40$. Since this is true for both kings independently, the chance of them both being in the middle square is $(8/40)^2 = 64/1600$, of both being in any corner square is $(3/40)^2=9/1600$, and in any edge square is $(5/40)^2=25/1600$. So the chance of them being in the same square approaches $\frac{64+4\times9+4\times25}{1600} = \frac{200}{1600} = \frac{1}{8}$ as $n$ approaches infinity.
Random walk: kings on a chessboard Since the two kings are moving independently, you can consider them separately. If the board is of finite size, and doesn't have any closed subsections, this is one of those cases where the stationary
33,504
Random walk: kings on a chessboard
You can solve using transition probability matrix. $\begin{bmatrix} C_1 & C_2 & C_3 \\ C_4 & C_5 & C_6 \\ C_7 & C_8 & C_9 \\\end{bmatrix}$ Construct Transition probability matrix, using the probability of one cell to another. Eg: $P[C_1, C_2] = P[C_1, C_4]= P[C_1, C_5] = \frac{1}{3}$. P will be a $9 \times 9$ matrix. Now you can calculate stationary probabilities (Since all states are recurrent). Solve $\pi P = \pi $ such that $\sum \pi =1$. This gives the probability of one king in particular square as n large. Use the independence property you can arrive at the required probability.
Random walk: kings on a chessboard
You can solve using transition probability matrix. $\begin{bmatrix} C_1 & C_2 & C_3 \\ C_4 & C_5 & C_6 \\ C_7 & C_8 & C_9 \\\end{bmatrix}$ Construct Transition probability matrix, using the probabili
Random walk: kings on a chessboard You can solve using transition probability matrix. $\begin{bmatrix} C_1 & C_2 & C_3 \\ C_4 & C_5 & C_6 \\ C_7 & C_8 & C_9 \\\end{bmatrix}$ Construct Transition probability matrix, using the probability of one cell to another. Eg: $P[C_1, C_2] = P[C_1, C_4]= P[C_1, C_5] = \frac{1}{3}$. P will be a $9 \times 9$ matrix. Now you can calculate stationary probabilities (Since all states are recurrent). Solve $\pi P = \pi $ such that $\sum \pi =1$. This gives the probability of one king in particular square as n large. Use the independence property you can arrive at the required probability.
Random walk: kings on a chessboard You can solve using transition probability matrix. $\begin{bmatrix} C_1 & C_2 & C_3 \\ C_4 & C_5 & C_6 \\ C_7 & C_8 & C_9 \\\end{bmatrix}$ Construct Transition probability matrix, using the probabili
33,505
Interpreting a negative confidence limit for a proportion
Because it is not possible to have a percentage less than zero, the first interpretation is the response is that between 0% and 52% were happy. Just substitute 0 for the negative percentage. The bigger question is why they are reporting results with such large margins of error. As a client, knowing that between 0% and 52% of respondents were happy is a pretty meaningless result. With such a small sample size, they are going to get those large margins of error for every single question in the survey. Ten people is just too small a sample size to get robust estimates. For me, the bigger question is why they didn't use a qualitative method for this work. Update based on comment below: increasing the margin of error to decrease the sample size is not a good way forward as you have seen with the margins of error you currently have. With a population of 60, you need to sample the entire population, i.e. undertaken a census, in order to get acceptably low margins of error. As for any survey, non-response bias will be a concern. Recommendation: for the population of 60 either undertake a census if you want the results to be analysed statistically, or pick some key individuals in the population on the basis of their known attitudes or views, use qualitative interviews, and report themes (don't do any statistics, not even counts). For 10 people, qualitative interviewing is just as quick as doing a survey anyway.
Interpreting a negative confidence limit for a proportion
Because it is not possible to have a percentage less than zero, the first interpretation is the response is that between 0% and 52% were happy. Just substitute 0 for the negative percentage. The bigge
Interpreting a negative confidence limit for a proportion Because it is not possible to have a percentage less than zero, the first interpretation is the response is that between 0% and 52% were happy. Just substitute 0 for the negative percentage. The bigger question is why they are reporting results with such large margins of error. As a client, knowing that between 0% and 52% of respondents were happy is a pretty meaningless result. With such a small sample size, they are going to get those large margins of error for every single question in the survey. Ten people is just too small a sample size to get robust estimates. For me, the bigger question is why they didn't use a qualitative method for this work. Update based on comment below: increasing the margin of error to decrease the sample size is not a good way forward as you have seen with the margins of error you currently have. With a population of 60, you need to sample the entire population, i.e. undertaken a census, in order to get acceptably low margins of error. As for any survey, non-response bias will be a concern. Recommendation: for the population of 60 either undertake a census if you want the results to be analysed statistically, or pick some key individuals in the population on the basis of their known attitudes or views, use qualitative interviews, and report themes (don't do any statistics, not even counts). For 10 people, qualitative interviewing is just as quick as doing a survey anyway.
Interpreting a negative confidence limit for a proportion Because it is not possible to have a percentage less than zero, the first interpretation is the response is that between 0% and 52% were happy. Just substitute 0 for the negative percentage. The bigge
33,506
Interpreting a negative confidence limit for a proportion
The issue arises from the assumption of normality not quite being valid. The simple confidence interval typically reported assumes the sample means is normally distributed with a deviation equal to the standard error. This assumption is based on the central limit theorem, which requires large numbers. It is possible to get exact Frequentist confidence intervals for small populations. For this case, with happy/not happy, the results are binary and the percent happy has a binomial distribution. For this sample size, a more fun approach is a Bayesian approach -- what's the posterior distribution of beliefs in possible parameter values. The probability of being happy has a prior beta distribution. The formula is very simple, scroll down to Shrinkage Factors on this page. Beta Binomial Distribution on Wikipedia. It is easy to plot a nice graph in Excel showing the posterior distribution.
Interpreting a negative confidence limit for a proportion
The issue arises from the assumption of normality not quite being valid. The simple confidence interval typically reported assumes the sample means is normally distributed with a deviation equal to th
Interpreting a negative confidence limit for a proportion The issue arises from the assumption of normality not quite being valid. The simple confidence interval typically reported assumes the sample means is normally distributed with a deviation equal to the standard error. This assumption is based on the central limit theorem, which requires large numbers. It is possible to get exact Frequentist confidence intervals for small populations. For this case, with happy/not happy, the results are binary and the percent happy has a binomial distribution. For this sample size, a more fun approach is a Bayesian approach -- what's the posterior distribution of beliefs in possible parameter values. The probability of being happy has a prior beta distribution. The formula is very simple, scroll down to Shrinkage Factors on this page. Beta Binomial Distribution on Wikipedia. It is easy to plot a nice graph in Excel showing the posterior distribution.
Interpreting a negative confidence limit for a proportion The issue arises from the assumption of normality not quite being valid. The simple confidence interval typically reported assumes the sample means is normally distributed with a deviation equal to th
33,507
Interpreting a negative confidence limit for a proportion
I agree with the statements already made here, but I have this tool to add:Newcombe's widely-cited proportion calculator. Using this tool, the confidence limits of 2/10 (the 20% case you mentioned) are {5.7%:51%}. Unless you gather more data, you're only really sure that half or less of the managers were happy. Edit: linking to university sites is problematic, as the webpages are often restructured as faculty come and go. Try this: vassarstats
Interpreting a negative confidence limit for a proportion
I agree with the statements already made here, but I have this tool to add:Newcombe's widely-cited proportion calculator. Using this tool, the confidence limits of 2/10 (the 20% case you mentioned) ar
Interpreting a negative confidence limit for a proportion I agree with the statements already made here, but I have this tool to add:Newcombe's widely-cited proportion calculator. Using this tool, the confidence limits of 2/10 (the 20% case you mentioned) are {5.7%:51%}. Unless you gather more data, you're only really sure that half or less of the managers were happy. Edit: linking to university sites is problematic, as the webpages are often restructured as faculty come and go. Try this: vassarstats
Interpreting a negative confidence limit for a proportion I agree with the statements already made here, but I have this tool to add:Newcombe's widely-cited proportion calculator. Using this tool, the confidence limits of 2/10 (the 20% case you mentioned) ar
33,508
What exactly does 'representative sample' refer to?
A representative sample is one which is drawn without bias from the population of interest. For example, suppose I want to find out how many people drink milk with breakfast. If I am a vegan, and I ask a random sample of my friends and associates (many of whom are also vegans), then the sample I have taken is not representative of the population as a whole: I will of course find that a low proportion of people drink milk with breakfast, but this is an artifact of my choice of sample, not because so few people do in reality. Basically, if there's any factor which causes us to select our sample in a non-random way, the inference is questionable. In the example above, a representative sample is one drawn randomly from all raids. We could also draw samples only during winter, in which case we might get a skewed result (maybe the cold makes people less prone to cooperation). Hope that clears things up a bit...
What exactly does 'representative sample' refer to?
A representative sample is one which is drawn without bias from the population of interest. For example, suppose I want to find out how many people drink milk with breakfast. If I am a vegan, and I as
What exactly does 'representative sample' refer to? A representative sample is one which is drawn without bias from the population of interest. For example, suppose I want to find out how many people drink milk with breakfast. If I am a vegan, and I ask a random sample of my friends and associates (many of whom are also vegans), then the sample I have taken is not representative of the population as a whole: I will of course find that a low proportion of people drink milk with breakfast, but this is an artifact of my choice of sample, not because so few people do in reality. Basically, if there's any factor which causes us to select our sample in a non-random way, the inference is questionable. In the example above, a representative sample is one drawn randomly from all raids. We could also draw samples only during winter, in which case we might get a skewed result (maybe the cold makes people less prone to cooperation). Hope that clears things up a bit...
What exactly does 'representative sample' refer to? A representative sample is one which is drawn without bias from the population of interest. For example, suppose I want to find out how many people drink milk with breakfast. If I am a vegan, and I as
33,509
What exactly does 'representative sample' refer to?
There are many different meanings of a term "representativity" in different fields. To give an answer I will post a quote from Bethlehem, Cobben, Schouten (2009) Indicators for the Representativeness of Survey Response. The concept of representativity is often used in survey research, but usually it is not clear what it means. Kruskal and Mosteller (1979a, 1979b and 1979c) present an extensive overview of what representative is supposed to mean in non-scientific literature, scientific literature excluding statistics and in the statistical literature. They found the following meanings for ‘representative sampling’: (1) general acclaim for data, (2) absence of selective forces, (3) miniature of the population, (4) typical or ideal case(s), (5) coverage of the population, (6) a vague term, to be made precise, (7) representative sampling as a specific sampling method, (8) as permitting good estimation, or (9) good enough for a particular purpose. They recommended not using the word representative, but instead to specify what one means. These are the references to Kruskal, and Mosteller: Kruskal, W. and Mosteller, F. (1979a). Representative sampling, I: Nonscientific literature. International Statistical Review, 47, 13–24. Kruskal, W. and Mosteller, F. (1979b). Representative sampling, II: Scientific literature, excluding statistics. International Statistical Review, 47, 113–127. Kruskal, W. and Mosteller, F. (1979c). Representative sampling, III: the current statistical literature. International Statistical Review, 47, 245–265. Kruskal, W. and Mosteller, F. (1980). Representative sampling, IV: the history of the concept in statistics, 1895 - 1939. International Statistical Review, 48, 169–195.
What exactly does 'representative sample' refer to?
There are many different meanings of a term "representativity" in different fields. To give an answer I will post a quote from Bethlehem, Cobben, Schouten (2009) Indicators for the Representativeness
What exactly does 'representative sample' refer to? There are many different meanings of a term "representativity" in different fields. To give an answer I will post a quote from Bethlehem, Cobben, Schouten (2009) Indicators for the Representativeness of Survey Response. The concept of representativity is often used in survey research, but usually it is not clear what it means. Kruskal and Mosteller (1979a, 1979b and 1979c) present an extensive overview of what representative is supposed to mean in non-scientific literature, scientific literature excluding statistics and in the statistical literature. They found the following meanings for ‘representative sampling’: (1) general acclaim for data, (2) absence of selective forces, (3) miniature of the population, (4) typical or ideal case(s), (5) coverage of the population, (6) a vague term, to be made precise, (7) representative sampling as a specific sampling method, (8) as permitting good estimation, or (9) good enough for a particular purpose. They recommended not using the word representative, but instead to specify what one means. These are the references to Kruskal, and Mosteller: Kruskal, W. and Mosteller, F. (1979a). Representative sampling, I: Nonscientific literature. International Statistical Review, 47, 13–24. Kruskal, W. and Mosteller, F. (1979b). Representative sampling, II: Scientific literature, excluding statistics. International Statistical Review, 47, 113–127. Kruskal, W. and Mosteller, F. (1979c). Representative sampling, III: the current statistical literature. International Statistical Review, 47, 245–265. Kruskal, W. and Mosteller, F. (1980). Representative sampling, IV: the history of the concept in statistics, 1895 - 1939. International Statistical Review, 48, 169–195.
What exactly does 'representative sample' refer to? There are many different meanings of a term "representativity" in different fields. To give an answer I will post a quote from Bethlehem, Cobben, Schouten (2009) Indicators for the Representativeness
33,510
What exactly does 'representative sample' refer to?
There seem to be three things going on in this discussion. John is correct in the statistical parlance that "representative sample means at random with no bias in the selection methodology. That needs to be distinguished from what Jose said about sample size. Sample size is not a measure of how reliable a sample is, but it more a measure of how accurate it is in the context of variance. This is what is usually referred to in the polling data for example as "accurate withing plus or minus five percentage points." That does not mean that the reference you quoted meant to use the phrase in the way John and I have described it. To figure if that is so you would have to read more of what they told you about how the sample was selected - and perhaps ask some rather pointed questions. The term is frequently misused to mean in " Using my judgment I purposely selected cases that I felt were representative."
What exactly does 'representative sample' refer to?
There seem to be three things going on in this discussion. John is correct in the statistical parlance that "representative sample means at random with no bias in the selection methodology. That needs
What exactly does 'representative sample' refer to? There seem to be three things going on in this discussion. John is correct in the statistical parlance that "representative sample means at random with no bias in the selection methodology. That needs to be distinguished from what Jose said about sample size. Sample size is not a measure of how reliable a sample is, but it more a measure of how accurate it is in the context of variance. This is what is usually referred to in the polling data for example as "accurate withing plus or minus five percentage points." That does not mean that the reference you quoted meant to use the phrase in the way John and I have described it. To figure if that is so you would have to read more of what they told you about how the sample was selected - and perhaps ask some rather pointed questions. The term is frequently misused to mean in " Using my judgment I purposely selected cases that I felt were representative."
What exactly does 'representative sample' refer to? There seem to be three things going on in this discussion. John is correct in the statistical parlance that "representative sample means at random with no bias in the selection methodology. That needs
33,511
What exactly does 'representative sample' refer to?
The representative sample is that how preciously you collect sample from the target population. There is no quantitative method for this purpose, and the person who make sampling frame can assess how much sample is representative of population. Nevertheless, one can also reduce the bias of estimates to claim that sample is representative of population. Definition with Example A subset of a statistical population that accurately reflects the members of the entire population. A representative sample should be an unbiased indication of what the population is like. In a classroom of 30 students in which half the students are male and half are female, a representative sample might include six students: three males and three females. When a sample is not representative, the result is known as a sampling error. Using the classroom example again, a sample that included six students, all of whom were male, would not be a representative sample. Whatever conclusions were drawn from studying the six male students would not be likely to translate to the entire group since no female students were studied. For more information check this URL.
What exactly does 'representative sample' refer to?
The representative sample is that how preciously you collect sample from the target population. There is no quantitative method for this purpose, and the person who make sampling frame can assess how
What exactly does 'representative sample' refer to? The representative sample is that how preciously you collect sample from the target population. There is no quantitative method for this purpose, and the person who make sampling frame can assess how much sample is representative of population. Nevertheless, one can also reduce the bias of estimates to claim that sample is representative of population. Definition with Example A subset of a statistical population that accurately reflects the members of the entire population. A representative sample should be an unbiased indication of what the population is like. In a classroom of 30 students in which half the students are male and half are female, a representative sample might include six students: three males and three females. When a sample is not representative, the result is known as a sampling error. Using the classroom example again, a sample that included six students, all of whom were male, would not be a representative sample. Whatever conclusions were drawn from studying the six male students would not be likely to translate to the entire group since no female students were studied. For more information check this URL.
What exactly does 'representative sample' refer to? The representative sample is that how preciously you collect sample from the target population. There is no quantitative method for this purpose, and the person who make sampling frame can assess how
33,512
What exactly does 'representative sample' refer to?
Let me disagree with previous responses. A "representative sample" is that sample that have enough data to represent the natural behavior of the variable. Enough data seems to be difficult to establish, and depends on the kind of variable, however, sample of more than 30 experimental units are often considered as enough.
What exactly does 'representative sample' refer to?
Let me disagree with previous responses. A "representative sample" is that sample that have enough data to represent the natural behavior of the variable. Enough data seems to be difficult to establis
What exactly does 'representative sample' refer to? Let me disagree with previous responses. A "representative sample" is that sample that have enough data to represent the natural behavior of the variable. Enough data seems to be difficult to establish, and depends on the kind of variable, however, sample of more than 30 experimental units are often considered as enough.
What exactly does 'representative sample' refer to? Let me disagree with previous responses. A "representative sample" is that sample that have enough data to represent the natural behavior of the variable. Enough data seems to be difficult to establis
33,513
What is a good general purpose plain text data format like that used for Bibtex? [closed]
Why not use XML? There are many good parsers that directly translate XML files to data structures, even one for R ( http://cran.r-project.org/web/packages/XML/index.html ). The format looks like this (example taken from http://www.w3schools.com/xml/default.asp ). <?xml version="1.0"?> <notes> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> <note> <to>Janis</to> <from>Cardinal</from> <heading>Reminder</heading> <body>Don't forget me the next weekend!</body> </note> </notes> E.g, using the XML package: z=xmlTreeParse("test.xml") z$doc$children$notes gives access to the complete notes body, z$doc$children$notes[1] is just the first node and so on...
What is a good general purpose plain text data format like that used for Bibtex? [closed]
Why not use XML? There are many good parsers that directly translate XML files to data structures, even one for R ( http://cran.r-project.org/web/packages/XML/index.html ). The format looks like this
What is a good general purpose plain text data format like that used for Bibtex? [closed] Why not use XML? There are many good parsers that directly translate XML files to data structures, even one for R ( http://cran.r-project.org/web/packages/XML/index.html ). The format looks like this (example taken from http://www.w3schools.com/xml/default.asp ). <?xml version="1.0"?> <notes> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> <note> <to>Janis</to> <from>Cardinal</from> <heading>Reminder</heading> <body>Don't forget me the next weekend!</body> </note> </notes> E.g, using the XML package: z=xmlTreeParse("test.xml") z$doc$children$notes gives access to the complete notes body, z$doc$children$notes[1] is just the first node and so on...
What is a good general purpose plain text data format like that used for Bibtex? [closed] Why not use XML? There are many good parsers that directly translate XML files to data structures, even one for R ( http://cran.r-project.org/web/packages/XML/index.html ). The format looks like this
33,514
What is a good general purpose plain text data format like that used for Bibtex? [closed]
I'd go with YAML. Straight forward to edit and has plenty parsers in different languages: --- - question: 1 + 1 incorrect: - 1 - 3 - 4 correct: 2 - question: What is the capital city of the country renowned for koalas, emus, and kangaroos? incorrect: - Melbourne - Sydney - Australia correct: Canberra You could then write a little script to randomly mix the incorrect with correct answers and output the LaTeX suggested in DQdlM's answer. EDIT: This ruby script: require 'yaml' questions = YAML.load(File.read(ARGV.first)) questions.each_with_index do |question,index| answers = question['incorrect'].map{|i| ' \choice ' + i.to_s } answers << ' \CorrectChoice ' + question['correct'].to_s output = ["\\question{#{index + 1}}"] output << question['question'] output << " \\begin{choices}" output << answers.sort_by{rand} output << " \\end{choices}" output << "\n" puts output.flatten.join("\n") end Will produce the following output \question{1} 1 + 1 \begin{choices} \choice 4 \choice 1 \choice 3 \CorrectChoice 2 \end{choices} \question{2} What is the capital city of the country renowned for koalas, emus, and kangaroos? \begin{choices} \choice Melbourne \choice Sydney \CorrectChoice Canberra \choice Australia \end{choices}
What is a good general purpose plain text data format like that used for Bibtex? [closed]
I'd go with YAML. Straight forward to edit and has plenty parsers in different languages: --- - question: 1 + 1 incorrect: - 1 - 3 - 4 correct: 2 - question: What is the capital ci
What is a good general purpose plain text data format like that used for Bibtex? [closed] I'd go with YAML. Straight forward to edit and has plenty parsers in different languages: --- - question: 1 + 1 incorrect: - 1 - 3 - 4 correct: 2 - question: What is the capital city of the country renowned for koalas, emus, and kangaroos? incorrect: - Melbourne - Sydney - Australia correct: Canberra You could then write a little script to randomly mix the incorrect with correct answers and output the LaTeX suggested in DQdlM's answer. EDIT: This ruby script: require 'yaml' questions = YAML.load(File.read(ARGV.first)) questions.each_with_index do |question,index| answers = question['incorrect'].map{|i| ' \choice ' + i.to_s } answers << ' \CorrectChoice ' + question['correct'].to_s output = ["\\question{#{index + 1}}"] output << question['question'] output << " \\begin{choices}" output << answers.sort_by{rand} output << " \\end{choices}" output << "\n" puts output.flatten.join("\n") end Will produce the following output \question{1} 1 + 1 \begin{choices} \choice 4 \choice 1 \choice 3 \CorrectChoice 2 \end{choices} \question{2} What is the capital city of the country renowned for koalas, emus, and kangaroos? \begin{choices} \choice Melbourne \choice Sydney \CorrectChoice Canberra \choice Australia \end{choices}
What is a good general purpose plain text data format like that used for Bibtex? [closed] I'd go with YAML. Straight forward to edit and has plenty parsers in different languages: --- - question: 1 + 1 incorrect: - 1 - 3 - 4 correct: 2 - question: What is the capital ci
33,515
What is a good general purpose plain text data format like that used for Bibtex? [closed]
This may not fully address applications beyond your multiple choice questions but there is an exam class available for LaTeX. Multiple choice questions are formed like this: \question[2] The fascile of a nerve is surrounded by what connective tissue layer? \begin{choices} \choice endoneurium \choice epineurium \CorrectChoice perineruium \choice neurolemma \choice none of the above \end{choices} By including \printanswers in your preamble it highlights the correct answer.
What is a good general purpose plain text data format like that used for Bibtex? [closed]
This may not fully address applications beyond your multiple choice questions but there is an exam class available for LaTeX. Multiple choice questions are formed like this: \question[2] The fascile o
What is a good general purpose plain text data format like that used for Bibtex? [closed] This may not fully address applications beyond your multiple choice questions but there is an exam class available for LaTeX. Multiple choice questions are formed like this: \question[2] The fascile of a nerve is surrounded by what connective tissue layer? \begin{choices} \choice endoneurium \choice epineurium \CorrectChoice perineruium \choice neurolemma \choice none of the above \end{choices} By including \printanswers in your preamble it highlights the correct answer.
What is a good general purpose plain text data format like that used for Bibtex? [closed] This may not fully address applications beyond your multiple choice questions but there is an exam class available for LaTeX. Multiple choice questions are formed like this: \question[2] The fascile o
33,516
What is a good general purpose plain text data format like that used for Bibtex? [closed]
Org Mode can do that. One way would be like this: #+COLUMNS: %id %a %b %c %d %correct * 1 + 1 :PROPERTIES: :id: 1 :a: 1 :b: 2 :c: 3 :d: 4 :correct: b :END: * What is the capital city of the country renowned for koalas, emus, and kangaroos? :PROPERTIES: :id: 2 :a: Canberra :b: Melbourne :c: Sydney :d: Australia :correct: a :END: If you'd like to visually inspect a quick summary table then insert the following * The column view #+BEGIN: columnview :hlines 1 :id global #+END: Put the cursor in the #+BEGIN block and do C-c C-x C-u to get #+BEGIN: columnview :hlines 1 :id global | id | a | b | c | d | correct | |----+----------+-----------+--------+-----------+---------| | 1 | 1 | 2 | 3 | 4 | b | | 2 | Canberra | Melbourne | Sydney | Australia | a | | | | | | | | #+END: and if you'd like to import (to R, for instance) then insert a table name like this: #+BEGIN: columnview :hlines 1 :id global #+tblname: simpleDF | id | a | b | c | d | correct | |----+----------+-----------+--------+-----------+---------| | 1 | 1 | 2 | 3 | 4 | b | | 2 | Canberra | Melbourne | Sydney | Australia | a | #+END: then insert and execute the following R code block with C-c C-c: #+begin_src R :session *R* :var df=simpleDF :colnames yes head(df) #+end_src this gives #+results: | id | a | b | c | d | correct | |----+----------+-----------+--------+-----------+---------| | 1 | 1 | 2 | 3 | 4 | b | | 2 | Canberra | Melbourne | Sydney | Australia | a | The good news is that the data frame df is now stored in the active *R* session and is available to post-process however you like. All of this being said, if it were me, I would probably start with the exams package (in R) for the specific application of storing/writing multiple choice questions, though that YAML example looks really cool.
What is a good general purpose plain text data format like that used for Bibtex? [closed]
Org Mode can do that. One way would be like this: #+COLUMNS: %id %a %b %c %d %correct * 1 + 1 :PROPERTIES: :id: 1 :a: 1 :b: 2 :c: 3 :d: 4
What is a good general purpose plain text data format like that used for Bibtex? [closed] Org Mode can do that. One way would be like this: #+COLUMNS: %id %a %b %c %d %correct * 1 + 1 :PROPERTIES: :id: 1 :a: 1 :b: 2 :c: 3 :d: 4 :correct: b :END: * What is the capital city of the country renowned for koalas, emus, and kangaroos? :PROPERTIES: :id: 2 :a: Canberra :b: Melbourne :c: Sydney :d: Australia :correct: a :END: If you'd like to visually inspect a quick summary table then insert the following * The column view #+BEGIN: columnview :hlines 1 :id global #+END: Put the cursor in the #+BEGIN block and do C-c C-x C-u to get #+BEGIN: columnview :hlines 1 :id global | id | a | b | c | d | correct | |----+----------+-----------+--------+-----------+---------| | 1 | 1 | 2 | 3 | 4 | b | | 2 | Canberra | Melbourne | Sydney | Australia | a | | | | | | | | #+END: and if you'd like to import (to R, for instance) then insert a table name like this: #+BEGIN: columnview :hlines 1 :id global #+tblname: simpleDF | id | a | b | c | d | correct | |----+----------+-----------+--------+-----------+---------| | 1 | 1 | 2 | 3 | 4 | b | | 2 | Canberra | Melbourne | Sydney | Australia | a | #+END: then insert and execute the following R code block with C-c C-c: #+begin_src R :session *R* :var df=simpleDF :colnames yes head(df) #+end_src this gives #+results: | id | a | b | c | d | correct | |----+----------+-----------+--------+-----------+---------| | 1 | 1 | 2 | 3 | 4 | b | | 2 | Canberra | Melbourne | Sydney | Australia | a | The good news is that the data frame df is now stored in the active *R* session and is available to post-process however you like. All of this being said, if it were me, I would probably start with the exams package (in R) for the specific application of storing/writing multiple choice questions, though that YAML example looks really cool.
What is a good general purpose plain text data format like that used for Bibtex? [closed] Org Mode can do that. One way would be like this: #+COLUMNS: %id %a %b %c %d %correct * 1 + 1 :PROPERTIES: :id: 1 :a: 1 :b: 2 :c: 3 :d: 4
33,517
What is a good general purpose plain text data format like that used for Bibtex? [closed]
Here are a couple of additional ideas: Use R itself: exam = list(question1 = list( question='Here is the first question', answers = list('a' = 'Here is the first answer', 'b' = 'here is the second answer', 'c' = 'Here is the third answer' ) ) ) > exam$question1 > exam$question1$question > exam$question1$answers > exam$question1$answers$a Use reStructuredText, which is a lightweight markup language, similar to markdown, that can be parsed into a DOM (Python), e.g.: Here is the first question. * First answer. * Second answer. * Third answer. There is an rst2xml writer that converts the above to: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE document PUBLIC "+//IDN docutils.sourceforge.net//DTD Docutils Generic//EN//XML" "http://docutils.sourceforge.net/docs/ref/docutils.dtd"> <!-- Generated by Docutils 0.7 --> <document source="tmp.rst"> <paragraph>Here is the first question.</paragraph> <bullet_list bullet="*"> <list_item> <paragraph>First answer.</paragraph> </list_item> <list_item> <paragraph>Second answer.</paragraph> </list_item> <list_item> <paragraph>Third answer.</paragraph> </list_item> </bullet_list> </document> There is also an rst2latex writer, so your test can be easily formatted for printing, and you can deal with the data using python and the document object model. The advantage of this option is that rst is easy to read and write, unlike XML, but your data is still structured for use in R, Python, etc.
What is a good general purpose plain text data format like that used for Bibtex? [closed]
Here are a couple of additional ideas: Use R itself: exam = list(question1 = list( question='Here is the first question', answers = list('a' = 'Here is
What is a good general purpose plain text data format like that used for Bibtex? [closed] Here are a couple of additional ideas: Use R itself: exam = list(question1 = list( question='Here is the first question', answers = list('a' = 'Here is the first answer', 'b' = 'here is the second answer', 'c' = 'Here is the third answer' ) ) ) > exam$question1 > exam$question1$question > exam$question1$answers > exam$question1$answers$a Use reStructuredText, which is a lightweight markup language, similar to markdown, that can be parsed into a DOM (Python), e.g.: Here is the first question. * First answer. * Second answer. * Third answer. There is an rst2xml writer that converts the above to: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE document PUBLIC "+//IDN docutils.sourceforge.net//DTD Docutils Generic//EN//XML" "http://docutils.sourceforge.net/docs/ref/docutils.dtd"> <!-- Generated by Docutils 0.7 --> <document source="tmp.rst"> <paragraph>Here is the first question.</paragraph> <bullet_list bullet="*"> <list_item> <paragraph>First answer.</paragraph> </list_item> <list_item> <paragraph>Second answer.</paragraph> </list_item> <list_item> <paragraph>Third answer.</paragraph> </list_item> </bullet_list> </document> There is also an rst2latex writer, so your test can be easily formatted for printing, and you can deal with the data using python and the document object model. The advantage of this option is that rst is easy to read and write, unlike XML, but your data is still structured for use in R, Python, etc.
What is a good general purpose plain text data format like that used for Bibtex? [closed] Here are a couple of additional ideas: Use R itself: exam = list(question1 = list( question='Here is the first question', answers = list('a' = 'Here is
33,518
Can (some) linear regression model this (population) function accurately?
I wouldn't say the authors are wrong as such, but they weren't adequately careful with the wording. Often it's clear from context whether you mean simple or multiple linear regression, but here it wasn't. The authors should have written ...it will not be possible to produce an accurate estimate using simple linear regression. ...where simple linear regression means using a single predictor: only $X_1$. You are right that in this same paragraph, the authors had been discussing (multiple) linear regression in general: For example, linear regression assumes that there is a linear relationship between $Y$ and $X_1$, $X_2$, ..., $X_p$. There's no reason you couldn't define e.g. polynomials such as $X_2=X_1^2$ and $X_3=X_1^3$, in which case a linear model should indeed be able to fit that true $f$ reasonably well. Edit: Alternately, to @whuber's point, they could have said ...it will not be possible to produce an accurate estimate using a regression that is linear in $X$. Especially given that in Chapter 3 the authors note how a polynomial regression (nonlinear in $X$) is still a linear model (linear in the $\beta$s), it would have been helpful to be more explicit here. Their point here was not to say that the $f$ plotted in Figure 2.11 can't be well-approximated by a model linear in the $\beta$s---only that it can't be well-approximated by a model linear in $X$.
Can (some) linear regression model this (population) function accurately?
I wouldn't say the authors are wrong as such, but they weren't adequately careful with the wording. Often it's clear from context whether you mean simple or multiple linear regression, but here it was
Can (some) linear regression model this (population) function accurately? I wouldn't say the authors are wrong as such, but they weren't adequately careful with the wording. Often it's clear from context whether you mean simple or multiple linear regression, but here it wasn't. The authors should have written ...it will not be possible to produce an accurate estimate using simple linear regression. ...where simple linear regression means using a single predictor: only $X_1$. You are right that in this same paragraph, the authors had been discussing (multiple) linear regression in general: For example, linear regression assumes that there is a linear relationship between $Y$ and $X_1$, $X_2$, ..., $X_p$. There's no reason you couldn't define e.g. polynomials such as $X_2=X_1^2$ and $X_3=X_1^3$, in which case a linear model should indeed be able to fit that true $f$ reasonably well. Edit: Alternately, to @whuber's point, they could have said ...it will not be possible to produce an accurate estimate using a regression that is linear in $X$. Especially given that in Chapter 3 the authors note how a polynomial regression (nonlinear in $X$) is still a linear model (linear in the $\beta$s), it would have been helpful to be more explicit here. Their point here was not to say that the $f$ plotted in Figure 2.11 can't be well-approximated by a model linear in the $\beta$s---only that it can't be well-approximated by a model linear in $X$.
Can (some) linear regression model this (population) function accurately? I wouldn't say the authors are wrong as such, but they weren't adequately careful with the wording. Often it's clear from context whether you mean simple or multiple linear regression, but here it was
33,519
Can (some) linear regression model this (population) function accurately?
A straight line is always going to leave something to be desired. In that sense, the claim is correct. However, the true relationship looks cubic, which means that $\mathbb E[Y\vert X] = \beta_0 + \beta_1X + \beta_2X^2 + \beta_3X^3$ might be a reasonable model. Since this is linear in the parameters, the model is a linear regression, yet the fit should be reasonable. In that sense, the claim in incorrect. Once you get into function convergence theorems in mathematical analysis, you will see that linear combinations of polynomial terms can get arbitrarily close to an awful lot of functions.
Can (some) linear regression model this (population) function accurately?
A straight line is always going to leave something to be desired. In that sense, the claim is correct. However, the true relationship looks cubic, which means that $\mathbb E[Y\vert X] = \beta_0 + \be
Can (some) linear regression model this (population) function accurately? A straight line is always going to leave something to be desired. In that sense, the claim is correct. However, the true relationship looks cubic, which means that $\mathbb E[Y\vert X] = \beta_0 + \beta_1X + \beta_2X^2 + \beta_3X^3$ might be a reasonable model. Since this is linear in the parameters, the model is a linear regression, yet the fit should be reasonable. In that sense, the claim in incorrect. Once you get into function convergence theorems in mathematical analysis, you will see that linear combinations of polynomial terms can get arbitrarily close to an awful lot of functions.
Can (some) linear regression model this (population) function accurately? A straight line is always going to leave something to be desired. In that sense, the claim is correct. However, the true relationship looks cubic, which means that $\mathbb E[Y\vert X] = \beta_0 + \be
33,520
Can (some) linear regression model this (population) function accurately?
Can (some) linear regression model this (population) function accurately? Yes, it can with polynomial regression (see the plot below) which is a particular special case of linear regression. (Or from a particular viewpoint an extension of linear regression) But, at that point in the book linear regression is to be interpreted as following. (Emphasis is mine in the following quote) On the other hand, bias refers to the error that is introduced by approximating a real-life problem, which may be extremely complicated, by a much simpler model. For example, linear regression assumes that there is a linear relationship between Y and $X_1, X_2,\dots,X_p$. It is unlikely that any real-life problem truly has such a simple linear relationship, and so performing linear regression will undoubtedly result in some bias in the estimate of $f$. Sure, you can have that the regression includes vectors in the regressor matrix that are a non-linear function of some variable, like fitting a polynomial or using log-transformed variables. Later on in the book they are doing exactly this Non-linear Relationships As discussed previously, the linear regression model (3.19) assumes a linear relationship between the response and predictors. But in some cases, the true relationship between the response and the predictors may be non-linear. Here we present a very simple way to directly extend the linear model to accommodate non-linear relationships, using polynomial regression. So linear regression can express relationships between variables that are not a straight line. Below is an example of fitting a cubic with a copy of the data from that figure. But that is besides the point that is being made in the book, where they are explaining bias-variance trade off and the idea of using more flexible functions to estimate the distribution of some population. data = matrix(c(0.3, 26.0, 2.9, 24.7, 4.4, 22.1, 7.6, 18.6, 14.0, 16.8, 14.9, 15.5, 15.2, 13.8, 17.8, 11.8, 19.0, 12.6, 21.9, 10.5, 22.4, 12.6, 25.9, 12.6, 26.8, 13.8, 30.6, 12.8, 33.5, 11.1, 34.4, 11.9, 35.6, 11.6, 37.0, 12.2, 37.9, 11.3, 39.9, 11.5, 40.2, 12.9, 42.9, 11.5, 44.0, 11.0, 45.2, 11.3, 46.9, 14.0, 47.5, 13.5, 48.4, 13.9, 49.3, 11.3, 49.6, 13.5, 51.9, 13.5, 53.1, 12.6, 57.7, 14.1, 59.5, 11.4, 64.4, 14.9, 67.1, 13.2, 71.1, 13.4, 71.4, 13.8, 71.7, 12.7, 72.3, 11.9, 76.1, 11.8, 76.7, 9.5, 78.7, 9.6, 82.8, 7.3, 83.4, 6.6, 87.2, 3.8, 90.7, 0.2, 92.1, 1.0, 92.7, -0.3, 94.2, -2.4, 99.1, -8.5), ncol = 2, byrow = TRUE) colnames(data) = c("x","y") data = as.data.frame(data) plot(data$x,data$y) mod = lm(y ~ x + I(x^2) + I(x^3), data = data) lines(data$x, predict(mod)) summary(mod)$r.squared # returns 0.9715887 What is the definition of a linear model in James, Witten, Hastie, Tibshirani's book? In the subscript of Figure 3.8 on page 91 they write "the linear regression fit is shown in orange. The linear regression fit for a model that includes horsepower² is shown as a blue curve." So for these authors the 'linear regression' is just simple linear regression unless you specify it differently. You may like it or not, but this is just subjective. In discussing the underlying topics you should get around this. The topics themselves don't care how they are being called. Also, on page 289 the author's define polynomial regression explicitly as an extension of linear regression Polynomial regression extends the linear model by adding extra predictors, obtained by raising each of the original predictors to a power. For example, a cubic regression uses three variables, $X, X^2 , and X^3$, as predictors. This approach provides a simple way to provide a non-linear fit to data. In a certain sense polynomial regression is again a form of linear regression but with different/additional/more predictors. The original set of predictors has changed. Where does the confusion stem from? Strictly speaking linear regression is a linear model. It fits a linear function of the input variables to estimate the outcome variable. When you restrict linear regression to be defined as only a linear combination of the input variables, then linear regression can not model the cubic function accurately if $y$ is the output and $x$ is the input variable. Standard linear regression, which is uses a linear combination of the regressor variables, can not express non-linear relationships between the output variable and the regressor variables. However, by adding non-linear transformations of the input/regressor variables as additional input/regressor variables we can use linear regression to model relationships between two variables that are non-linear. So we can have linear regression to express some non-linear relationships. But to do this we need additional input variables $x^2$ and $x^3$. This is different from plain vanilla linear regression and the authors consider this as an extension. Linear regression can only model linear relationships between the response variable and the regressor variables. Polynomial regression is when we add additional regressors such that we are able to express a non-linear relationship between a response variable and an input variable. This polynomial regression is from a certain perspective a linear regression as well but only in terms of the new set of regressor variables which include the non-linear transformations of the original set of regressor variables. Polynomial regression is expressing a non-linear relationship between the response $𝑦$ and regressor variable $𝑥$, but it is expressing a linear relationship between the response $𝑦$ and regressor variables $𝑥,𝑥^2,𝑥^3,\dots,𝑥^𝑝$. If your only regressor variable is $𝑥$ then you can not use linear regression to express the non-linear relationship.
Can (some) linear regression model this (population) function accurately?
Can (some) linear regression model this (population) function accurately? Yes, it can with polynomial regression (see the plot below) which is a particular special case of linear regression. (Or from
Can (some) linear regression model this (population) function accurately? Can (some) linear regression model this (population) function accurately? Yes, it can with polynomial regression (see the plot below) which is a particular special case of linear regression. (Or from a particular viewpoint an extension of linear regression) But, at that point in the book linear regression is to be interpreted as following. (Emphasis is mine in the following quote) On the other hand, bias refers to the error that is introduced by approximating a real-life problem, which may be extremely complicated, by a much simpler model. For example, linear regression assumes that there is a linear relationship between Y and $X_1, X_2,\dots,X_p$. It is unlikely that any real-life problem truly has such a simple linear relationship, and so performing linear regression will undoubtedly result in some bias in the estimate of $f$. Sure, you can have that the regression includes vectors in the regressor matrix that are a non-linear function of some variable, like fitting a polynomial or using log-transformed variables. Later on in the book they are doing exactly this Non-linear Relationships As discussed previously, the linear regression model (3.19) assumes a linear relationship between the response and predictors. But in some cases, the true relationship between the response and the predictors may be non-linear. Here we present a very simple way to directly extend the linear model to accommodate non-linear relationships, using polynomial regression. So linear regression can express relationships between variables that are not a straight line. Below is an example of fitting a cubic with a copy of the data from that figure. But that is besides the point that is being made in the book, where they are explaining bias-variance trade off and the idea of using more flexible functions to estimate the distribution of some population. data = matrix(c(0.3, 26.0, 2.9, 24.7, 4.4, 22.1, 7.6, 18.6, 14.0, 16.8, 14.9, 15.5, 15.2, 13.8, 17.8, 11.8, 19.0, 12.6, 21.9, 10.5, 22.4, 12.6, 25.9, 12.6, 26.8, 13.8, 30.6, 12.8, 33.5, 11.1, 34.4, 11.9, 35.6, 11.6, 37.0, 12.2, 37.9, 11.3, 39.9, 11.5, 40.2, 12.9, 42.9, 11.5, 44.0, 11.0, 45.2, 11.3, 46.9, 14.0, 47.5, 13.5, 48.4, 13.9, 49.3, 11.3, 49.6, 13.5, 51.9, 13.5, 53.1, 12.6, 57.7, 14.1, 59.5, 11.4, 64.4, 14.9, 67.1, 13.2, 71.1, 13.4, 71.4, 13.8, 71.7, 12.7, 72.3, 11.9, 76.1, 11.8, 76.7, 9.5, 78.7, 9.6, 82.8, 7.3, 83.4, 6.6, 87.2, 3.8, 90.7, 0.2, 92.1, 1.0, 92.7, -0.3, 94.2, -2.4, 99.1, -8.5), ncol = 2, byrow = TRUE) colnames(data) = c("x","y") data = as.data.frame(data) plot(data$x,data$y) mod = lm(y ~ x + I(x^2) + I(x^3), data = data) lines(data$x, predict(mod)) summary(mod)$r.squared # returns 0.9715887 What is the definition of a linear model in James, Witten, Hastie, Tibshirani's book? In the subscript of Figure 3.8 on page 91 they write "the linear regression fit is shown in orange. The linear regression fit for a model that includes horsepower² is shown as a blue curve." So for these authors the 'linear regression' is just simple linear regression unless you specify it differently. You may like it or not, but this is just subjective. In discussing the underlying topics you should get around this. The topics themselves don't care how they are being called. Also, on page 289 the author's define polynomial regression explicitly as an extension of linear regression Polynomial regression extends the linear model by adding extra predictors, obtained by raising each of the original predictors to a power. For example, a cubic regression uses three variables, $X, X^2 , and X^3$, as predictors. This approach provides a simple way to provide a non-linear fit to data. In a certain sense polynomial regression is again a form of linear regression but with different/additional/more predictors. The original set of predictors has changed. Where does the confusion stem from? Strictly speaking linear regression is a linear model. It fits a linear function of the input variables to estimate the outcome variable. When you restrict linear regression to be defined as only a linear combination of the input variables, then linear regression can not model the cubic function accurately if $y$ is the output and $x$ is the input variable. Standard linear regression, which is uses a linear combination of the regressor variables, can not express non-linear relationships between the output variable and the regressor variables. However, by adding non-linear transformations of the input/regressor variables as additional input/regressor variables we can use linear regression to model relationships between two variables that are non-linear. So we can have linear regression to express some non-linear relationships. But to do this we need additional input variables $x^2$ and $x^3$. This is different from plain vanilla linear regression and the authors consider this as an extension. Linear regression can only model linear relationships between the response variable and the regressor variables. Polynomial regression is when we add additional regressors such that we are able to express a non-linear relationship between a response variable and an input variable. This polynomial regression is from a certain perspective a linear regression as well but only in terms of the new set of regressor variables which include the non-linear transformations of the original set of regressor variables. Polynomial regression is expressing a non-linear relationship between the response $𝑦$ and regressor variable $𝑥$, but it is expressing a linear relationship between the response $𝑦$ and regressor variables $𝑥,𝑥^2,𝑥^3,\dots,𝑥^𝑝$. If your only regressor variable is $𝑥$ then you can not use linear regression to express the non-linear relationship.
Can (some) linear regression model this (population) function accurately? Can (some) linear regression model this (population) function accurately? Yes, it can with polynomial regression (see the plot below) which is a particular special case of linear regression. (Or from
33,521
Is the method of mean substitution for replacing missing data out of date?
Barring the fact that it's not necessary to shoot mosquitoes with a cannon (i.e. if you have one missing value in a million data points, just drop it), using the mean could be suboptimal to say the least: the result can be biased, and you should at least correct the result for the uncertainty. There are some other options, but the one easiest to explain is multiple imputation. The concept is simple: based upon a model for your data itself (e.g. obtained from the complete cases, though other options are available, like MICE), draw values from the associated distribution to 'complete' your dataset. Then in this completed dataset you don't have anymore missing data, and you can run your analysis of interest. If you did this only once (in fact, replacing the missing values with the mean is a very contorted form of this), it would be called single imputation, and there is no reason why it would perform better than mean replacement. However: the trick is to do this repeatedly (hence Multiple Imputation), and each time do your analysis on each completed (=imputed) dataset. The result is typically a set of parameter estimates or similar for each completed dataset. Under relatively loose conditions, it is OK to average your parameter estimates over all these imputed datasets. The advantage is that there also exists a simple formula to adjust the standard error for the uncertainty caused by the missing data. If you want to know more, you probably want to read Little and Rubin's 'Statistical Analysis with Missing Data'. This also holds other methods (EM,...) and more explanation on how/why/when they work.
Is the method of mean substitution for replacing missing data out of date?
Barring the fact that it's not necessary to shoot mosquitoes with a cannon (i.e. if you have one missing value in a million data points, just drop it), using the mean could be suboptimal to say the le
Is the method of mean substitution for replacing missing data out of date? Barring the fact that it's not necessary to shoot mosquitoes with a cannon (i.e. if you have one missing value in a million data points, just drop it), using the mean could be suboptimal to say the least: the result can be biased, and you should at least correct the result for the uncertainty. There are some other options, but the one easiest to explain is multiple imputation. The concept is simple: based upon a model for your data itself (e.g. obtained from the complete cases, though other options are available, like MICE), draw values from the associated distribution to 'complete' your dataset. Then in this completed dataset you don't have anymore missing data, and you can run your analysis of interest. If you did this only once (in fact, replacing the missing values with the mean is a very contorted form of this), it would be called single imputation, and there is no reason why it would perform better than mean replacement. However: the trick is to do this repeatedly (hence Multiple Imputation), and each time do your analysis on each completed (=imputed) dataset. The result is typically a set of parameter estimates or similar for each completed dataset. Under relatively loose conditions, it is OK to average your parameter estimates over all these imputed datasets. The advantage is that there also exists a simple formula to adjust the standard error for the uncertainty caused by the missing data. If you want to know more, you probably want to read Little and Rubin's 'Statistical Analysis with Missing Data'. This also holds other methods (EM,...) and more explanation on how/why/when they work.
Is the method of mean substitution for replacing missing data out of date? Barring the fact that it's not necessary to shoot mosquitoes with a cannon (i.e. if you have one missing value in a million data points, just drop it), using the mean could be suboptimal to say the le
33,522
Is the method of mean substitution for replacing missing data out of date?
You did not tell us very much about the nature of your missing data. Did you check for MCAR (Missing Completely at Random)? Given that you cannot assume MCAR, mean substitution can lead to biased estimators. As a non-mathematical starting point, I can recommend the following two references: Graham, Hohn W. (2009): Missing Data Analysis: Making It Work in the Real World. Allison, Paul (2002): Missing data. (see section "Imputation", p. 11)
Is the method of mean substitution for replacing missing data out of date?
You did not tell us very much about the nature of your missing data. Did you check for MCAR (Missing Completely at Random)? Given that you cannot assume MCAR, mean substitution can lead to biased esti
Is the method of mean substitution for replacing missing data out of date? You did not tell us very much about the nature of your missing data. Did you check for MCAR (Missing Completely at Random)? Given that you cannot assume MCAR, mean substitution can lead to biased estimators. As a non-mathematical starting point, I can recommend the following two references: Graham, Hohn W. (2009): Missing Data Analysis: Making It Work in the Real World. Allison, Paul (2002): Missing data. (see section "Imputation", p. 11)
Is the method of mean substitution for replacing missing data out of date? You did not tell us very much about the nature of your missing data. Did you check for MCAR (Missing Completely at Random)? Given that you cannot assume MCAR, mean substitution can lead to biased esti
33,523
Is the method of mean substitution for replacing missing data out of date?
If your missing values are randomly distributed, or your sample size is small, you might be better off just using the mean. I would first split the data into two parts: 1 with the missing values and the other without and then test for the difference in means of some key variables between the two samples. If there is no difference, you have some support for substituting the mean, or just deleting the observations entirely. -Ralph Winters
Is the method of mean substitution for replacing missing data out of date?
If your missing values are randomly distributed, or your sample size is small, you might be better off just using the mean. I would first split the data into two parts: 1 with the missing values and
Is the method of mean substitution for replacing missing data out of date? If your missing values are randomly distributed, or your sample size is small, you might be better off just using the mean. I would first split the data into two parts: 1 with the missing values and the other without and then test for the difference in means of some key variables between the two samples. If there is no difference, you have some support for substituting the mean, or just deleting the observations entirely. -Ralph Winters
Is the method of mean substitution for replacing missing data out of date? If your missing values are randomly distributed, or your sample size is small, you might be better off just using the mean. I would first split the data into two parts: 1 with the missing values and
33,524
Is the method of mean substitution for replacing missing data out of date?
Missing data is one big issue everywhere. I wish you'd answer the following question first. 1) what %age of the data is missing ? -- if its more than 10% of the data you'd not risk imputing it with mean. Because imputing such missing with mean is equivalent to telling the LR box that look ..this variable has mean most of the places( so draw some conclusion) and you dont want LR box to draw conclusions upon your suggestions.do you ?? Now, the least you can do if you dont want much is you can try to relate this variables available values with different predictors value or use a business sense where ever possible..example..if I have a missing for marriage_ind , one of the ways could be seeing the median age of the people married, (lets say it comes out to be 29), I can assume that generally people(in India) get married by 30 and 29 suggests so. PROC MI also does thing internally for you but in a far more sofisticated way..so my 2 cents..see atleast 4-5 variables which are linked to your missings and try to form a correlation..This can be better than mean.
Is the method of mean substitution for replacing missing data out of date?
Missing data is one big issue everywhere. I wish you'd answer the following question first. 1) what %age of the data is missing ? -- if its more than 10% of the data you'd not risk imputing it with me
Is the method of mean substitution for replacing missing data out of date? Missing data is one big issue everywhere. I wish you'd answer the following question first. 1) what %age of the data is missing ? -- if its more than 10% of the data you'd not risk imputing it with mean. Because imputing such missing with mean is equivalent to telling the LR box that look ..this variable has mean most of the places( so draw some conclusion) and you dont want LR box to draw conclusions upon your suggestions.do you ?? Now, the least you can do if you dont want much is you can try to relate this variables available values with different predictors value or use a business sense where ever possible..example..if I have a missing for marriage_ind , one of the ways could be seeing the median age of the people married, (lets say it comes out to be 29), I can assume that generally people(in India) get married by 30 and 29 suggests so. PROC MI also does thing internally for you but in a far more sofisticated way..so my 2 cents..see atleast 4-5 variables which are linked to your missings and try to form a correlation..This can be better than mean.
Is the method of mean substitution for replacing missing data out of date? Missing data is one big issue everywhere. I wish you'd answer the following question first. 1) what %age of the data is missing ? -- if its more than 10% of the data you'd not risk imputing it with me
33,525
How do I group a list of numeric values into ranges?
Why group them? Instead, how about estimate the probability density function (PDF) of the distributions from which the data arise? Here's an R-based example: set.seed(123) dat <- c(sample(2000000, 500), rnorm(100, 1000000, 1000), rnorm(150, 1500000, 100),rnorm(150, 500000, 10), rnorm(180, 10000, 10), rnorm(10, 1000, 5), 1:10) dens <- density(dat) plot(dens) If the data are strictly bounded (0, 2,000,000) then the kernel density estimate is perhaps not best suited. You could fudge things by asking it to only evaluate the density between the bounds: dens2 <- density(dat, from = 0, to = 2000000) plot(dens2) Alternatively there is the histogram - a coarse version of the kernel density. What you specifically talk about is binning your data. There are lots of rules/approaches to selecting equal-width bins (i.e. the number of bins) from the data. In R the default is Sturges rule, but it also includes the Freedman-Diaconis rule and Scott's rule. There are others as well - see the Wikipedia page on histograms. hist(dat) If you are not interested in the kernel density plot or the histogram per se, rather just the binned data, then you can compute the number of bins using the nclass.X family of functions where X is one of Sturges, scott or FD. And then use cut() to bin your data: cut.dat <- cut(dat, breaks = nclass.FD(dat), include.lowest = TRUE) table(cut.dat) which gives: > cut.dat [-2e+03,2.21e+05] (2.21e+05,4.43e+05] (4.43e+05,6.65e+05] (6.65e+05,8.88e+05] 247 60 215 61 (8.88e+05,1.11e+06] (1.11e+06,1.33e+06] (1.33e+06,1.56e+06] (1.56e+06,1.78e+06] 153 51 205 50 (1.78e+06,2e+06] 58 in R. However, binning is fraught with problems, most notably; How do you know that your choice of bins hasn't influenced the resulting impression you get of the way the data are distributed?
How do I group a list of numeric values into ranges?
Why group them? Instead, how about estimate the probability density function (PDF) of the distributions from which the data arise? Here's an R-based example: set.seed(123) dat <- c(sample(2000000, 500
How do I group a list of numeric values into ranges? Why group them? Instead, how about estimate the probability density function (PDF) of the distributions from which the data arise? Here's an R-based example: set.seed(123) dat <- c(sample(2000000, 500), rnorm(100, 1000000, 1000), rnorm(150, 1500000, 100),rnorm(150, 500000, 10), rnorm(180, 10000, 10), rnorm(10, 1000, 5), 1:10) dens <- density(dat) plot(dens) If the data are strictly bounded (0, 2,000,000) then the kernel density estimate is perhaps not best suited. You could fudge things by asking it to only evaluate the density between the bounds: dens2 <- density(dat, from = 0, to = 2000000) plot(dens2) Alternatively there is the histogram - a coarse version of the kernel density. What you specifically talk about is binning your data. There are lots of rules/approaches to selecting equal-width bins (i.e. the number of bins) from the data. In R the default is Sturges rule, but it also includes the Freedman-Diaconis rule and Scott's rule. There are others as well - see the Wikipedia page on histograms. hist(dat) If you are not interested in the kernel density plot or the histogram per se, rather just the binned data, then you can compute the number of bins using the nclass.X family of functions where X is one of Sturges, scott or FD. And then use cut() to bin your data: cut.dat <- cut(dat, breaks = nclass.FD(dat), include.lowest = TRUE) table(cut.dat) which gives: > cut.dat [-2e+03,2.21e+05] (2.21e+05,4.43e+05] (4.43e+05,6.65e+05] (6.65e+05,8.88e+05] 247 60 215 61 (8.88e+05,1.11e+06] (1.11e+06,1.33e+06] (1.33e+06,1.56e+06] (1.56e+06,1.78e+06] 153 51 205 50 (1.78e+06,2e+06] 58 in R. However, binning is fraught with problems, most notably; How do you know that your choice of bins hasn't influenced the resulting impression you get of the way the data are distributed?
How do I group a list of numeric values into ranges? Why group them? Instead, how about estimate the probability density function (PDF) of the distributions from which the data arise? Here's an R-based example: set.seed(123) dat <- c(sample(2000000, 500
33,526
How do I group a list of numeric values into ranges?
I'll assume that you've already determined the number of categories you'll use. Let's say you want to use 20 categories. Then they will be: Category 1: [0 - 100,000) Category 2: [100,000 - 200,000) Category 3: [200,000 - 300,000) ... Category 19: [1,800,000 - 1,900,000) Category 20: [1,900,000 - 2,000,000] Note that the label of each category can be defined as FLOOR (x / category_size) + 1 This is trivial to define as a computed column in SQL or as a formula in Excel. Note that the last category is infinitesimally larger than the others, since it is closed on both sides. If you happen to get a value of exactly 2,000,000 you might erroneously classify it as falling into category 21, so you have to treat this exception with an ugly "IF" (in Excel) or "CASE" (in SQL).
How do I group a list of numeric values into ranges?
I'll assume that you've already determined the number of categories you'll use. Let's say you want to use 20 categories. Then they will be: Category 1: [0 - 100,000) Category 2: [100,000 - 200,000) C
How do I group a list of numeric values into ranges? I'll assume that you've already determined the number of categories you'll use. Let's say you want to use 20 categories. Then they will be: Category 1: [0 - 100,000) Category 2: [100,000 - 200,000) Category 3: [200,000 - 300,000) ... Category 19: [1,800,000 - 1,900,000) Category 20: [1,900,000 - 2,000,000] Note that the label of each category can be defined as FLOOR (x / category_size) + 1 This is trivial to define as a computed column in SQL or as a formula in Excel. Note that the last category is infinitesimally larger than the others, since it is closed on both sides. If you happen to get a value of exactly 2,000,000 you might erroneously classify it as falling into category 21, so you have to treat this exception with an ugly "IF" (in Excel) or "CASE" (in SQL).
How do I group a list of numeric values into ranges? I'll assume that you've already determined the number of categories you'll use. Let's say you want to use 20 categories. Then they will be: Category 1: [0 - 100,000) Category 2: [100,000 - 200,000) C
33,527
How do I group a list of numeric values into ranges?
Another option using Excel that gives you a fair amount of flexibility over the number & size of bins is the =frequency(data_array, bins_array) function. It is an array function that expects two arguments. The first argument is your data, the second is your bins that you define. Let's assume your data is in cells A1 - A1000 and create bins in cells B1 - B20. You would want to highlight cells C1 - C21 and then type something like =FREQUENCY(A1:A100, B1:B21). Unlike normal functions, array functions must be entered with the key combination SHIFT + CTRL + ENTER. You should see the counts fill down for all bins, if not - you most likely only hit enter and the first cell is calculated. There are plenty of good tutorials online explaining this in more detail, here's a decent one.
How do I group a list of numeric values into ranges?
Another option using Excel that gives you a fair amount of flexibility over the number & size of bins is the =frequency(data_array, bins_array) function. It is an array function that expects two argum
How do I group a list of numeric values into ranges? Another option using Excel that gives you a fair amount of flexibility over the number & size of bins is the =frequency(data_array, bins_array) function. It is an array function that expects two arguments. The first argument is your data, the second is your bins that you define. Let's assume your data is in cells A1 - A1000 and create bins in cells B1 - B20. You would want to highlight cells C1 - C21 and then type something like =FREQUENCY(A1:A100, B1:B21). Unlike normal functions, array functions must be entered with the key combination SHIFT + CTRL + ENTER. You should see the counts fill down for all bins, if not - you most likely only hit enter and the first cell is calculated. There are plenty of good tutorials online explaining this in more detail, here's a decent one.
How do I group a list of numeric values into ranges? Another option using Excel that gives you a fair amount of flexibility over the number & size of bins is the =frequency(data_array, bins_array) function. It is an array function that expects two argum
33,528
How do I group a list of numeric values into ranges?
You have requested an Excel or SQL solution. The easiest way in Excel is to use its "Analysis" add-in to create a histogram. It will automatically create the bins (ranges of values) but, optionally, accepts a list of bin cutpoints as input and uses them. The output includes a parallel list of bin counts. This is especially handy for irregular-width bins. This is a one-off calculation: if the data change or the cutpoints change, you have to go through the entire dialog again. A more flexible option is to use COUNTIF to count all values less than or equal to any given bin cutpoint. The first differences of such an array give the bin counts. Here is a working example. The data are in a column named "Simulation_Z" (which in this particular case is defined to be an entire column, such as $C:$C). The formulae shown below are copied from columns L2:N10 of a sheet in the same workbook. They were created by copying the first one downward (but notice the special formula for the first count in N3). Cut Count up Count -3.0 =COUNTIF(Simulation_Z, "<=" & L3) =M3 -2.0 =COUNTIF(Simulation_Z, "<=" & L4) =M4-M3 -1.0 =COUNTIF(Simulation_Z, "<=" & L5) =M5-M4 0.0 =COUNTIF(Simulation_Z, "<=" & L6) =M6-M5 1.0 =COUNTIF(Simulation_Z, "<=" & L7) =M7-M6 2.0 =COUNTIF(Simulation_Z, "<=" & L8) =M8-M7 3.0 =COUNTIF(Simulation_Z, "<=" & L9) =M9-M8 =MAX(Simulation_Z) =COUNTIF(Simulation_Z, "<=" & L10) =M10-M9 Column L ("Cut") stipulates the upper limits of each bin. This procedure simultaneously defines the bins and computes their counts, which are then available for further testing (e.g., $\chi\text{-squared}$) or plotting.
How do I group a list of numeric values into ranges?
You have requested an Excel or SQL solution. The easiest way in Excel is to use its "Analysis" add-in to create a histogram. It will automatically create the bins (ranges of values) but, optionally,
How do I group a list of numeric values into ranges? You have requested an Excel or SQL solution. The easiest way in Excel is to use its "Analysis" add-in to create a histogram. It will automatically create the bins (ranges of values) but, optionally, accepts a list of bin cutpoints as input and uses them. The output includes a parallel list of bin counts. This is especially handy for irregular-width bins. This is a one-off calculation: if the data change or the cutpoints change, you have to go through the entire dialog again. A more flexible option is to use COUNTIF to count all values less than or equal to any given bin cutpoint. The first differences of such an array give the bin counts. Here is a working example. The data are in a column named "Simulation_Z" (which in this particular case is defined to be an entire column, such as $C:$C). The formulae shown below are copied from columns L2:N10 of a sheet in the same workbook. They were created by copying the first one downward (but notice the special formula for the first count in N3). Cut Count up Count -3.0 =COUNTIF(Simulation_Z, "<=" & L3) =M3 -2.0 =COUNTIF(Simulation_Z, "<=" & L4) =M4-M3 -1.0 =COUNTIF(Simulation_Z, "<=" & L5) =M5-M4 0.0 =COUNTIF(Simulation_Z, "<=" & L6) =M6-M5 1.0 =COUNTIF(Simulation_Z, "<=" & L7) =M7-M6 2.0 =COUNTIF(Simulation_Z, "<=" & L8) =M8-M7 3.0 =COUNTIF(Simulation_Z, "<=" & L9) =M9-M8 =MAX(Simulation_Z) =COUNTIF(Simulation_Z, "<=" & L10) =M10-M9 Column L ("Cut") stipulates the upper limits of each bin. This procedure simultaneously defines the bins and computes their counts, which are then available for further testing (e.g., $\chi\text{-squared}$) or plotting.
How do I group a list of numeric values into ranges? You have requested an Excel or SQL solution. The easiest way in Excel is to use its "Analysis" add-in to create a histogram. It will automatically create the bins (ranges of values) but, optionally,
33,529
How do I group a list of numeric values into ranges?
In Excel, a simple way to group numeric data into bins is via the Pivot Table. Pull the numeric variable into the "row labels". Now right-click on any of the values in this right column and choose "Group". You can set the min and max of the overall range and the bin size (equal bins widths for all data).
How do I group a list of numeric values into ranges?
In Excel, a simple way to group numeric data into bins is via the Pivot Table. Pull the numeric variable into the "row labels". Now right-click on any of the values in this right column and choose "Gr
How do I group a list of numeric values into ranges? In Excel, a simple way to group numeric data into bins is via the Pivot Table. Pull the numeric variable into the "row labels". Now right-click on any of the values in this right column and choose "Group". You can set the min and max of the overall range and the bin size (equal bins widths for all data).
How do I group a list of numeric values into ranges? In Excel, a simple way to group numeric data into bins is via the Pivot Table. Pull the numeric variable into the "row labels". Now right-click on any of the values in this right column and choose "Gr
33,530
How do I group a list of numeric values into ranges?
Although the FLOOR answer is probably nicer, you can do this with a vlookup. The first column of the lookup table (shown below) is the lower bound of each of your bins. Then you enter a formula to make the labels in the second column (formula shown, and result of the formula in the third column -- obviously you'd only have two columns.) Note the last two rows of the table are wonky -- the second last has a different formula because you want it to be the unbounded "greater than" case (unless you don't want that, then change the formula - you can set this up however you like). You would enter this formula (assuming the values you want to bin are in Col A, and the lookup table is in cols F:G somewhere. Note the TRUE parameter, so vlookup doesn't need to find an exact match. =VLOOKUP(A2,$F$2:$G$24,2,TRUE) This is what the lookup table would look like: Floor Formula Result of Formula (label) 0 =F2 & " - " &F3-1 0 - 49999 50000 =F3 & " - " &F4-1 50000 - 99999 100000 =F4 & " - " &F5-1 100000 - 149999 150000 =F5 & " - " &F6-1 150000 - 199999 200000 =F6 & " - " &F7-1 200000 - 249999 250000 =F7 & " - " &F8-1 250000 - 299999 300000 =F8 & " - " &F9-1 300000 - 349999 .... 1100000 =" >= " &F25 >= 1100000
How do I group a list of numeric values into ranges?
Although the FLOOR answer is probably nicer, you can do this with a vlookup. The first column of the lookup table (shown below) is the lower bound of each of your bins. Then you enter a formula to mak
How do I group a list of numeric values into ranges? Although the FLOOR answer is probably nicer, you can do this with a vlookup. The first column of the lookup table (shown below) is the lower bound of each of your bins. Then you enter a formula to make the labels in the second column (formula shown, and result of the formula in the third column -- obviously you'd only have two columns.) Note the last two rows of the table are wonky -- the second last has a different formula because you want it to be the unbounded "greater than" case (unless you don't want that, then change the formula - you can set this up however you like). You would enter this formula (assuming the values you want to bin are in Col A, and the lookup table is in cols F:G somewhere. Note the TRUE parameter, so vlookup doesn't need to find an exact match. =VLOOKUP(A2,$F$2:$G$24,2,TRUE) This is what the lookup table would look like: Floor Formula Result of Formula (label) 0 =F2 & " - " &F3-1 0 - 49999 50000 =F3 & " - " &F4-1 50000 - 99999 100000 =F4 & " - " &F5-1 100000 - 149999 150000 =F5 & " - " &F6-1 150000 - 199999 200000 =F6 & " - " &F7-1 200000 - 249999 250000 =F7 & " - " &F8-1 250000 - 299999 300000 =F8 & " - " &F9-1 300000 - 349999 .... 1100000 =" >= " &F25 >= 1100000
How do I group a list of numeric values into ranges? Although the FLOOR answer is probably nicer, you can do this with a vlookup. The first column of the lookup table (shown below) is the lower bound of each of your bins. Then you enter a formula to mak
33,531
How do I group a list of numeric values into ranges?
To answer this for SQL, you really need to have a database that understands a window function (part of SQL:2003), such as MS SQL Server or PostgreSQL. To group val from table data into, say, 13 equal-width bins, use the ntile window function: SELECT val, ntile(13) OVER (ORDER BY val) FROM data; val | ntile ------------------+------- 8908.96283090115 | 1 9090.72533249855 | 1 9620.1803535223 | 1 11068.768799305 | 1 ... 1994248.56621772 | 13 1994786.21594608 | 13 1995945.97052783 | 13 1997640.62557369 | 13 (1000 rows)
How do I group a list of numeric values into ranges?
To answer this for SQL, you really need to have a database that understands a window function (part of SQL:2003), such as MS SQL Server or PostgreSQL. To group val from table data into, say, 13 equal-
How do I group a list of numeric values into ranges? To answer this for SQL, you really need to have a database that understands a window function (part of SQL:2003), such as MS SQL Server or PostgreSQL. To group val from table data into, say, 13 equal-width bins, use the ntile window function: SELECT val, ntile(13) OVER (ORDER BY val) FROM data; val | ntile ------------------+------- 8908.96283090115 | 1 9090.72533249855 | 1 9620.1803535223 | 1 11068.768799305 | 1 ... 1994248.56621772 | 13 1994786.21594608 | 13 1995945.97052783 | 13 1997640.62557369 | 13 (1000 rows)
How do I group a list of numeric values into ranges? To answer this for SQL, you really need to have a database that understands a window function (part of SQL:2003), such as MS SQL Server or PostgreSQL. To group val from table data into, say, 13 equal-
33,532
How do I group a list of numeric values into ranges?
that is simply to use this formula in excel: Ceiling(Cell(i,j),1000)/1000 Then you have group of 1000: 1, 2, 3, ...
How do I group a list of numeric values into ranges?
that is simply to use this formula in excel: Ceiling(Cell(i,j),1000)/1000 Then you have group of 1000: 1, 2, 3, ...
How do I group a list of numeric values into ranges? that is simply to use this formula in excel: Ceiling(Cell(i,j),1000)/1000 Then you have group of 1000: 1, 2, 3, ...
How do I group a list of numeric values into ranges? that is simply to use this formula in excel: Ceiling(Cell(i,j),1000)/1000 Then you have group of 1000: 1, 2, 3, ...
33,533
Would a machine learning classifier algorithm be able to determine whether a number is odd or even?
As is often the case, the issue is one of defining your features. If you use the digits of the binary expansion of the number as features, your classifiers should have no problem picking up the fact that only one feature perfectly separates the target classes. Here I construct an example where the training data is 500 integers randomly selected from $\{1,2, \dots, 1000\}$ and use linear regression to classify: y <- sample(1:1000, 500, replace=FALSE) x <- t(matrix(as.integer(intToBits(y)), 32)) x <- x[, 1:10] # as the numbers < 1001 don't use any higher bits tgt <- y %% 2 train_data <- data.frame(cbind(tgt,x)) m1 <- lm(tgt~., data=train_data) y_pred <- sample(1:1000, 10, replace=FALSE) x_pred <- t(matrix(as.integer(intToBits(y_pred)), 32))[, 1:10] test_data <- data.frame(x_pred) test_results <- data.frame(actual = y_pred, odd_even = predict(m1, test_data)) # Clean up the results, as floating point math doesn't always give exact integers test_results$cleaned_odd_even <- ifelse(test_results$odd_even < 1e-10, 0, 1) and the results: > test_results actual odd_even cleaned_odd_even 1 727 1.000000e+00 1 2 544 -1.311871e-15 0 3 689 1.000000e+00 1 4 647 1.000000e+00 1 5 444 -1.116987e-15 0 6 89 1.000000e+00 1 7 168 -1.229638e-15 0 8 770 -1.401580e-15 0 9 870 -1.107620e-15 0 10 31 1.000000e+00 1 This would allow you to classify any non-negative integer based on its lowest order 10 bits (or however many bits we include). The algorithm figured out that only the lowest order bit mattered.
Would a machine learning classifier algorithm be able to determine whether a number is odd or even?
As is often the case, the issue is one of defining your features. If you use the digits of the binary expansion of the number as features, your classifiers should have no problem picking up the fact t
Would a machine learning classifier algorithm be able to determine whether a number is odd or even? As is often the case, the issue is one of defining your features. If you use the digits of the binary expansion of the number as features, your classifiers should have no problem picking up the fact that only one feature perfectly separates the target classes. Here I construct an example where the training data is 500 integers randomly selected from $\{1,2, \dots, 1000\}$ and use linear regression to classify: y <- sample(1:1000, 500, replace=FALSE) x <- t(matrix(as.integer(intToBits(y)), 32)) x <- x[, 1:10] # as the numbers < 1001 don't use any higher bits tgt <- y %% 2 train_data <- data.frame(cbind(tgt,x)) m1 <- lm(tgt~., data=train_data) y_pred <- sample(1:1000, 10, replace=FALSE) x_pred <- t(matrix(as.integer(intToBits(y_pred)), 32))[, 1:10] test_data <- data.frame(x_pred) test_results <- data.frame(actual = y_pred, odd_even = predict(m1, test_data)) # Clean up the results, as floating point math doesn't always give exact integers test_results$cleaned_odd_even <- ifelse(test_results$odd_even < 1e-10, 0, 1) and the results: > test_results actual odd_even cleaned_odd_even 1 727 1.000000e+00 1 2 544 -1.311871e-15 0 3 689 1.000000e+00 1 4 647 1.000000e+00 1 5 444 -1.116987e-15 0 6 89 1.000000e+00 1 7 168 -1.229638e-15 0 8 770 -1.401580e-15 0 9 870 -1.107620e-15 0 10 31 1.000000e+00 1 This would allow you to classify any non-negative integer based on its lowest order 10 bits (or however many bits we include). The algorithm figured out that only the lowest order bit mattered.
Would a machine learning classifier algorithm be able to determine whether a number is odd or even? As is often the case, the issue is one of defining your features. If you use the digits of the binary expansion of the number as features, your classifiers should have no problem picking up the fact t
33,534
Would a machine learning classifier algorithm be able to determine whether a number is odd or even?
This is a fun little problem. @jbowman notes "As is often the case, the issue is one of defining your features". One way to engineer a feature for this problem is to look at the last digit of the number. Here is a simple little script in sklearn import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.preprocessing import OneHotEncoder, FunctionTransformer @np.vectorize def get_last_digit_of_float(x): str_x = str(x) if len(str_x) == 1: return int(str_x) else: return int(str_x[-1]) last_digit_transformer = FunctionTransformer(get_last_digit_of_float) def main(): train_set = np.arange(100).reshape(-1, 1) y_train = np.arange(100) % 2 test_set = np.arange(100, 200).reshape(-1, 1) y_test = np.arange(100, 200) % 2 model = make_pipeline( last_digit_transformer, OneHotEncoder(categories='auto', sparse=False, handle_unknown='error', drop='first'), LogisticRegression(solver='lbfgs', multi_class='multinomial') ) model.fit(train_set, y_train) print('Test Set Accuracy:', model.score(test_set, y_test)) if __name__ == '__main__': main() This returns a test set accuracy of 1.0. The trick here is to turn the last digit of the number into a feature and then one hot encode the number. This works because any number which ends in an even number is also even. The result is a design matrix with 9 columns (numbers 1 through 9, 0 is not needed in this case since it is absorbed by the intercept in Logistic regression). As always, a clever feature engineering approach is all that is needed.
Would a machine learning classifier algorithm be able to determine whether a number is odd or even?
This is a fun little problem. @jbowman notes "As is often the case, the issue is one of defining your features". One way to engineer a feature for this problem is to look at the last digit of the nu
Would a machine learning classifier algorithm be able to determine whether a number is odd or even? This is a fun little problem. @jbowman notes "As is often the case, the issue is one of defining your features". One way to engineer a feature for this problem is to look at the last digit of the number. Here is a simple little script in sklearn import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.preprocessing import OneHotEncoder, FunctionTransformer @np.vectorize def get_last_digit_of_float(x): str_x = str(x) if len(str_x) == 1: return int(str_x) else: return int(str_x[-1]) last_digit_transformer = FunctionTransformer(get_last_digit_of_float) def main(): train_set = np.arange(100).reshape(-1, 1) y_train = np.arange(100) % 2 test_set = np.arange(100, 200).reshape(-1, 1) y_test = np.arange(100, 200) % 2 model = make_pipeline( last_digit_transformer, OneHotEncoder(categories='auto', sparse=False, handle_unknown='error', drop='first'), LogisticRegression(solver='lbfgs', multi_class='multinomial') ) model.fit(train_set, y_train) print('Test Set Accuracy:', model.score(test_set, y_test)) if __name__ == '__main__': main() This returns a test set accuracy of 1.0. The trick here is to turn the last digit of the number into a feature and then one hot encode the number. This works because any number which ends in an even number is also even. The result is a design matrix with 9 columns (numbers 1 through 9, 0 is not needed in this case since it is absorbed by the intercept in Logistic regression). As always, a clever feature engineering approach is all that is needed.
Would a machine learning classifier algorithm be able to determine whether a number is odd or even? This is a fun little problem. @jbowman notes "As is often the case, the issue is one of defining your features". One way to engineer a feature for this problem is to look at the last digit of the nu
33,535
Would a machine learning classifier algorithm be able to determine whether a number is odd or even?
A sine curve should do the trick. Pick a sine curve with a vertical distance of $1$ and a period of 2 so the curve hits $0$ at the even numbers and $1$ at the odd numbers. Then the output is the probability of being off vs even, and the predicted probabilities exactly match the labels. If you want to make an optimizer do some work, you could consider a model like $y=a+b\sin(cx+d)$, where you let the optimizer figure out the amplitude, frequency, phase shift, and vertical shift.
Would a machine learning classifier algorithm be able to determine whether a number is odd or even?
A sine curve should do the trick. Pick a sine curve with a vertical distance of $1$ and a period of 2 so the curve hits $0$ at the even numbers and $1$ at the odd numbers. Then the output is the proba
Would a machine learning classifier algorithm be able to determine whether a number is odd or even? A sine curve should do the trick. Pick a sine curve with a vertical distance of $1$ and a period of 2 so the curve hits $0$ at the even numbers and $1$ at the odd numbers. Then the output is the probability of being off vs even, and the predicted probabilities exactly match the labels. If you want to make an optimizer do some work, you could consider a model like $y=a+b\sin(cx+d)$, where you let the optimizer figure out the amplitude, frequency, phase shift, and vertical shift.
Would a machine learning classifier algorithm be able to determine whether a number is odd or even? A sine curve should do the trick. Pick a sine curve with a vertical distance of $1$ and a period of 2 so the curve hits $0$ at the even numbers and $1$ at the odd numbers. Then the output is the proba
33,536
Would a machine learning classifier algorithm be able to determine whether a number is odd or even?
This answer won't solve your problem directly, but I think it's important to give a more philosophical interpretation, otherwise the question might results a bit confusing for a beginner. I am a statistician, not a machine learning or computer science expert, so expect inaccuracies and superficiality in the content (please, feel free to enrich it with more technical details, I would be thankful). Here comes the point: As previous answers and comments pointed out, the answer to this question is completely deterministic. You don't need a machine learning algorithm to solve it, because if you know the definition of odd and even number, that itself would be the trivial solution to the question. This solution can be interpreted and solved straightforwardly by any basic machine. To be more practical, for most modern programming languages this problem can be answer by a single IF statement: IF (the number can be divided by 2 with reminder equal to zero) THEN (even) ELSE (odd). Naturally, in the all answers provided above they assumed to know this definition and they built the model around it. Inevitably the accuracy will be always 1. And I can tell you more: if I know the definition there are infinite perfect solutions to your problem, think about it! Imagining that we don't know the definition of even/odd number. How do I solve this problem? Well, I don't really know what is the problem you are trying to solve because a real problem would come with a set of features, that is some real (and imperfect) pieces of information that we have available to classify odd and even numbers. To sum it up, do we know the definition of odd or even number? YES. Then, there is no need for classification algorithms because we know the answer already and it is straightforwardly translatable in machine language. NO. Then, we need some real data (features) and a trial-and-error strategy to understand what's the best model in terms of accuracy. I hope this helps providing a different view point.
Would a machine learning classifier algorithm be able to determine whether a number is odd or even?
This answer won't solve your problem directly, but I think it's important to give a more philosophical interpretation, otherwise the question might results a bit confusing for a beginner. I am a stati
Would a machine learning classifier algorithm be able to determine whether a number is odd or even? This answer won't solve your problem directly, but I think it's important to give a more philosophical interpretation, otherwise the question might results a bit confusing for a beginner. I am a statistician, not a machine learning or computer science expert, so expect inaccuracies and superficiality in the content (please, feel free to enrich it with more technical details, I would be thankful). Here comes the point: As previous answers and comments pointed out, the answer to this question is completely deterministic. You don't need a machine learning algorithm to solve it, because if you know the definition of odd and even number, that itself would be the trivial solution to the question. This solution can be interpreted and solved straightforwardly by any basic machine. To be more practical, for most modern programming languages this problem can be answer by a single IF statement: IF (the number can be divided by 2 with reminder equal to zero) THEN (even) ELSE (odd). Naturally, in the all answers provided above they assumed to know this definition and they built the model around it. Inevitably the accuracy will be always 1. And I can tell you more: if I know the definition there are infinite perfect solutions to your problem, think about it! Imagining that we don't know the definition of even/odd number. How do I solve this problem? Well, I don't really know what is the problem you are trying to solve because a real problem would come with a set of features, that is some real (and imperfect) pieces of information that we have available to classify odd and even numbers. To sum it up, do we know the definition of odd or even number? YES. Then, there is no need for classification algorithms because we know the answer already and it is straightforwardly translatable in machine language. NO. Then, we need some real data (features) and a trial-and-error strategy to understand what's the best model in terms of accuracy. I hope this helps providing a different view point.
Would a machine learning classifier algorithm be able to determine whether a number is odd or even? This answer won't solve your problem directly, but I think it's important to give a more philosophical interpretation, otherwise the question might results a bit confusing for a beginner. I am a stati
33,537
Would a machine learning classifier algorithm be able to determine whether a number is odd or even?
I think a linear model can't do it because there is no direct or inverse relationship between a number (your feature) and the class it belongs to (odd/even). I mean, you can't say something like "as the number gets bigger it will tend to be odd". Also, there are no clusters of even and odd numbers, both classes are uniformly distributed in the set of integer numbers, so SVM, KNN or any clustering algorithm will fail as well. I think you should ask yourself the following: "How can I recognize whether a number is even or odd if the only thing I know is the number itself?" well, there are a bunch of ways to do that. For example, you can divide by two and check if the result is an integer or decimal, but linear models (or any ML model, I think) know nothing about integers or decimal numbers, so they can't help you. Other ways would be using transformations as described in the previous answers but, again, a linear model won't be able to create a binary or sine transformation (perhaps a deep ANN can do something like the sine transform, but I'm not sure). At the end, I think the answer was already given: "...the issue is one of defining your features". You need to help the ML model by providing useful features.
Would a machine learning classifier algorithm be able to determine whether a number is odd or even?
I think a linear model can't do it because there is no direct or inverse relationship between a number (your feature) and the class it belongs to (odd/even). I mean, you can't say something like "as t
Would a machine learning classifier algorithm be able to determine whether a number is odd or even? I think a linear model can't do it because there is no direct or inverse relationship between a number (your feature) and the class it belongs to (odd/even). I mean, you can't say something like "as the number gets bigger it will tend to be odd". Also, there are no clusters of even and odd numbers, both classes are uniformly distributed in the set of integer numbers, so SVM, KNN or any clustering algorithm will fail as well. I think you should ask yourself the following: "How can I recognize whether a number is even or odd if the only thing I know is the number itself?" well, there are a bunch of ways to do that. For example, you can divide by two and check if the result is an integer or decimal, but linear models (or any ML model, I think) know nothing about integers or decimal numbers, so they can't help you. Other ways would be using transformations as described in the previous answers but, again, a linear model won't be able to create a binary or sine transformation (perhaps a deep ANN can do something like the sine transform, but I'm not sure). At the end, I think the answer was already given: "...the issue is one of defining your features". You need to help the ML model by providing useful features.
Would a machine learning classifier algorithm be able to determine whether a number is odd or even? I think a linear model can't do it because there is no direct or inverse relationship between a number (your feature) and the class it belongs to (odd/even). I mean, you can't say something like "as t
33,538
What would be a good machine learning model to predict the next vending machine location?
Let's consider the inputs and outputs for a moment. Say your model takes as inputs things like sales and geolocation. The output is if that location is a vending machine or not. Now...is that useful? Your model does not tell you where to place a vending machine. It tells you if that spot on the map is already a vending machine. That isn't what you want. What you likely want is to find a location on the map which is not a vending machine and optimizes some criteria (likely potential sales). You might want: A lot of foot traffic Not to be too close to other vending machines etc. You need to feed in all that information into some sort of function which scores the location in terms of it being a good or bad location based on the above criteria. Then, you want to find the location which optimizes that function. A really simple example of this might be to put a vending machine somewhere which is farthest from all other vending machines. Of course this might put the machine in the middle of a field somewhere, which is why you need to add constraints to this optimization somehow.
What would be a good machine learning model to predict the next vending machine location?
Let's consider the inputs and outputs for a moment. Say your model takes as inputs things like sales and geolocation. The output is if that location is a vending machine or not. Now...is that useful?
What would be a good machine learning model to predict the next vending machine location? Let's consider the inputs and outputs for a moment. Say your model takes as inputs things like sales and geolocation. The output is if that location is a vending machine or not. Now...is that useful? Your model does not tell you where to place a vending machine. It tells you if that spot on the map is already a vending machine. That isn't what you want. What you likely want is to find a location on the map which is not a vending machine and optimizes some criteria (likely potential sales). You might want: A lot of foot traffic Not to be too close to other vending machines etc. You need to feed in all that information into some sort of function which scores the location in terms of it being a good or bad location based on the above criteria. Then, you want to find the location which optimizes that function. A really simple example of this might be to put a vending machine somewhere which is farthest from all other vending machines. Of course this might put the machine in the middle of a field somewhere, which is why you need to add constraints to this optimization somehow.
What would be a good machine learning model to predict the next vending machine location? Let's consider the inputs and outputs for a moment. Say your model takes as inputs things like sales and geolocation. The output is if that location is a vending machine or not. Now...is that useful?
33,539
What would be a good machine learning model to predict the next vending machine location?
I would try to create some explanatory variables for each geographic location, such as the income distribution at this location, traffic, amount of pedestrians, and similar features. Then I would use the data from existing vending machines to train a model that predicts your response variable from those explanatory variables, e.g. the profit made by a vending machine. If that works, you can predict for each spot in the city the amount of money made by a vending machine placed there. Then you select the places where this prediction returns particularly favorable values and where you don't already have a vending machine. You might also do an experiment and place some new vending machines next to already existing ones, use (some function of) the distances to other vending machines as an additional explanatory variable, and thus learn how the "vending machine density" of a location affects the sales of a new vending machine. I don't really see a time series property here. I would guess that the sales numbers of a vending machine are only affected by the explanatory features referred to above. If the sales numbers of a vending machine depend on those of previously installed vending machines then, I would suspect, only via those features.
What would be a good machine learning model to predict the next vending machine location?
I would try to create some explanatory variables for each geographic location, such as the income distribution at this location, traffic, amount of pedestrians, and similar features. Then I would use
What would be a good machine learning model to predict the next vending machine location? I would try to create some explanatory variables for each geographic location, such as the income distribution at this location, traffic, amount of pedestrians, and similar features. Then I would use the data from existing vending machines to train a model that predicts your response variable from those explanatory variables, e.g. the profit made by a vending machine. If that works, you can predict for each spot in the city the amount of money made by a vending machine placed there. Then you select the places where this prediction returns particularly favorable values and where you don't already have a vending machine. You might also do an experiment and place some new vending machines next to already existing ones, use (some function of) the distances to other vending machines as an additional explanatory variable, and thus learn how the "vending machine density" of a location affects the sales of a new vending machine. I don't really see a time series property here. I would guess that the sales numbers of a vending machine are only affected by the explanatory features referred to above. If the sales numbers of a vending machine depend on those of previously installed vending machines then, I would suspect, only via those features.
What would be a good machine learning model to predict the next vending machine location? I would try to create some explanatory variables for each geographic location, such as the income distribution at this location, traffic, amount of pedestrians, and similar features. Then I would use
33,540
What would be a good machine learning model to predict the next vending machine location?
@whuber made a very good point: "Placing a new vending machine 'cannibalizes' sales from nearby ones". Cannibalization may be desirable or not, depending on whether the OP is eating the market of his competitor, or himself. Instead of a writing a machine learner to predict locations, it might be more useful to simulate vending machines. We have a City, say 東京, with existing vending machines owned by a number of companies (maybe try modelling as 2, Us and Them). Initially I imagine that the obvious good locations, such railway stations,are taken. We have a number of graphical views, such number of potential customers, distance to nearest machine, revenue of each machine, etc. Now you can model the effects of new locations, and new products, subject to whatever assumptions you may be making. Next step might be allowing the simulation to try out new locations, Monte Carlo style.
What would be a good machine learning model to predict the next vending machine location?
@whuber made a very good point: "Placing a new vending machine 'cannibalizes' sales from nearby ones". Cannibalization may be desirable or not, depending on whether the OP is eating the market of his
What would be a good machine learning model to predict the next vending machine location? @whuber made a very good point: "Placing a new vending machine 'cannibalizes' sales from nearby ones". Cannibalization may be desirable or not, depending on whether the OP is eating the market of his competitor, or himself. Instead of a writing a machine learner to predict locations, it might be more useful to simulate vending machines. We have a City, say 東京, with existing vending machines owned by a number of companies (maybe try modelling as 2, Us and Them). Initially I imagine that the obvious good locations, such railway stations,are taken. We have a number of graphical views, such number of potential customers, distance to nearest machine, revenue of each machine, etc. Now you can model the effects of new locations, and new products, subject to whatever assumptions you may be making. Next step might be allowing the simulation to try out new locations, Monte Carlo style.
What would be a good machine learning model to predict the next vending machine location? @whuber made a very good point: "Placing a new vending machine 'cannibalizes' sales from nearby ones". Cannibalization may be desirable or not, depending on whether the OP is eating the market of his
33,541
What would be a good machine learning model to predict the next vending machine location?
If you want to frame it as a time series problem, then you might want to go the autoregressive decoder route, where you feed in the sequence of past "outputs" (using teacher forcing, as is commonly used to parallelize transformer model training) in addition to your regular input features in order to help the model predict the next location. Note that the time series formulation and using the historical data as ground truth assumes that the historical placements and timings were optimal, which is a shaky assumption. However, you should be able to approximate human performance provided you have supplied your model with enough information. Note that this is likely a high perplexity task so don't expect your training losses to get very low-- but even an RNN should be a good fit for this. Recurrent memories retain information about likely candidates and can pivot to another close or "next-best" option if the model's top-1 pick in the current timeframe isn't the "best fit" to the historical data. In any case, it sounds to me like your problem has an inherent autoregressive property. If you wanted to flatten out the time element, the problem becomes something like, "given the currently deployed machines and the other input features, predict a heatmap, top-k or a single-best location for future machines", for which a variety of architectures could be reasonable candidates.
What would be a good machine learning model to predict the next vending machine location?
If you want to frame it as a time series problem, then you might want to go the autoregressive decoder route, where you feed in the sequence of past "outputs" (using teacher forcing, as is commonly us
What would be a good machine learning model to predict the next vending machine location? If you want to frame it as a time series problem, then you might want to go the autoregressive decoder route, where you feed in the sequence of past "outputs" (using teacher forcing, as is commonly used to parallelize transformer model training) in addition to your regular input features in order to help the model predict the next location. Note that the time series formulation and using the historical data as ground truth assumes that the historical placements and timings were optimal, which is a shaky assumption. However, you should be able to approximate human performance provided you have supplied your model with enough information. Note that this is likely a high perplexity task so don't expect your training losses to get very low-- but even an RNN should be a good fit for this. Recurrent memories retain information about likely candidates and can pivot to another close or "next-best" option if the model's top-1 pick in the current timeframe isn't the "best fit" to the historical data. In any case, it sounds to me like your problem has an inherent autoregressive property. If you wanted to flatten out the time element, the problem becomes something like, "given the currently deployed machines and the other input features, predict a heatmap, top-k or a single-best location for future machines", for which a variety of architectures could be reasonable candidates.
What would be a good machine learning model to predict the next vending machine location? If you want to frame it as a time series problem, then you might want to go the autoregressive decoder route, where you feed in the sequence of past "outputs" (using teacher forcing, as is commonly us
33,542
How many times to repeat an event with known probability before it has occurred a number of times
Consider a sequence of $n$ independent trials with success probability $p$. Let $X$ be the number of successes out of the $n$ trials. Then $X$ has a Binomial distribution with parameters $n$ and $p$. The expected value of a Binomial rv is $E(X) = np$. A simple approach is to set this equal to $120$ and solve for $n$. Since $p=0.01$, we have $n(0.01) = 120$ which means that $n=12,000$ trials are expected to obtain $120$ successes. Alternatively, here is a related approach that gives the number of trials needed to observe $r=120$ successes with some probability $\gamma$ (i.e. $\gamma=0.95$). Consider a sequence of independent trials with success probability $p$. Let $X$ be the number of trials required to observe $r$ successes. Then $X$ has a Negative Binomial distribution with parameters $r$ and $p$. In your case, $X \sim \text{Negative-Binomial}(120, 0.01)$, and you want to find $x$ such that $$P(X \leq x) = \gamma.$$ Although the Negative Binomial distribution has no closed form quantile function, this $x$ can be solved for easily. For instance, the answer can be obtained in R by typing: qnbinom(.95, 120, .01). The answer $x=13728$ indicates that $13,728$ trials are required to have a 95% chance of observing $120$ (or more) successes.
How many times to repeat an event with known probability before it has occurred a number of times
Consider a sequence of $n$ independent trials with success probability $p$. Let $X$ be the number of successes out of the $n$ trials. Then $X$ has a Binomial distribution with parameters $n$ and $p$.
How many times to repeat an event with known probability before it has occurred a number of times Consider a sequence of $n$ independent trials with success probability $p$. Let $X$ be the number of successes out of the $n$ trials. Then $X$ has a Binomial distribution with parameters $n$ and $p$. The expected value of a Binomial rv is $E(X) = np$. A simple approach is to set this equal to $120$ and solve for $n$. Since $p=0.01$, we have $n(0.01) = 120$ which means that $n=12,000$ trials are expected to obtain $120$ successes. Alternatively, here is a related approach that gives the number of trials needed to observe $r=120$ successes with some probability $\gamma$ (i.e. $\gamma=0.95$). Consider a sequence of independent trials with success probability $p$. Let $X$ be the number of trials required to observe $r$ successes. Then $X$ has a Negative Binomial distribution with parameters $r$ and $p$. In your case, $X \sim \text{Negative-Binomial}(120, 0.01)$, and you want to find $x$ such that $$P(X \leq x) = \gamma.$$ Although the Negative Binomial distribution has no closed form quantile function, this $x$ can be solved for easily. For instance, the answer can be obtained in R by typing: qnbinom(.95, 120, .01). The answer $x=13728$ indicates that $13,728$ trials are required to have a 95% chance of observing $120$ (or more) successes.
How many times to repeat an event with known probability before it has occurred a number of times Consider a sequence of $n$ independent trials with success probability $p$. Let $X$ be the number of successes out of the $n$ trials. Then $X$ has a Binomial distribution with parameters $n$ and $p$.
33,543
How many times to repeat an event with known probability before it has occurred a number of times
First, I'm going to assume that the experiments are independent since you said the probably of a success is always 1%. The keyword in your question is "expected," which means we'll be looking for a mean or expected value. If you are interested in the number of trials $X$ (with common probability of success $p$), needed to obtain $r$ successes, then you can model this as a negative binomial random variable with probability mass function: \begin{eqnarray*} f_{X}(x|r,p) & = & {x-1 \choose r-1}p^{r}(1-p)^{x-r} \end{eqnarray*} for $x=r,r+1,...,$ The expected value of the negative binomial is well known as: \begin{eqnarray*} E(X) & = & \frac{r}{p} \end{eqnarray*} In your case, $p=0.01$ and $r=120$. So the expected number of independent trials of your experiment (times) needed to obtain $120$ successes is simply given by $120/0.01=12,000$
How many times to repeat an event with known probability before it has occurred a number of times
First, I'm going to assume that the experiments are independent since you said the probably of a success is always 1%. The keyword in your question is "expected," which means we'll be looking for a m
How many times to repeat an event with known probability before it has occurred a number of times First, I'm going to assume that the experiments are independent since you said the probably of a success is always 1%. The keyword in your question is "expected," which means we'll be looking for a mean or expected value. If you are interested in the number of trials $X$ (with common probability of success $p$), needed to obtain $r$ successes, then you can model this as a negative binomial random variable with probability mass function: \begin{eqnarray*} f_{X}(x|r,p) & = & {x-1 \choose r-1}p^{r}(1-p)^{x-r} \end{eqnarray*} for $x=r,r+1,...,$ The expected value of the negative binomial is well known as: \begin{eqnarray*} E(X) & = & \frac{r}{p} \end{eqnarray*} In your case, $p=0.01$ and $r=120$. So the expected number of independent trials of your experiment (times) needed to obtain $120$ successes is simply given by $120/0.01=12,000$
How many times to repeat an event with known probability before it has occurred a number of times First, I'm going to assume that the experiments are independent since you said the probably of a success is always 1%. The keyword in your question is "expected," which means we'll be looking for a m
33,544
How many times to repeat an event with known probability before it has occurred a number of times
As others have noted, the chance of succeeding enought times will follow a negative binomial distribution. It is useful to plot this, and you can do this in R with: plot(function(x) pnbinom(x,120,0.01),120,20000) Which gives: As you can see it has a sigmoidal shape and there are large areas with virtually no chance and almost certainty and a rapid shift between the two close to the expected value. Therefore, increasing the number of trials may have little effect or a very great effect on the chance of achieving the target depending on how many you've already decided on. If you scale this function by the number of trails (i.e. mean chance per trial), you can see that there is a clear maximum value, plot(function(x) pnbinom(x,120,0.01)/x,120,20000) which you can identify with: optimise(function(x) pnbinom(x,120,0.01)/x,c(120,20000),maximum=TRUE) $maximum [1] 13888 $objective [1] 6.929301e-05
How many times to repeat an event with known probability before it has occurred a number of times
As others have noted, the chance of succeeding enought times will follow a negative binomial distribution. It is useful to plot this, and you can do this in R with: plot(function(x) pnbinom(x,120,0.01
How many times to repeat an event with known probability before it has occurred a number of times As others have noted, the chance of succeeding enought times will follow a negative binomial distribution. It is useful to plot this, and you can do this in R with: plot(function(x) pnbinom(x,120,0.01),120,20000) Which gives: As you can see it has a sigmoidal shape and there are large areas with virtually no chance and almost certainty and a rapid shift between the two close to the expected value. Therefore, increasing the number of trials may have little effect or a very great effect on the chance of achieving the target depending on how many you've already decided on. If you scale this function by the number of trails (i.e. mean chance per trial), you can see that there is a clear maximum value, plot(function(x) pnbinom(x,120,0.01)/x,120,20000) which you can identify with: optimise(function(x) pnbinom(x,120,0.01)/x,c(120,20000),maximum=TRUE) $maximum [1] 13888 $objective [1] 6.929301e-05
How many times to repeat an event with known probability before it has occurred a number of times As others have noted, the chance of succeeding enought times will follow a negative binomial distribution. It is useful to plot this, and you can do this in R with: plot(function(x) pnbinom(x,120,0.01
33,545
How many times to repeat an event with known probability before it has occurred a number of times
As knrumsey says, the number of successes will follow a binomial distribution, but unless you need a high level of precision, 1% is a small enough number that you can use the approximation of a Poisson distribution with $\lambda=120\frac{1\%}{99\%}=1.2121$
How many times to repeat an event with known probability before it has occurred a number of times
As knrumsey says, the number of successes will follow a binomial distribution, but unless you need a high level of precision, 1% is a small enough number that you can use the approximation of a Poisso
How many times to repeat an event with known probability before it has occurred a number of times As knrumsey says, the number of successes will follow a binomial distribution, but unless you need a high level of precision, 1% is a small enough number that you can use the approximation of a Poisson distribution with $\lambda=120\frac{1\%}{99\%}=1.2121$
How many times to repeat an event with known probability before it has occurred a number of times As knrumsey says, the number of successes will follow a binomial distribution, but unless you need a high level of precision, 1% is a small enough number that you can use the approximation of a Poisso
33,546
What will happen if I use a nonparametric test with normally distributed data?
In statistical analysis, if your data follow a parametric distribution, you should utilize the benefit of knowing the distribution, and employ the statistical methods based on that distribution. But sometimes we do not know the distribution of the random variable, so the nonparametric statistical methods were developed to embrace the wide range of the distributions while sacrificing some efficiency. Given you know the distribution of random variable and use the nonparametric statistical method, instead of parametric statistical methods based on knowing the distribution, it will be inefficient, i.e., the power of test will decrease, standard error will increase, and the confidence intervals will be wider than with the parametric method.
What will happen if I use a nonparametric test with normally distributed data?
In statistical analysis, if your data follow a parametric distribution, you should utilize the benefit of knowing the distribution, and employ the statistical methods based on that distribution. But
What will happen if I use a nonparametric test with normally distributed data? In statistical analysis, if your data follow a parametric distribution, you should utilize the benefit of knowing the distribution, and employ the statistical methods based on that distribution. But sometimes we do not know the distribution of the random variable, so the nonparametric statistical methods were developed to embrace the wide range of the distributions while sacrificing some efficiency. Given you know the distribution of random variable and use the nonparametric statistical method, instead of parametric statistical methods based on knowing the distribution, it will be inefficient, i.e., the power of test will decrease, standard error will increase, and the confidence intervals will be wider than with the parametric method.
What will happen if I use a nonparametric test with normally distributed data? In statistical analysis, if your data follow a parametric distribution, you should utilize the benefit of knowing the distribution, and employ the statistical methods based on that distribution. But
33,547
What will happen if I use a nonparametric test with normally distributed data?
If your data happened to be drawn from a normal population (and the other usual assumptions for an ordinary t-test apply), then the test works as it should (it's non-parametric, it's supposed to work). There's no drama on that score. If you know enough that you're confident in assuming normality you may want to take advantage of that knowledge, but for many tests it doesn't help you a lot. If you're doing one of the common location-tests (Wilcoxon signed rank test, Wilcoxon-Mann-Whitney test) you lose almost nothing (power-wise) in a test for a location shift by ignoring the normality. [You need one extra observation for every 21 observations to match the power of the most powerful test when all its assumptions hold.] If you're dealing with some other tests is may matter a bit more (though some may matter even less). One example where it makes a somewhat bigger difference is using a Friedman test compared to the corresponding ANOVA test in a randomized blocks design.
What will happen if I use a nonparametric test with normally distributed data?
If your data happened to be drawn from a normal population (and the other usual assumptions for an ordinary t-test apply), then the test works as it should (it's non-parametric, it's supposed to work)
What will happen if I use a nonparametric test with normally distributed data? If your data happened to be drawn from a normal population (and the other usual assumptions for an ordinary t-test apply), then the test works as it should (it's non-parametric, it's supposed to work). There's no drama on that score. If you know enough that you're confident in assuming normality you may want to take advantage of that knowledge, but for many tests it doesn't help you a lot. If you're doing one of the common location-tests (Wilcoxon signed rank test, Wilcoxon-Mann-Whitney test) you lose almost nothing (power-wise) in a test for a location shift by ignoring the normality. [You need one extra observation for every 21 observations to match the power of the most powerful test when all its assumptions hold.] If you're dealing with some other tests is may matter a bit more (though some may matter even less). One example where it makes a somewhat bigger difference is using a Friedman test compared to the corresponding ANOVA test in a randomized blocks design.
What will happen if I use a nonparametric test with normally distributed data? If your data happened to be drawn from a normal population (and the other usual assumptions for an ordinary t-test apply), then the test works as it should (it's non-parametric, it's supposed to work)
33,548
Does regression work on data that isn't normally distributed?
A regression analysis assumes that the data is normally distributed conditioned on the variables in the regression model. That is, if this is the regression model: $$y=X\beta+\varepsilon$$ where $X$ is your matrix of regressor variables, $y$ is the (vector of) data to be explained, $\beta$ is a vector of coefficients on the regressors and $\varepsilon$ is random variability (typically considered noise), then the assumption of Normality applies strictly to $\varepsilon$, not to $y$ (edit: well, strictly speaking it applies to the conditional distribution $y|X$ (which is the same as the distribution of $\varepsilon$), but not to the marginal distribution of $y$). In other words, the data should be Normally distributed once the effects of the regressors have been accounted for, but not (necessarily) before. What you're testing here is the distribution of $y$, where what you want to test is the distribution of $\varepsilon$. Of course you don't know $\varepsilon$, but you can estimate it by running the regression and examining the distrbution of the residuals $\hat\varepsilon=y-X\hat\beta $ (where $\hat\beta$ are the estimated coefficents from the regression). These residuals $\hat\varepsilon$ are an estimate of $\varepsilon$, and so their distribution will be an approximation of the distribution of $\varepsilon$.
Does regression work on data that isn't normally distributed?
A regression analysis assumes that the data is normally distributed conditioned on the variables in the regression model. That is, if this is the regression model: $$y=X\beta+\varepsilon$$ where $X$ i
Does regression work on data that isn't normally distributed? A regression analysis assumes that the data is normally distributed conditioned on the variables in the regression model. That is, if this is the regression model: $$y=X\beta+\varepsilon$$ where $X$ is your matrix of regressor variables, $y$ is the (vector of) data to be explained, $\beta$ is a vector of coefficients on the regressors and $\varepsilon$ is random variability (typically considered noise), then the assumption of Normality applies strictly to $\varepsilon$, not to $y$ (edit: well, strictly speaking it applies to the conditional distribution $y|X$ (which is the same as the distribution of $\varepsilon$), but not to the marginal distribution of $y$). In other words, the data should be Normally distributed once the effects of the regressors have been accounted for, but not (necessarily) before. What you're testing here is the distribution of $y$, where what you want to test is the distribution of $\varepsilon$. Of course you don't know $\varepsilon$, but you can estimate it by running the regression and examining the distrbution of the residuals $\hat\varepsilon=y-X\hat\beta $ (where $\hat\beta$ are the estimated coefficents from the regression). These residuals $\hat\varepsilon$ are an estimate of $\varepsilon$, and so their distribution will be an approximation of the distribution of $\varepsilon$.
Does regression work on data that isn't normally distributed? A regression analysis assumes that the data is normally distributed conditioned on the variables in the regression model. That is, if this is the regression model: $$y=X\beta+\varepsilon$$ where $X$ i
33,549
Does regression work on data that isn't normally distributed?
The short answer is yes. First of all (as is pointed out by Ruben van Bergen), the distribution of $y$ (or $X$, for that matter) is not relevant. If you were to make a distributional assumption, it would be on your residuals $\varepsilon$, so that is what you should check. But more importantly, you don't need the normality assumption at all for your estimation to work. You are using R's lm function, which estimates your model using ordinary least squares (OLS). That method will give you a correct estimation of the expectation of $Y$ conditional on $X$ as long as: $\mathbb{E}[\varepsilon|X] = 0$ (there is no external factor affecting both your outcome and your explanatory variables). $\mathrm{Var}(\varepsilon) < \infty$ (your residuals have finite variance). If you further make the assumption that you residuals are uncorrelated and that they all have the same variance, then the Gauss-Markov theorem applies and the OLS is the best linear unbiased estimator (BLUE). If your residuals are correlated or have different variances, then OLS still works but it can be less precise, which must be reflected in the way you report the confidence intervals of your estimates (using, say robust standard errors). If you also make the assumption that your residuals are normally distributed, then OLS becomes asymptotically efficient because it is equivalent to maximum likelihood. So the regression may work better if your data are normally distributed, but it will still work if they aren't.
Does regression work on data that isn't normally distributed?
The short answer is yes. First of all (as is pointed out by Ruben van Bergen), the distribution of $y$ (or $X$, for that matter) is not relevant. If you were to make a distributional assumption, it wo
Does regression work on data that isn't normally distributed? The short answer is yes. First of all (as is pointed out by Ruben van Bergen), the distribution of $y$ (or $X$, for that matter) is not relevant. If you were to make a distributional assumption, it would be on your residuals $\varepsilon$, so that is what you should check. But more importantly, you don't need the normality assumption at all for your estimation to work. You are using R's lm function, which estimates your model using ordinary least squares (OLS). That method will give you a correct estimation of the expectation of $Y$ conditional on $X$ as long as: $\mathbb{E}[\varepsilon|X] = 0$ (there is no external factor affecting both your outcome and your explanatory variables). $\mathrm{Var}(\varepsilon) < \infty$ (your residuals have finite variance). If you further make the assumption that you residuals are uncorrelated and that they all have the same variance, then the Gauss-Markov theorem applies and the OLS is the best linear unbiased estimator (BLUE). If your residuals are correlated or have different variances, then OLS still works but it can be less precise, which must be reflected in the way you report the confidence intervals of your estimates (using, say robust standard errors). If you also make the assumption that your residuals are normally distributed, then OLS becomes asymptotically efficient because it is equivalent to maximum likelihood. So the regression may work better if your data are normally distributed, but it will still work if they aren't.
Does regression work on data that isn't normally distributed? The short answer is yes. First of all (as is pointed out by Ruben van Bergen), the distribution of $y$ (or $X$, for that matter) is not relevant. If you were to make a distributional assumption, it wo
33,550
How to calculate the median of a pdf
A median by definition is a real number $m$ that satisfies $$P(X\leq m)=\frac{1}{2}.$$ So in your case, we have $$\int_0^m2xe^{-x^2}\,dx=\frac{1}{2}.$$ How do you solve for $m$ then? Hint: integration by substitution.
How to calculate the median of a pdf
A median by definition is a real number $m$ that satisfies $$P(X\leq m)=\frac{1}{2}.$$ So in your case, we have $$\int_0^m2xe^{-x^2}\,dx=\frac{1}{2}.$$ How do you solve for $m$ then? Hint: integration
How to calculate the median of a pdf A median by definition is a real number $m$ that satisfies $$P(X\leq m)=\frac{1}{2}.$$ So in your case, we have $$\int_0^m2xe^{-x^2}\,dx=\frac{1}{2}.$$ How do you solve for $m$ then? Hint: integration by substitution.
How to calculate the median of a pdf A median by definition is a real number $m$ that satisfies $$P(X\leq m)=\frac{1}{2}.$$ So in your case, we have $$\int_0^m2xe^{-x^2}\,dx=\frac{1}{2}.$$ How do you solve for $m$ then? Hint: integration
33,551
R vs STATA which is more valuable to an actuary?
I passed a few of the actuarial exams before deciding that I did not want to be an actuary, so I don't work as an actuary, but as a statistician (and I hire statisticians). I use R, but Stata is a good program as well (I like R in that for the same low price I can have it installed on my work computer, my laptop, my home computer, the computer at church, etc.). My sister who is an FSA (retired now) primarily used Excel for her work, but we get along despite this. Why do you feel the need to focus on only one? When I interview prospective employees, if they only know one program (even if it is my favorite) I don't know if they can learn another if needed (or learn different parts of that one that they don't know yet). But, if they know 3 programs (I don't expect full expertise in all) even if my favorite is not included, then I am fairly confident that they can learn another if needed and learn more about the ones that they do know. So when I look at job candidates (granted not actuaries, but statisticians) I am more impressed by bredth in knowing multiple packages than depth in only 1 package. So I would recommend rather than choosing one to focus on that you develope your skills in both and probably add some basic knowledge in a 3rd (SAS would be good based on its history and wide spread use, but others could fill the 3rd slot as well).
R vs STATA which is more valuable to an actuary?
I passed a few of the actuarial exams before deciding that I did not want to be an actuary, so I don't work as an actuary, but as a statistician (and I hire statisticians). I use R, but Stata is a go
R vs STATA which is more valuable to an actuary? I passed a few of the actuarial exams before deciding that I did not want to be an actuary, so I don't work as an actuary, but as a statistician (and I hire statisticians). I use R, but Stata is a good program as well (I like R in that for the same low price I can have it installed on my work computer, my laptop, my home computer, the computer at church, etc.). My sister who is an FSA (retired now) primarily used Excel for her work, but we get along despite this. Why do you feel the need to focus on only one? When I interview prospective employees, if they only know one program (even if it is my favorite) I don't know if they can learn another if needed (or learn different parts of that one that they don't know yet). But, if they know 3 programs (I don't expect full expertise in all) even if my favorite is not included, then I am fairly confident that they can learn another if needed and learn more about the ones that they do know. So when I look at job candidates (granted not actuaries, but statisticians) I am more impressed by bredth in knowing multiple packages than depth in only 1 package. So I would recommend rather than choosing one to focus on that you develope your skills in both and probably add some basic knowledge in a 3rd (SAS would be good based on its history and wide spread use, but others could fill the 3rd slot as well).
R vs STATA which is more valuable to an actuary? I passed a few of the actuarial exams before deciding that I did not want to be an actuary, so I don't work as an actuary, but as a statistician (and I hire statisticians). I use R, but Stata is a go
33,552
R vs STATA which is more valuable to an actuary?
Not an actuarial, but in case none wander by and answer your question... What software does your school use? What software does your school offer classes in? Does your school help you to get STATA at a student price? When you read actuarial journals and textbooks, what tools do they use? As jem77bfp said, R is free and you can continue to use it and explore it all you want. Professionals in most fields use multiple tools, and you can't tell what future employers might require (SAS, SPSS, etc), so it might be a good idea to branch out a bit now. It wouldn't be unusual for a professional economist/statistician to use R for general-purpose analysis and graphing, JAGS/BUGS/STAN for MCMC analysis, ArcGIS for spatial data, Gephi or some other program for analyzing graphs, etc. But the bottom line is that R is free and has a LOT of packages to do particular types of analysis. A couple of years ago I was in a graduate machine learning class where the teacher did everything in Matlab and recommended Matlab toolkits. (The school also sold student discount Matlab in the school store.) But I used R and did very well, while other students used Stata, Java, etc. I wasn't going to get any help from the teacher or TA's -- or even other students -- if I had a problem doing something in R, but that wasn't a concern for me.
R vs STATA which is more valuable to an actuary?
Not an actuarial, but in case none wander by and answer your question... What software does your school use? What software does your school offer classes in? Does your school help you to get STATA at
R vs STATA which is more valuable to an actuary? Not an actuarial, but in case none wander by and answer your question... What software does your school use? What software does your school offer classes in? Does your school help you to get STATA at a student price? When you read actuarial journals and textbooks, what tools do they use? As jem77bfp said, R is free and you can continue to use it and explore it all you want. Professionals in most fields use multiple tools, and you can't tell what future employers might require (SAS, SPSS, etc), so it might be a good idea to branch out a bit now. It wouldn't be unusual for a professional economist/statistician to use R for general-purpose analysis and graphing, JAGS/BUGS/STAN for MCMC analysis, ArcGIS for spatial data, Gephi or some other program for analyzing graphs, etc. But the bottom line is that R is free and has a LOT of packages to do particular types of analysis. A couple of years ago I was in a graduate machine learning class where the teacher did everything in Matlab and recommended Matlab toolkits. (The school also sold student discount Matlab in the school store.) But I used R and did very well, while other students used Stata, Java, etc. I wasn't going to get any help from the teacher or TA's -- or even other students -- if I had a problem doing something in R, but that wasn't a concern for me.
R vs STATA which is more valuable to an actuary? Not an actuarial, but in case none wander by and answer your question... What software does your school use? What software does your school offer classes in? Does your school help you to get STATA at
33,553
R vs STATA which is more valuable to an actuary?
R. Stata is easy if you want to use (but not learn) basic, undergrad level, stuff. R on the other hand does everything Stata does and much, much more. In particular, you can use R for serious data cleaning & manipulation as well as advanced analyses. Furthermore, if you user R, it is easier for others to work with you and, you'll actually improve your skills. Using a GUI will only make you good at using that particular GUI.
R vs STATA which is more valuable to an actuary?
R. Stata is easy if you want to use (but not learn) basic, undergrad level, stuff. R on the other hand does everything Stata does and much, much more. In particular, you can use R for serious data cle
R vs STATA which is more valuable to an actuary? R. Stata is easy if you want to use (but not learn) basic, undergrad level, stuff. R on the other hand does everything Stata does and much, much more. In particular, you can use R for serious data cleaning & manipulation as well as advanced analyses. Furthermore, if you user R, it is easier for others to work with you and, you'll actually improve your skills. Using a GUI will only make you good at using that particular GUI.
R vs STATA which is more valuable to an actuary? R. Stata is easy if you want to use (but not learn) basic, undergrad level, stuff. R on the other hand does everything Stata does and much, much more. In particular, you can use R for serious data cle
33,554
R vs STATA which is more valuable to an actuary?
Look at job listings. SQL is the buzzword that comes up most often. I have seen some R listed, and I can't remember seeing Stata mentioned, that might be because my mind glosses over it since I've never used it.
R vs STATA which is more valuable to an actuary?
Look at job listings. SQL is the buzzword that comes up most often. I have seen some R listed, and I can't remember seeing Stata mentioned, that might be because my mind glosses over it since I've n
R vs STATA which is more valuable to an actuary? Look at job listings. SQL is the buzzword that comes up most often. I have seen some R listed, and I can't remember seeing Stata mentioned, that might be because my mind glosses over it since I've never used it.
R vs STATA which is more valuable to an actuary? Look at job listings. SQL is the buzzword that comes up most often. I have seen some R listed, and I can't remember seeing Stata mentioned, that might be because my mind glosses over it since I've n
33,555
Interpreting effect size
These "standards" in psychology are an unfortunate consequence of poor statistics training. Don't look for such standards in an entire field. At best they could be found within a particular subject matter. Cohen never intended these to be standards and just suggested them as a starting point for interpretation based on a prior analysis of social science effect sizes and intuition. We were supposed to grow beyond that suggestion, not turn it into doctrine.
Interpreting effect size
These "standards" in psychology are an unfortunate consequence of poor statistics training. Don't look for such standards in an entire field. At best they could be found within a particular subject m
Interpreting effect size These "standards" in psychology are an unfortunate consequence of poor statistics training. Don't look for such standards in an entire field. At best they could be found within a particular subject matter. Cohen never intended these to be standards and just suggested them as a starting point for interpretation based on a prior analysis of social science effect sizes and intuition. We were supposed to grow beyond that suggestion, not turn it into doctrine.
Interpreting effect size These "standards" in psychology are an unfortunate consequence of poor statistics training. Don't look for such standards in an entire field. At best they could be found within a particular subject m
33,556
Interpreting effect size
John has already given a spot on answer. Just as an addendum (which is just a bit too long as a comment), let me just add a quote from Cohen himself (from Statistical power analysis for the behavioral sciences, 1988): The terms "small,", "medium,", and "large" are relative, not only to each other, but to the area of behavioral science or even more particularly to the specific content and research method being employed in any given investigation [...]. In the face of this relativity, there is a certain risk inherent in offering conventional operational definitions for these terms [...]. This risk is nevertheless accepted in the belief that more is to be gained than lost by supplying a common conventional frame of reference which is recommended for use only when no better basis for estimating the ES index is available. (p. 25). The emphasis is mine. In many cases, there is a better basis, since effects are often measured with scales for which we have some prior knowledge/intuition about the meaning of the raw units and the amount of variability in the outcome. In his famous 1994 paper ("The earth is round (p < .05)"), Cohen himself also recommended moving away from 'standardized' measures of effect and instead advocated working with raw measures of effect. Another quote: To work constructively with "raw" regression coefficients and confidence intervals, psychologists have to start respecting the units they work with, or develop measurement units they can respect enough so that researchers in a given field or subfield can agree to use them. In this way, there can be hope that researchers' knowledge can be cumulative. (p. 1001). Again, emphasis is mine. It is unfortunate that Cohen got his name attached to these 'canned' values, when in fact he was quite careful not to overemphasize their meaning.
Interpreting effect size
John has already given a spot on answer. Just as an addendum (which is just a bit too long as a comment), let me just add a quote from Cohen himself (from Statistical power analysis for the behavioral
Interpreting effect size John has already given a spot on answer. Just as an addendum (which is just a bit too long as a comment), let me just add a quote from Cohen himself (from Statistical power analysis for the behavioral sciences, 1988): The terms "small,", "medium,", and "large" are relative, not only to each other, but to the area of behavioral science or even more particularly to the specific content and research method being employed in any given investigation [...]. In the face of this relativity, there is a certain risk inherent in offering conventional operational definitions for these terms [...]. This risk is nevertheless accepted in the belief that more is to be gained than lost by supplying a common conventional frame of reference which is recommended for use only when no better basis for estimating the ES index is available. (p. 25). The emphasis is mine. In many cases, there is a better basis, since effects are often measured with scales for which we have some prior knowledge/intuition about the meaning of the raw units and the amount of variability in the outcome. In his famous 1994 paper ("The earth is round (p < .05)"), Cohen himself also recommended moving away from 'standardized' measures of effect and instead advocated working with raw measures of effect. Another quote: To work constructively with "raw" regression coefficients and confidence intervals, psychologists have to start respecting the units they work with, or develop measurement units they can respect enough so that researchers in a given field or subfield can agree to use them. In this way, there can be hope that researchers' knowledge can be cumulative. (p. 1001). Again, emphasis is mine. It is unfortunate that Cohen got his name attached to these 'canned' values, when in fact he was quite careful not to overemphasize their meaning.
Interpreting effect size John has already given a spot on answer. Just as an addendum (which is just a bit too long as a comment), let me just add a quote from Cohen himself (from Statistical power analysis for the behavioral
33,557
An example of a SYMMETRIC distribution with finite mean but infinite/undefined variance?
A t-distribution with a small degrees of freedom parameter satisfies your requirements. While having one degree of freedom results in a Cauchy distribution that even lacks an expected value, $t_{\nu}$ for $\nu\in(1,2]$ has a mean of zero but infinite variance while also being symmetric about its mean.
An example of a SYMMETRIC distribution with finite mean but infinite/undefined variance?
A t-distribution with a small degrees of freedom parameter satisfies your requirements. While having one degree of freedom results in a Cauchy distribution that even lacks an expected value, $t_{\nu}$
An example of a SYMMETRIC distribution with finite mean but infinite/undefined variance? A t-distribution with a small degrees of freedom parameter satisfies your requirements. While having one degree of freedom results in a Cauchy distribution that even lacks an expected value, $t_{\nu}$ for $\nu\in(1,2]$ has a mean of zero but infinite variance while also being symmetric about its mean.
An example of a SYMMETRIC distribution with finite mean but infinite/undefined variance? A t-distribution with a small degrees of freedom parameter satisfies your requirements. While having one degree of freedom results in a Cauchy distribution that even lacks an expected value, $t_{\nu}$
33,558
An example of a SYMMETRIC distribution with finite mean but infinite/undefined variance?
Expanding on @whuber's suggestion: let $g : [0,+\infty) \rightarrow \mathbb{R}_+$ be any positive function such that $\int^{+\infty}_0 g(t) dt < +\infty$, $\int^{+\infty}_0 tg(t) dt < +\infty$ and $\int^{+\infty}_0 t^2 g(t) dt = +\infty$. Let us denote $f := x\mapsto g(\vert x \vert)$. Then $\frac{f}{2\int^{+\infty}_0 g(t)dt}$ is a symmetric distribution with finite first moment, but infinite second moment. Such $g$'s are easy to build: for example, let $\alpha>0$, and let us denote, for each $t \in [0,+\infty)$, $g(t) := 1$ if $t \leq 1$ and $g(t) := \frac{1}{t^\alpha}$ if $t>1$. Then such a $g$ satisfies the requirements if and only if $\alpha \in (2,3]$, so there are many of such $g$'s.
An example of a SYMMETRIC distribution with finite mean but infinite/undefined variance?
Expanding on @whuber's suggestion: let $g : [0,+\infty) \rightarrow \mathbb{R}_+$ be any positive function such that $\int^{+\infty}_0 g(t) dt < +\infty$, $\int^{+\infty}_0 tg(t) dt < +\infty$ and
An example of a SYMMETRIC distribution with finite mean but infinite/undefined variance? Expanding on @whuber's suggestion: let $g : [0,+\infty) \rightarrow \mathbb{R}_+$ be any positive function such that $\int^{+\infty}_0 g(t) dt < +\infty$, $\int^{+\infty}_0 tg(t) dt < +\infty$ and $\int^{+\infty}_0 t^2 g(t) dt = +\infty$. Let us denote $f := x\mapsto g(\vert x \vert)$. Then $\frac{f}{2\int^{+\infty}_0 g(t)dt}$ is a symmetric distribution with finite first moment, but infinite second moment. Such $g$'s are easy to build: for example, let $\alpha>0$, and let us denote, for each $t \in [0,+\infty)$, $g(t) := 1$ if $t \leq 1$ and $g(t) := \frac{1}{t^\alpha}$ if $t>1$. Then such a $g$ satisfies the requirements if and only if $\alpha \in (2,3]$, so there are many of such $g$'s.
An example of a SYMMETRIC distribution with finite mean but infinite/undefined variance? Expanding on @whuber's suggestion: let $g : [0,+\infty) \rightarrow \mathbb{R}_+$ be any positive function such that $\int^{+\infty}_0 g(t) dt < +\infty$, $\int^{+\infty}_0 tg(t) dt < +\infty$ and
33,559
identify the point of intersection from two distributions
A tiny bit of statistics is needed here, if only to point out the need to control the bandwidth and study the sensitivity of the solutions to the bandwidth. Provided a solution is bracketed closely by data points, it will tend to be stable even when the bandwidth is varied substantially. Here is an example involving datasets with 23 points (black density) and 14 points (light blue). Red vertical lines mark the solutions. The data are shown as rug plots at the bottom. The default bandwidth for these data will be around $1/2,$ as shown in the middle panel You can see from this example how one solution (the right hand one in the right panel) persists across all bandwidths. Another solution (the left hand one in the right panel) varies appreciably because data are scarce in its neighborhood. Spurious solutions pop up when using a relatively small bandwidth (left panel). These examples were created by this R code. set.seed(17) x <- rnorm(23) y <- rnorm(14, 2, 3/2) bw <- 0.25 # or 0.5, or 1.5, or even "SP", etc: see the help page for `density` obj <- intersect(x, y, kernel = "gaussian", n = 512, bw = bw, from = -4, to = 8) All kernel densities produce a discrete grid of density estimates. The solution implemented by intersect allows you to exploit the default methods of finding endpoints, bandwidths, etc by first computing a density for the combined data. Those defaults are then used to recompute the densities for the data separately. Because both densities are computed on the same grid, it's a simple matter to locate the places where they cross and interpolate linearly on the grid. Linear interpolation is more than precise enough, because it errs less than the mesh of the grid, which presumably is already small enough for your purposes. # # Find all points where density $g$ exceeds density $f.$ # intersect <- function(x, y, bw = "nrd0", from, to, ...) { # # Compute a density for all points combined. # largs <- list(x = c(x,y), bw = bw) if (!missing(from)) largs <- c(largs, from = from) if (!missing(to)) largs <- c(largs, to = to) largs <- c(largs, list(...)) obj <- do.call(density, largs) # Compute a common density # # Compute densities for the datasets separately. # x.0 <- obj$x f.x <- density(x, bw = obj$bw, from = min(x.0), to = max(x.0), ...) f.y <- density(y, bw = obj$bw, from = min(x.0), to = max(x.0), ...) # # Find the crossings. # d <- zapsmall(f.y$y - f.x$y) abscissae <- sapply(which(d[-1] * d[-length(d)] < 0), function(i) { w <- d[i+1] - d[i] if (w > 0) (d[i+1] * x.0[i] - d[i] * x.0[i+1]) / w else (x.0[i] + x.0[i+1]) / 2 }) list(Points = abscissae, xlim = range(x.0), f = f.x, g = f.y) }
identify the point of intersection from two distributions
A tiny bit of statistics is needed here, if only to point out the need to control the bandwidth and study the sensitivity of the solutions to the bandwidth. Provided a solution is bracketed closely by
identify the point of intersection from two distributions A tiny bit of statistics is needed here, if only to point out the need to control the bandwidth and study the sensitivity of the solutions to the bandwidth. Provided a solution is bracketed closely by data points, it will tend to be stable even when the bandwidth is varied substantially. Here is an example involving datasets with 23 points (black density) and 14 points (light blue). Red vertical lines mark the solutions. The data are shown as rug plots at the bottom. The default bandwidth for these data will be around $1/2,$ as shown in the middle panel You can see from this example how one solution (the right hand one in the right panel) persists across all bandwidths. Another solution (the left hand one in the right panel) varies appreciably because data are scarce in its neighborhood. Spurious solutions pop up when using a relatively small bandwidth (left panel). These examples were created by this R code. set.seed(17) x <- rnorm(23) y <- rnorm(14, 2, 3/2) bw <- 0.25 # or 0.5, or 1.5, or even "SP", etc: see the help page for `density` obj <- intersect(x, y, kernel = "gaussian", n = 512, bw = bw, from = -4, to = 8) All kernel densities produce a discrete grid of density estimates. The solution implemented by intersect allows you to exploit the default methods of finding endpoints, bandwidths, etc by first computing a density for the combined data. Those defaults are then used to recompute the densities for the data separately. Because both densities are computed on the same grid, it's a simple matter to locate the places where they cross and interpolate linearly on the grid. Linear interpolation is more than precise enough, because it errs less than the mesh of the grid, which presumably is already small enough for your purposes. # # Find all points where density $g$ exceeds density $f.$ # intersect <- function(x, y, bw = "nrd0", from, to, ...) { # # Compute a density for all points combined. # largs <- list(x = c(x,y), bw = bw) if (!missing(from)) largs <- c(largs, from = from) if (!missing(to)) largs <- c(largs, to = to) largs <- c(largs, list(...)) obj <- do.call(density, largs) # Compute a common density # # Compute densities for the datasets separately. # x.0 <- obj$x f.x <- density(x, bw = obj$bw, from = min(x.0), to = max(x.0), ...) f.y <- density(y, bw = obj$bw, from = min(x.0), to = max(x.0), ...) # # Find the crossings. # d <- zapsmall(f.y$y - f.x$y) abscissae <- sapply(which(d[-1] * d[-length(d)] < 0), function(i) { w <- d[i+1] - d[i] if (w > 0) (d[i+1] * x.0[i] - d[i] * x.0[i+1]) / w else (x.0[i] + x.0[i+1]) / 2 }) list(Points = abscissae, xlim = range(x.0), f = f.x, g = f.y) }
identify the point of intersection from two distributions A tiny bit of statistics is needed here, if only to point out the need to control the bandwidth and study the sensitivity of the solutions to the bandwidth. Provided a solution is bracketed closely by
33,560
identify the point of intersection from two distributions
Here is a crude approach to find the intersection point(s). # Generate data set.seed(12345) x <- rnorm(100) y <- rnorm(150, 1, 3) # Find global minimum and maximum xymin <- min(x,y) xymax <- max(x,y) # Estimate densities dx <- density(x, n=512, from=xymin, to=xymax) dy <- density(y, n=512, from=xymin, to=xymax) # Plot results plot(dx, xlim=c(xymin, xymax), type="l", lwd=3, xlab="X", ylab="Density", main="") lines(dy, col="red", lwd=3) # Differences in densities dx$diff <- dx$y - dy$y ex <- NULL # Store the interection points ey <- NULL k = 0 for (i in 2:length(dx$x)) { # Look for a change in sign of the difference in densities if (sign(dx$diff[i-1]) != sign(dx$diff[i])) { k = k + 1 # Linearly interpolate ex[k] <- dx$x[i-1] + (dx$x[i]-dx$x[i-1])*(0-dx$diff[i-1])/(dx$diff[i]-dx$diff[i-1]) ey[k] <- dx$y[i-1] + (dx$y[i]-dx$y[i-1])*(ex[k]-dx$x[i-1])/(dx$x[i]-dx$x[i-1]) lines(c(ex[k],ex[k]), c(0,ey[k])) points(ex[k], ey[k], pch=16, col="green" ) } } cbind(ex, ey) # ex ey #[1,] -1.957378 0.06736659 #[2,] 2.106521 0.12664663
identify the point of intersection from two distributions
Here is a crude approach to find the intersection point(s). # Generate data set.seed(12345) x <- rnorm(100) y <- rnorm(150, 1, 3) # Find global minimum and maximum xymin <- min(x,y) xymax <
identify the point of intersection from two distributions Here is a crude approach to find the intersection point(s). # Generate data set.seed(12345) x <- rnorm(100) y <- rnorm(150, 1, 3) # Find global minimum and maximum xymin <- min(x,y) xymax <- max(x,y) # Estimate densities dx <- density(x, n=512, from=xymin, to=xymax) dy <- density(y, n=512, from=xymin, to=xymax) # Plot results plot(dx, xlim=c(xymin, xymax), type="l", lwd=3, xlab="X", ylab="Density", main="") lines(dy, col="red", lwd=3) # Differences in densities dx$diff <- dx$y - dy$y ex <- NULL # Store the interection points ey <- NULL k = 0 for (i in 2:length(dx$x)) { # Look for a change in sign of the difference in densities if (sign(dx$diff[i-1]) != sign(dx$diff[i])) { k = k + 1 # Linearly interpolate ex[k] <- dx$x[i-1] + (dx$x[i]-dx$x[i-1])*(0-dx$diff[i-1])/(dx$diff[i]-dx$diff[i-1]) ey[k] <- dx$y[i-1] + (dx$y[i]-dx$y[i-1])*(ex[k]-dx$x[i-1])/(dx$x[i]-dx$x[i-1]) lines(c(ex[k],ex[k]), c(0,ey[k])) points(ex[k], ey[k], pch=16, col="green" ) } } cbind(ex, ey) # ex ey #[1,] -1.957378 0.06736659 #[2,] 2.106521 0.12664663
identify the point of intersection from two distributions Here is a crude approach to find the intersection point(s). # Generate data set.seed(12345) x <- rnorm(100) y <- rnorm(150, 1, 3) # Find global minimum and maximum xymin <- min(x,y) xymax <
33,561
Which metric to use to evaluate Quantile Regression?
Quantile regression at quantile $\tau$ has a loss function, often called "pinball loss". Let $$ l_{\tau}(y_i, \hat y_i) = \begin{cases} \tau\vert y_i - \hat y_i\vert, & y_i - \hat y_i \ge 0 \\ (1 - \tau)\vert y_i - \hat y_i\vert, & y_i - \hat y_i < 0 \end{cases} $$ Then we add up each individual $l$ to get a loss $L$ for the whole model. $$ L_{\tau}(y, \hat y) = \sum_{i=1}^n l_{\tau}(y_i, \hat y_i) $$ Use the loss function, same as you would in least squares linear regression.
Which metric to use to evaluate Quantile Regression?
Quantile regression at quantile $\tau$ has a loss function, often called "pinball loss". Let $$ l_{\tau}(y_i, \hat y_i) = \begin{cases} \tau\vert y_i - \hat y_i\vert, & y_i - \hat y_i \ge 0 \\
Which metric to use to evaluate Quantile Regression? Quantile regression at quantile $\tau$ has a loss function, often called "pinball loss". Let $$ l_{\tau}(y_i, \hat y_i) = \begin{cases} \tau\vert y_i - \hat y_i\vert, & y_i - \hat y_i \ge 0 \\ (1 - \tau)\vert y_i - \hat y_i\vert, & y_i - \hat y_i < 0 \end{cases} $$ Then we add up each individual $l$ to get a loss $L$ for the whole model. $$ L_{\tau}(y, \hat y) = \sum_{i=1}^n l_{\tau}(y_i, \hat y_i) $$ Use the loss function, same as you would in least squares linear regression.
Which metric to use to evaluate Quantile Regression? Quantile regression at quantile $\tau$ has a loss function, often called "pinball loss". Let $$ l_{\tau}(y_i, \hat y_i) = \begin{cases} \tau\vert y_i - \hat y_i\vert, & y_i - \hat y_i \ge 0 \\
33,562
Which metric to use to evaluate Quantile Regression?
@Dave's suggestion is known as the pinball loss, and it is precisely the standard loss function for quantile predictions. For references, take a look at Koenker's textbook Quantile Regression, or Gneiting (2011, "Quantiles as optimal point forecasts", IJF). We also have a number of threads here at CV. There are Python implementations in scikit-learn and TensorFlow.
Which metric to use to evaluate Quantile Regression?
@Dave's suggestion is known as the pinball loss, and it is precisely the standard loss function for quantile predictions. For references, take a look at Koenker's textbook Quantile Regression, or Gnei
Which metric to use to evaluate Quantile Regression? @Dave's suggestion is known as the pinball loss, and it is precisely the standard loss function for quantile predictions. For references, take a look at Koenker's textbook Quantile Regression, or Gneiting (2011, "Quantiles as optimal point forecasts", IJF). We also have a number of threads here at CV. There are Python implementations in scikit-learn and TensorFlow.
Which metric to use to evaluate Quantile Regression? @Dave's suggestion is known as the pinball loss, and it is precisely the standard loss function for quantile predictions. For references, take a look at Koenker's textbook Quantile Regression, or Gnei
33,563
Which metric to use to evaluate Quantile Regression?
You commented that pinball loss might be hard to interpret compared to something like $R^2$. Fortunately, we can draw an analogy to $R^2$ to get a metric that is similar. In linear regression with square loss, we are estimating the conditional mean of $y$. In the absence of any information that could explain variability in $y$ (no features), a reasonable naïve model is to predict the pooled mean of $y$ every time, so $\bar y$. This gives some kind of baseline performance to which we can compare models that want to tighten up the estimation of the conditional mean, and $R^2$ has an interpretation as this. $$ R^2=1-\dfrac{\text{ Square loss of model of interest }}{\text{ Square loss of baseline model }} $$ Do something similar with your pinball loss, where the baseline model always predicts the pooled $75$th percentile of $y$. $$ R^2=1-\dfrac{\text{ Pinball loss of model of interest }}{\text{ Pinball loss of baseline model }} $$ This idea of comparing your performance to the performance of a baseline model is used elsewhere, such as in McFadden’s $R^2$ for logistic regression.
Which metric to use to evaluate Quantile Regression?
You commented that pinball loss might be hard to interpret compared to something like $R^2$. Fortunately, we can draw an analogy to $R^2$ to get a metric that is similar. In linear regression with squ
Which metric to use to evaluate Quantile Regression? You commented that pinball loss might be hard to interpret compared to something like $R^2$. Fortunately, we can draw an analogy to $R^2$ to get a metric that is similar. In linear regression with square loss, we are estimating the conditional mean of $y$. In the absence of any information that could explain variability in $y$ (no features), a reasonable naïve model is to predict the pooled mean of $y$ every time, so $\bar y$. This gives some kind of baseline performance to which we can compare models that want to tighten up the estimation of the conditional mean, and $R^2$ has an interpretation as this. $$ R^2=1-\dfrac{\text{ Square loss of model of interest }}{\text{ Square loss of baseline model }} $$ Do something similar with your pinball loss, where the baseline model always predicts the pooled $75$th percentile of $y$. $$ R^2=1-\dfrac{\text{ Pinball loss of model of interest }}{\text{ Pinball loss of baseline model }} $$ This idea of comparing your performance to the performance of a baseline model is used elsewhere, such as in McFadden’s $R^2$ for logistic regression.
Which metric to use to evaluate Quantile Regression? You commented that pinball loss might be hard to interpret compared to something like $R^2$. Fortunately, we can draw an analogy to $R^2$ to get a metric that is similar. In linear regression with squ
33,564
Inverse transform method, theoretical graph not matching sample
This happens all the time with distributions that have infinite variance. (This one even has infinite expectation.) One or more extreme values can swamp all the others. When all values are positive, a nice solution is to plot the histogram on a log scale. Fortunately, you don't have to do the math to succeed with this. The idea is that when the probability element of your distribution is $f_X(x)\mathrm{d}x,$ on a log scale $y = \log(x)$ we have $x=e^y,$ so the probability element becomes $$f_Y(y)\mathrm{d}y = f_X\left(e^y\right)\,\mathrm{d}e^y = f_X\left(e^y\right)e^y\,\mathrm{d}y.$$ Notice this involves only (a) evaluating $f_X$ at $e^y$ and (b) multiplying that by $e^y.$ The changes to the code--which work in all such cases, regardless of $f$--are Make a histogram of the logarithms of the data. hist(log(x), prob = TRUE, main = bquote(f(x)==1/(1+x)^2), breaks=50, col=gray(.9)) Overplot it with the adjusted function $f_Y:$ f <- function(x) 1 / (1+x)^2 # The original density function curve(f(exp(y)) * exp(y), add=TRUE, n=201, xname="y", lwd=2, col="Red") You can get a little fancier with (1) if you like. Here is a version of it with with the values shown on the axis rather than their logarithms. If you prefer this style, here's some R code for step (1) to get you started. hist(log(x), prob = TRUE, main = bquote(f(x)==1/(1+x)^2), breaks=50, col=gray(.9), xaxt="n", xlab="Value") i <- floor(range(log10(x))) xlab <- seq(min(i), max(i))[-1] rug(xlab * log(10)) for (x in xlab) mtext(bquote(10^.(x)), side=1, line=1/2, at=x * log(10)) An alternative approach is to break the histogram up into two or more pieces. Use a high quantile for a flexible choice; or inspect the initial histogram and choose the threshold(s) for splitting the data by eye. Watch out for a pitfall: when you feed only a part of the data to hist, it overestimates the densities. Multiply the densities by the fraction of data being shown. The code demonstrates how to do that in R: save the output of hist and simply scale its densities (making no other changes), and only then plot this object. The code is starting to get a little fussy, though: alpha <- 0.02 threshold <- quantile(x, 1 - alpha) par(mfrow=c(1,2)) h <- hist(x[x <= threshold], breaks=50, plot=FALSE) # h$density <- h$density * (1-alpha) plot(h, freq=FALSE, main = bquote(f(x)==1/(1+x)^2), col=gray(.9), xlab="Value", sub=bquote(paste("The highest ", .(signif(100*alpha, 2)), "% of data are not shown"))) curve(f(x), add=TRUE, col="Red", lwd=2) h <- hist(x[x > threshold], breaks=seq(threshold, max(x), length.out=21), plot=FALSE) h$density <- h$density * alpha plot(h, freq=FALSE, main = bquote(f(x)==1/(1+x)^2), col=gray(.9), xlab="Value", sub=bquote(paste("Only the highest ", .(signif(100*alpha, 2)), "% of data are shown"))) curve(f(x), add=TRUE, col="Red", lwd=2) par(mfrow=c(1,1)) It can be interesting to use variable-width bins. This method can be combined with the previous ones. Here is an example of the lower part of the data. I broke the data by quantiles for this one. Again, the densities have to be adjusted when a subset of the data is being plotted. b <- quantile(x, seq(0, 1, length.out=21)) k <- 2 n <- length(b)-k h <- hist(x[x <= b[n]], plot=FALSE, breaks=b[-(n + seq_len(k))]) q <- sum(x <= b[n]) / length(x) h$density <- h$density * q plot(h, main = bquote(f(x)==1/(1+x)^2), col=gray(.9), xlab="Value", sub=bquote(paste("Only the lowest ", .(signif(100*q, 2)), "% of data are shown"))) curve(f(x), add=TRUE, col="Red", lwd=2)
Inverse transform method, theoretical graph not matching sample
This happens all the time with distributions that have infinite variance. (This one even has infinite expectation.) One or more extreme values can swamp all the others. When all values are positive,
Inverse transform method, theoretical graph not matching sample This happens all the time with distributions that have infinite variance. (This one even has infinite expectation.) One or more extreme values can swamp all the others. When all values are positive, a nice solution is to plot the histogram on a log scale. Fortunately, you don't have to do the math to succeed with this. The idea is that when the probability element of your distribution is $f_X(x)\mathrm{d}x,$ on a log scale $y = \log(x)$ we have $x=e^y,$ so the probability element becomes $$f_Y(y)\mathrm{d}y = f_X\left(e^y\right)\,\mathrm{d}e^y = f_X\left(e^y\right)e^y\,\mathrm{d}y.$$ Notice this involves only (a) evaluating $f_X$ at $e^y$ and (b) multiplying that by $e^y.$ The changes to the code--which work in all such cases, regardless of $f$--are Make a histogram of the logarithms of the data. hist(log(x), prob = TRUE, main = bquote(f(x)==1/(1+x)^2), breaks=50, col=gray(.9)) Overplot it with the adjusted function $f_Y:$ f <- function(x) 1 / (1+x)^2 # The original density function curve(f(exp(y)) * exp(y), add=TRUE, n=201, xname="y", lwd=2, col="Red") You can get a little fancier with (1) if you like. Here is a version of it with with the values shown on the axis rather than their logarithms. If you prefer this style, here's some R code for step (1) to get you started. hist(log(x), prob = TRUE, main = bquote(f(x)==1/(1+x)^2), breaks=50, col=gray(.9), xaxt="n", xlab="Value") i <- floor(range(log10(x))) xlab <- seq(min(i), max(i))[-1] rug(xlab * log(10)) for (x in xlab) mtext(bquote(10^.(x)), side=1, line=1/2, at=x * log(10)) An alternative approach is to break the histogram up into two or more pieces. Use a high quantile for a flexible choice; or inspect the initial histogram and choose the threshold(s) for splitting the data by eye. Watch out for a pitfall: when you feed only a part of the data to hist, it overestimates the densities. Multiply the densities by the fraction of data being shown. The code demonstrates how to do that in R: save the output of hist and simply scale its densities (making no other changes), and only then plot this object. The code is starting to get a little fussy, though: alpha <- 0.02 threshold <- quantile(x, 1 - alpha) par(mfrow=c(1,2)) h <- hist(x[x <= threshold], breaks=50, plot=FALSE) # h$density <- h$density * (1-alpha) plot(h, freq=FALSE, main = bquote(f(x)==1/(1+x)^2), col=gray(.9), xlab="Value", sub=bquote(paste("The highest ", .(signif(100*alpha, 2)), "% of data are not shown"))) curve(f(x), add=TRUE, col="Red", lwd=2) h <- hist(x[x > threshold], breaks=seq(threshold, max(x), length.out=21), plot=FALSE) h$density <- h$density * alpha plot(h, freq=FALSE, main = bquote(f(x)==1/(1+x)^2), col=gray(.9), xlab="Value", sub=bquote(paste("Only the highest ", .(signif(100*alpha, 2)), "% of data are shown"))) curve(f(x), add=TRUE, col="Red", lwd=2) par(mfrow=c(1,1)) It can be interesting to use variable-width bins. This method can be combined with the previous ones. Here is an example of the lower part of the data. I broke the data by quantiles for this one. Again, the densities have to be adjusted when a subset of the data is being plotted. b <- quantile(x, seq(0, 1, length.out=21)) k <- 2 n <- length(b)-k h <- hist(x[x <= b[n]], plot=FALSE, breaks=b[-(n + seq_len(k))]) q <- sum(x <= b[n]) / length(x) h$density <- h$density * q plot(h, main = bquote(f(x)==1/(1+x)^2), col=gray(.9), xlab="Value", sub=bquote(paste("Only the lowest ", .(signif(100*q, 2)), "% of data are shown"))) curve(f(x), add=TRUE, col="Red", lwd=2)
Inverse transform method, theoretical graph not matching sample This happens all the time with distributions that have infinite variance. (This one even has infinite expectation.) One or more extreme values can swamp all the others. When all values are positive,
33,565
Inverse transform method, theoretical graph not matching sample
I don't see anything wrong with the implementation of the inverse transform method. The first distribution is strongly right-skewed. If you run your simulation, you should see that roughly 95% of observations will be smaller than 19 (=0.95/0.05), but the largest sample is typically much larger, say a few thousand. So, most samples are small, but there is a small probability of very large samples. The bars on a histogram have a fixed width, so you end up with the first bar containing most observations, and then several other bars on the right that are just tiny slivers of rectangles. For this specific distribution, since the support is the positive real numbers, you could plot the histogram on a log scale to see it better, but you'll need to derive the transformed density. If $X$ has density: $$f_X(x) = \frac{1}{(1+x)^2}, \quad x \geq 0$$ Then you can check that $Y := \log(X)$ has density: $$f_Y(y) = \frac{e^y}{(1+e^y)^2}, y \in \mathbb{R}$$ Then if you plot it: hist(log(x), prob = TRUE, main = "Histogram for Y", xlab = "Y") z <- seq(-10,10,length.out = 100) lines(z, (exp(z)/(1+exp(z))^2)) You can see that they are in fairly good agreement. For reference, the distribution of $Y$ is called the logistic distribution, and $X$ has the log-logistic distribution.
Inverse transform method, theoretical graph not matching sample
I don't see anything wrong with the implementation of the inverse transform method. The first distribution is strongly right-skewed. If you run your simulation, you should see that roughly 95% of obse
Inverse transform method, theoretical graph not matching sample I don't see anything wrong with the implementation of the inverse transform method. The first distribution is strongly right-skewed. If you run your simulation, you should see that roughly 95% of observations will be smaller than 19 (=0.95/0.05), but the largest sample is typically much larger, say a few thousand. So, most samples are small, but there is a small probability of very large samples. The bars on a histogram have a fixed width, so you end up with the first bar containing most observations, and then several other bars on the right that are just tiny slivers of rectangles. For this specific distribution, since the support is the positive real numbers, you could plot the histogram on a log scale to see it better, but you'll need to derive the transformed density. If $X$ has density: $$f_X(x) = \frac{1}{(1+x)^2}, \quad x \geq 0$$ Then you can check that $Y := \log(X)$ has density: $$f_Y(y) = \frac{e^y}{(1+e^y)^2}, y \in \mathbb{R}$$ Then if you plot it: hist(log(x), prob = TRUE, main = "Histogram for Y", xlab = "Y") z <- seq(-10,10,length.out = 100) lines(z, (exp(z)/(1+exp(z))^2)) You can see that they are in fairly good agreement. For reference, the distribution of $Y$ is called the logistic distribution, and $X$ has the log-logistic distribution.
Inverse transform method, theoretical graph not matching sample I don't see anything wrong with the implementation of the inverse transform method. The first distribution is strongly right-skewed. If you run your simulation, you should see that roughly 95% of obse
33,566
Order of variables in R's lm
Differences due to type I/II/III sums The order is not important for the summary of the linear model (which is based on t-tests that don't change). You can see this in your output which is the same. However when you do an ANOVA then you might get different results depending on the order (this happens for type I sums) > anova(lm(a~c+b+d)) Analysis of Variance Table Response: a Df Sum Sq Mean Sq F value Pr(>F) c 1 82067 82067 3412.9019 < 2.2e-16 *** b 1 494 494 20.5397 1.683e-05 *** d 1 77 77 3.1872 0.07738 . Residuals 96 2308 24 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 > anova(lm(a~b+c+d)) Analysis of Variance Table Response: a Df Sum Sq Mean Sq F value Pr(>F) b 1 82146 82146 3416.2075 < 2.2e-16 *** c 1 414 414 17.2341 7.155e-05 *** d 1 77 77 3.1872 0.07738 . Residuals 96 2308 24 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 > Note the different p-values for the factors b and c. The reason is that ANOVA is a comparison of models and there are different ways to interpret this comparison (see type I/II/III sums). The standard anova function is performing the models in a cascading way, dropping terms one by one starting from the back. Those are type I sums It goes a bit like this (but slightly different F-scores because the degrees of freedom are computed differently) anova(lm(a~1+b+c), lm(a~1+b+c+d)) # testing the effect of d anova(lm(a~1+b ), lm(a~1+b+c )) # testing the effect of c anova(lm(a~1 ), lm(a~1+b )) # testing the effect of b The t-scores and the related p-values (from the summary of the lm function) relate to the F-test/ANOVA in the case of type III sums, which is dropping terms relative to the full model (and that is why the order doesn't matter for the t-test) anova(lm(a~1+b+c), lm(a~1+b+c+d)) # testing the effect of d anova(lm(a~1+b+d), lm(a~1+b+c+d)) # testing the effect of c anova(lm(a~1+c+d), lm(a~1+b+c+d)) # testing the effect of b This can also be done with the drop1 function > drop1(lm(a~b+c+d), test = "F") Single term deletions Model: a ~ b + c + d Df Sum of Sq RSS AIC F value Pr(>F) <none> 2308.4 321.92 b 1 232.725 2541.2 329.52 9.6783 0.002456 ** c 1 147.721 2456.2 326.12 6.1433 0.014937 * d 1 76.639 2385.1 323.18 3.1872 0.077377 . --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Differences due to the position of the intercept In the referenced question the reason for the impact of the order is due to the position of the intercept. In that question, the intercept is explicitly excluded from the model, but indirectly it is still part of the model because the categorical variables often add up to one. In that case, the intercept is placed for whichever variable and factor level is first in the order. An illustrative problems that shows how the factors of $n$ levels are only fitted with $n-1$ coefficients and one term gets absorbed into the intercept is: Fitting a Logistic Regression Without an Intercept . In that problem you see that the person who ask's the questions tries to get rid of this 'dropping of one level for each factor' by not using an intercept. But this only works for one factor. The factor for which this works is the one which is the beginning of the model. A more silly example is: Why do output coefficients not resemble true coefficients in a linear model? In that particular example pay especially attention to the nls model where the dropping of the first level of each factor must be done explicitly modelnls2 <- nls(Y ~ exp(a + c(0,b1,b2)[Home] + c(0,c1)[Gender] + c(0,d1,d2)[Rank]), start = c(a=1,b1=1,b2=1,c1=1,d1=1,d2=1), data=dune) For each of the factors (Home, Gender, Rank), the related coefficients are set explicitly at 0 for one of the levels. If you would take away the intercept coefficient a then you could add it to one of the others. For instance: modelnls2 <- nls(Y ~ exp(c(a,b1+a,b2+a)[Home] + c(0,c1)[Gender] + c(0,d1,d2)[Rank]), start = c(a=1,b1=1,b2=1,c1=1,d1=1,d2=1), data=dune) ### or equivalent modelnls2 <- nls(Y ~ exp(c(a,b1,b2)[Home] + c(0,c1)[Gender] + c(0,d1,d2)[Rank]), start = c(a=1,b1=1,b2=1,c1=1,d1=1,d2=1), data=dune) This is what happens with the lm function for the referenced question and is the reason why the order matters.
Order of variables in R's lm
Differences due to type I/II/III sums The order is not important for the summary of the linear model (which is based on t-tests that don't change). You can see this in your output which is the same. H
Order of variables in R's lm Differences due to type I/II/III sums The order is not important for the summary of the linear model (which is based on t-tests that don't change). You can see this in your output which is the same. However when you do an ANOVA then you might get different results depending on the order (this happens for type I sums) > anova(lm(a~c+b+d)) Analysis of Variance Table Response: a Df Sum Sq Mean Sq F value Pr(>F) c 1 82067 82067 3412.9019 < 2.2e-16 *** b 1 494 494 20.5397 1.683e-05 *** d 1 77 77 3.1872 0.07738 . Residuals 96 2308 24 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 > anova(lm(a~b+c+d)) Analysis of Variance Table Response: a Df Sum Sq Mean Sq F value Pr(>F) b 1 82146 82146 3416.2075 < 2.2e-16 *** c 1 414 414 17.2341 7.155e-05 *** d 1 77 77 3.1872 0.07738 . Residuals 96 2308 24 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 > Note the different p-values for the factors b and c. The reason is that ANOVA is a comparison of models and there are different ways to interpret this comparison (see type I/II/III sums). The standard anova function is performing the models in a cascading way, dropping terms one by one starting from the back. Those are type I sums It goes a bit like this (but slightly different F-scores because the degrees of freedom are computed differently) anova(lm(a~1+b+c), lm(a~1+b+c+d)) # testing the effect of d anova(lm(a~1+b ), lm(a~1+b+c )) # testing the effect of c anova(lm(a~1 ), lm(a~1+b )) # testing the effect of b The t-scores and the related p-values (from the summary of the lm function) relate to the F-test/ANOVA in the case of type III sums, which is dropping terms relative to the full model (and that is why the order doesn't matter for the t-test) anova(lm(a~1+b+c), lm(a~1+b+c+d)) # testing the effect of d anova(lm(a~1+b+d), lm(a~1+b+c+d)) # testing the effect of c anova(lm(a~1+c+d), lm(a~1+b+c+d)) # testing the effect of b This can also be done with the drop1 function > drop1(lm(a~b+c+d), test = "F") Single term deletions Model: a ~ b + c + d Df Sum of Sq RSS AIC F value Pr(>F) <none> 2308.4 321.92 b 1 232.725 2541.2 329.52 9.6783 0.002456 ** c 1 147.721 2456.2 326.12 6.1433 0.014937 * d 1 76.639 2385.1 323.18 3.1872 0.077377 . --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Differences due to the position of the intercept In the referenced question the reason for the impact of the order is due to the position of the intercept. In that question, the intercept is explicitly excluded from the model, but indirectly it is still part of the model because the categorical variables often add up to one. In that case, the intercept is placed for whichever variable and factor level is first in the order. An illustrative problems that shows how the factors of $n$ levels are only fitted with $n-1$ coefficients and one term gets absorbed into the intercept is: Fitting a Logistic Regression Without an Intercept . In that problem you see that the person who ask's the questions tries to get rid of this 'dropping of one level for each factor' by not using an intercept. But this only works for one factor. The factor for which this works is the one which is the beginning of the model. A more silly example is: Why do output coefficients not resemble true coefficients in a linear model? In that particular example pay especially attention to the nls model where the dropping of the first level of each factor must be done explicitly modelnls2 <- nls(Y ~ exp(a + c(0,b1,b2)[Home] + c(0,c1)[Gender] + c(0,d1,d2)[Rank]), start = c(a=1,b1=1,b2=1,c1=1,d1=1,d2=1), data=dune) For each of the factors (Home, Gender, Rank), the related coefficients are set explicitly at 0 for one of the levels. If you would take away the intercept coefficient a then you could add it to one of the others. For instance: modelnls2 <- nls(Y ~ exp(c(a,b1+a,b2+a)[Home] + c(0,c1)[Gender] + c(0,d1,d2)[Rank]), start = c(a=1,b1=1,b2=1,c1=1,d1=1,d2=1), data=dune) ### or equivalent modelnls2 <- nls(Y ~ exp(c(a,b1,b2)[Home] + c(0,c1)[Gender] + c(0,d1,d2)[Rank]), start = c(a=1,b1=1,b2=1,c1=1,d1=1,d2=1), data=dune) This is what happens with the lm function for the referenced question and is the reason why the order matters.
Order of variables in R's lm Differences due to type I/II/III sums The order is not important for the summary of the linear model (which is based on t-tests that don't change). You can see this in your output which is the same. H
33,567
Order of variables in R's lm
The two models you fitted are exactly the same. The results are shown in the order you have entered them into R. The only 'difference' as such is that the rows for b and c have been swapped over, but the p-values, estimates and so on are identical > summary(lm(a~c+b+d)) Call: lm(formula = a ~ c + b + d) Residuals: Min 1Q Median 3Q Max -10.6989 -3.4114 -0.0175 3.4746 12.1792 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.8080 0.9928 0.814 0.41778 c 0.3388 0.1367 2.479 0.01494 * b 40.5137 13.0228 3.111 0.00246 ** d 0.2504 0.1402 1.785 0.07738 . > summary(lm(a~b+c+d)) Call: lm(formula = a ~ b + c + d) Residuals: Min 1Q Median 3Q Max -10.6989 -3.4114 -0.0175 3.4746 12.1792 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.8080 0.9928 0.814 0.41778 b 40.5137 13.0228 3.111 0.00246 ** c 0.3388 0.1367 2.479 0.01494 * d 0.2504 0.1402 1.785 0.07738 . ```
Order of variables in R's lm
The two models you fitted are exactly the same. The results are shown in the order you have entered them into R. The only 'difference' as such is that the rows for b and c have been swapped over, but
Order of variables in R's lm The two models you fitted are exactly the same. The results are shown in the order you have entered them into R. The only 'difference' as such is that the rows for b and c have been swapped over, but the p-values, estimates and so on are identical > summary(lm(a~c+b+d)) Call: lm(formula = a ~ c + b + d) Residuals: Min 1Q Median 3Q Max -10.6989 -3.4114 -0.0175 3.4746 12.1792 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.8080 0.9928 0.814 0.41778 c 0.3388 0.1367 2.479 0.01494 * b 40.5137 13.0228 3.111 0.00246 ** d 0.2504 0.1402 1.785 0.07738 . > summary(lm(a~b+c+d)) Call: lm(formula = a ~ b + c + d) Residuals: Min 1Q Median 3Q Max -10.6989 -3.4114 -0.0175 3.4746 12.1792 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.8080 0.9928 0.814 0.41778 b 40.5137 13.0228 3.111 0.00246 ** c 0.3388 0.1367 2.479 0.01494 * d 0.2504 0.1402 1.785 0.07738 . ```
Order of variables in R's lm The two models you fitted are exactly the same. The results are shown in the order you have entered them into R. The only 'difference' as such is that the rows for b and c have been swapped over, but
33,568
Order of variables in R's lm
Here is a more formal answer (more elegant proofs that start with something like "consider the space spanned by the columns of $X$..." are surely possible) to the question of why just changing the order of the regressors does not matter. As I sketch at the end, the question you link to deals with a case where more than just permuting the columns is happening (as the accepted answer there, I believe, also explains quite well). Consider changing the position of the variables in the $(n\times p)$ regressor matrix $$ X=(X_1,\ldots,X_p), $$ where $X_j=(x_{1j},\ldots,x_{nj})'$, $j=1,\ldots,p$, amounts to postmultiplying $X$ with a $(p\times p)$ permutation matrix $P$ that has a single entry 1 in each column $j$ that indicates the new column position of that regressor $X_j$. For example, if the new columns are to be the old columns 2, 1 and 3, we have $$P=\begin{pmatrix} 0&1&0\\ 1&0&0\\ 0&0&1 \end{pmatrix}$$ This matrix $P$ is invertible, being just a permuted version of the identity matrix. Also, as it is easy to check that $P'P=I$, $P^{-1}$ is equal to the transpose of $P$, $P^{-1}=P'$. Thus, the OLS coefficient of the regression of $y$ on the transformed regressors, call it $\hat\beta_t$, is \begin{eqnarray*} \hat\beta_t&=&((XP)'XP)^{-1}(XP)'y\\ &\stackrel{(AB)'=B'A'}{=}&(P'X'XP)^{-1}P'X'y\\ &\stackrel{(ABC)^{-1}=C^{-1}B^{-1}A^{-1}}{=}&P^{-1}(X'X)^{-1}\underbrace{(P')^{-1}P'}_{=I}X'y\\ &=&P^{-1}(X'X)^{-1}X'y\\ &=&P'(X'X)^{-1}X'y\\ &=&P'\hat\beta\\ \end{eqnarray*} Here, $P'$ is a matrix that permutes the row elements of $\hat\beta$, and hence permutes the entries of the original coeffient estimator $\hat\beta$ according to the permutation of the columns. To see why the question you link to addresses a slightly different situation in which something else happens than just permuting the columns, I suggest to inspect model.matrix(out_1) and model.matrix(out_2) in that code, which gives you the different regressor matrices in the two models.
Order of variables in R's lm
Here is a more formal answer (more elegant proofs that start with something like "consider the space spanned by the columns of $X$..." are surely possible) to the question of why just changing the ord
Order of variables in R's lm Here is a more formal answer (more elegant proofs that start with something like "consider the space spanned by the columns of $X$..." are surely possible) to the question of why just changing the order of the regressors does not matter. As I sketch at the end, the question you link to deals with a case where more than just permuting the columns is happening (as the accepted answer there, I believe, also explains quite well). Consider changing the position of the variables in the $(n\times p)$ regressor matrix $$ X=(X_1,\ldots,X_p), $$ where $X_j=(x_{1j},\ldots,x_{nj})'$, $j=1,\ldots,p$, amounts to postmultiplying $X$ with a $(p\times p)$ permutation matrix $P$ that has a single entry 1 in each column $j$ that indicates the new column position of that regressor $X_j$. For example, if the new columns are to be the old columns 2, 1 and 3, we have $$P=\begin{pmatrix} 0&1&0\\ 1&0&0\\ 0&0&1 \end{pmatrix}$$ This matrix $P$ is invertible, being just a permuted version of the identity matrix. Also, as it is easy to check that $P'P=I$, $P^{-1}$ is equal to the transpose of $P$, $P^{-1}=P'$. Thus, the OLS coefficient of the regression of $y$ on the transformed regressors, call it $\hat\beta_t$, is \begin{eqnarray*} \hat\beta_t&=&((XP)'XP)^{-1}(XP)'y\\ &\stackrel{(AB)'=B'A'}{=}&(P'X'XP)^{-1}P'X'y\\ &\stackrel{(ABC)^{-1}=C^{-1}B^{-1}A^{-1}}{=}&P^{-1}(X'X)^{-1}\underbrace{(P')^{-1}P'}_{=I}X'y\\ &=&P^{-1}(X'X)^{-1}X'y\\ &=&P'(X'X)^{-1}X'y\\ &=&P'\hat\beta\\ \end{eqnarray*} Here, $P'$ is a matrix that permutes the row elements of $\hat\beta$, and hence permutes the entries of the original coeffient estimator $\hat\beta$ according to the permutation of the columns. To see why the question you link to addresses a slightly different situation in which something else happens than just permuting the columns, I suggest to inspect model.matrix(out_1) and model.matrix(out_2) in that code, which gives you the different regressor matrices in the two models.
Order of variables in R's lm Here is a more formal answer (more elegant proofs that start with something like "consider the space spanned by the columns of $X$..." are surely possible) to the question of why just changing the ord
33,569
Order of variables in R's lm
Couple of additional points. your understanding of the calculation process is incorrect. My own guess is that the model first calculates the effect of first variable, and then uses the second variable for remaining variation in dependent variable and so on. No, Linear Regression calculating all the coefficients at the same time, but one by one. In R, lm is using QR decomposition. And changing the order is just switching columns in the matrix. When people say, order of the variable it may mean "Coding Systems for Categorical Variables in Regression" and reference level for categorical Variables. For example if you are fitting a regression model, and one of the variable is education level. (high school, bachelor, master), If the reference level is different. Then the coefficient will be different.
Order of variables in R's lm
Couple of additional points. your understanding of the calculation process is incorrect. My own guess is that the model first calculates the effect of first variable, and then uses the second varia
Order of variables in R's lm Couple of additional points. your understanding of the calculation process is incorrect. My own guess is that the model first calculates the effect of first variable, and then uses the second variable for remaining variation in dependent variable and so on. No, Linear Regression calculating all the coefficients at the same time, but one by one. In R, lm is using QR decomposition. And changing the order is just switching columns in the matrix. When people say, order of the variable it may mean "Coding Systems for Categorical Variables in Regression" and reference level for categorical Variables. For example if you are fitting a regression model, and one of the variable is education level. (high school, bachelor, master), If the reference level is different. Then the coefficient will be different.
Order of variables in R's lm Couple of additional points. your understanding of the calculation process is incorrect. My own guess is that the model first calculates the effect of first variable, and then uses the second varia
33,570
Binomial glmer() singular despite "lots" of data
A further comment: I took a look at your data, and it's clear, again, that there is no evidence of systematic variance between the different channels. This is why the mixed model estimates the between-channel variance to be $0$, making the model singular. You can see this in the figure below, where the standard errors for almost every channel overlap... ...and can confirm it by ANOVA decomposition of a fixed-effects GLM, showing that there is no significant main effect of Channel (p = .986). m_fixed_effects = glm(cbind(n, total) ~ Pedra + factor(Channel), data=positive, family=binomial) car::Anova(m_fixed_effects) # Analysis of Deviance Table (Type II tests) # # Response: cbind(n, total) # LR Chisq Df Pr(>Chisq) # Pedra 4.9148 1 0.02663 * # factor(Channel) 1.3859 7 0.98600 # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Code library(tidyverse) df = read.csv('/path/to/reaction.csv') head(df) # Channel Pedra reaction n # 1 1 No 0 6 # 2 1 No 1 7 # 3 1 Yes 0 3 # 4 1 Yes 1 10 # 5 2 No 0 7 # 6 2 No 1 7 df = df %>% group_by(Channel, Pedra) %>% mutate(total = sum(n), prop = n / total, se = sqrt((prop * (1-prop)) / n)) %>% ungroup() positive = filter(df, reaction==1) ggplot(positive, aes(Pedra, prop, group=Channel, color=factor(Channel))) + geom_path(position = position_dodge(width=.1)) + geom_point(position = position_dodge(width=.1)) + stat_summary(fun.data=mean_se, group=1, color='black', position = position_nudge(x=c(-.2, .2))) + geom_linerange(mapping=aes(ymin=prop-se, ymax=prop+se), position = position_dodge(width=.1)) + geom_hline(linetype='dashed', yintercept=.5) + coord_cartesian(ylim=c(0, 1)) + labs(color='Channel', y='Proportion positive reactions', caption='Error bars show SEM') m_fixed_effects = glm(cbind(n, total) ~ Pedra + factor(Channel), data=positive, family=binomial) car::Anova(m_fixed_effects) # Analysis of Deviance Table (Type II tests) # # Response: cbind(n, total) # LR Chisq Df Pr(>Chisq) # Pedra 4.9148 1 0.02663 * # factor(Channel) 1.3859 7 0.98600 # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Binomial glmer() singular despite "lots" of data
A further comment: I took a look at your data, and it's clear, again, that there is no evidence of systematic variance between the different channels. This is why the mixed model estimates the between
Binomial glmer() singular despite "lots" of data A further comment: I took a look at your data, and it's clear, again, that there is no evidence of systematic variance between the different channels. This is why the mixed model estimates the between-channel variance to be $0$, making the model singular. You can see this in the figure below, where the standard errors for almost every channel overlap... ...and can confirm it by ANOVA decomposition of a fixed-effects GLM, showing that there is no significant main effect of Channel (p = .986). m_fixed_effects = glm(cbind(n, total) ~ Pedra + factor(Channel), data=positive, family=binomial) car::Anova(m_fixed_effects) # Analysis of Deviance Table (Type II tests) # # Response: cbind(n, total) # LR Chisq Df Pr(>Chisq) # Pedra 4.9148 1 0.02663 * # factor(Channel) 1.3859 7 0.98600 # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Code library(tidyverse) df = read.csv('/path/to/reaction.csv') head(df) # Channel Pedra reaction n # 1 1 No 0 6 # 2 1 No 1 7 # 3 1 Yes 0 3 # 4 1 Yes 1 10 # 5 2 No 0 7 # 6 2 No 1 7 df = df %>% group_by(Channel, Pedra) %>% mutate(total = sum(n), prop = n / total, se = sqrt((prop * (1-prop)) / n)) %>% ungroup() positive = filter(df, reaction==1) ggplot(positive, aes(Pedra, prop, group=Channel, color=factor(Channel))) + geom_path(position = position_dodge(width=.1)) + geom_point(position = position_dodge(width=.1)) + stat_summary(fun.data=mean_se, group=1, color='black', position = position_nudge(x=c(-.2, .2))) + geom_linerange(mapping=aes(ymin=prop-se, ymax=prop+se), position = position_dodge(width=.1)) + geom_hline(linetype='dashed', yintercept=.5) + coord_cartesian(ylim=c(0, 1)) + labs(color='Channel', y='Proportion positive reactions', caption='Error bars show SEM') m_fixed_effects = glm(cbind(n, total) ~ Pedra + factor(Channel), data=positive, family=binomial) car::Anova(m_fixed_effects) # Analysis of Deviance Table (Type II tests) # # Response: cbind(n, total) # LR Chisq Df Pr(>Chisq) # Pedra 4.9148 1 0.02663 * # factor(Channel) 1.3859 7 0.98600 # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Binomial glmer() singular despite "lots" of data A further comment: I took a look at your data, and it's clear, again, that there is no evidence of systematic variance between the different channels. This is why the mixed model estimates the between
33,571
Binomial glmer() singular despite "lots" of data
Isabella made some excellent points. This can also happen when there is very little variation at the channel level. Perhaps channels are just very similar to each other so their variance really is close to zero and therefore not needed in the model. You can assess this by fitting a glm and see if the inferences are similar.
Binomial glmer() singular despite "lots" of data
Isabella made some excellent points. This can also happen when there is very little variation at the channel level. Perhaps channels are just very similar to each other so their variance really is cl
Binomial glmer() singular despite "lots" of data Isabella made some excellent points. This can also happen when there is very little variation at the channel level. Perhaps channels are just very similar to each other so their variance really is close to zero and therefore not needed in the model. You can assess this by fitting a glm and see if the inferences are similar.
Binomial glmer() singular despite "lots" of data Isabella made some excellent points. This can also happen when there is very little variation at the channel level. Perhaps channels are just very similar to each other so their variance really is cl
33,572
Binomial glmer() singular despite "lots" of data
Because this is a mixed effects binary logistic regression model, it assumes that your outcome variable is binary with values coded as either 0 or 1. What you need to investigate is whether you have enough 1's present in your response variable for a sufficient number of 'subjects'. (In your case, subject stands for channel.) Here is a made-up example which produces the same warning as wnat you got: SubjectID <- rep(1:5, each = 3) SubjectID Outcome <- rep(0, 15) Outcome[1] <- 1 Data <- data.frame(Outcome, SubjectID) str(Data) Data library(lme4) glmer(Outcome ~ 1 + (1|SubjectID), family="binomial", data = Data) In this example, there are 5 subjects such that 4 of them have only 0 outcome values and one of them has outcome values which include a single value of 1. (Each subject has 3 outcome values in total.) Even if you give each of the subject in this made-up example a value of 1 for their first outcome value, you will still get the same error message when fitting the model: Outcome <- rep(0, 15) Outcome[c(1, 4, 7, 10, 13)] <- 1 However, if all 4 subjects who initially had only 0 values are allowed to keep these values and the first subject receives two values of 1, the error message disappears: Outcome <- rep(0, 15) Outcome[c(1,2)] <- 1 Once you understand better the pattern of 0 and 1 values for the outcome variable among your study subjects, the other thing you can try is fitting your model with the mixed_model() function from the GLMMadaptive package in R. For the small example provided here, this function would be used like this: library(GLMMadaptive) m <- mixed_model(fixed = Outcome ~ 1, random = ~ 1 | SubjectID, data = Data, family = binomial()) summary(m)
Binomial glmer() singular despite "lots" of data
Because this is a mixed effects binary logistic regression model, it assumes that your outcome variable is binary with values coded as either 0 or 1. What you need to investigate is whether you have e
Binomial glmer() singular despite "lots" of data Because this is a mixed effects binary logistic regression model, it assumes that your outcome variable is binary with values coded as either 0 or 1. What you need to investigate is whether you have enough 1's present in your response variable for a sufficient number of 'subjects'. (In your case, subject stands for channel.) Here is a made-up example which produces the same warning as wnat you got: SubjectID <- rep(1:5, each = 3) SubjectID Outcome <- rep(0, 15) Outcome[1] <- 1 Data <- data.frame(Outcome, SubjectID) str(Data) Data library(lme4) glmer(Outcome ~ 1 + (1|SubjectID), family="binomial", data = Data) In this example, there are 5 subjects such that 4 of them have only 0 outcome values and one of them has outcome values which include a single value of 1. (Each subject has 3 outcome values in total.) Even if you give each of the subject in this made-up example a value of 1 for their first outcome value, you will still get the same error message when fitting the model: Outcome <- rep(0, 15) Outcome[c(1, 4, 7, 10, 13)] <- 1 However, if all 4 subjects who initially had only 0 values are allowed to keep these values and the first subject receives two values of 1, the error message disappears: Outcome <- rep(0, 15) Outcome[c(1,2)] <- 1 Once you understand better the pattern of 0 and 1 values for the outcome variable among your study subjects, the other thing you can try is fitting your model with the mixed_model() function from the GLMMadaptive package in R. For the small example provided here, this function would be used like this: library(GLMMadaptive) m <- mixed_model(fixed = Outcome ~ 1, random = ~ 1 | SubjectID, data = Data, family = binomial()) summary(m)
Binomial glmer() singular despite "lots" of data Because this is a mixed effects binary logistic regression model, it assumes that your outcome variable is binary with values coded as either 0 or 1. What you need to investigate is whether you have e
33,573
Binomial glmer() singular despite "lots" of data
Out of curiosity, does the error arise when you use an alternative estimator? It could be that the estimator is for some reason getting stuck at a singularity. You may just try the following: mod.alt_est <- allFit(mod.detection_rand). Alternatively, you may need a Bayesian solution to help regularize the estimation and force it away from a singularity (try blme package if the allFit function doesn't produce an estimator that works).
Binomial glmer() singular despite "lots" of data
Out of curiosity, does the error arise when you use an alternative estimator? It could be that the estimator is for some reason getting stuck at a singularity. You may just try the following: mod.alt_
Binomial glmer() singular despite "lots" of data Out of curiosity, does the error arise when you use an alternative estimator? It could be that the estimator is for some reason getting stuck at a singularity. You may just try the following: mod.alt_est <- allFit(mod.detection_rand). Alternatively, you may need a Bayesian solution to help regularize the estimation and force it away from a singularity (try blme package if the allFit function doesn't produce an estimator that works).
Binomial glmer() singular despite "lots" of data Out of curiosity, does the error arise when you use an alternative estimator? It could be that the estimator is for some reason getting stuck at a singularity. You may just try the following: mod.alt_
33,574
Is it mandatory to subset your data to validate a model?
To start, I would suggest that it is usually good to be wary of statements that there is only one way to do something. Splitting an obtained sample into a "training" and a "testing" data set is a common approach in many machine learning/data science applications. Oftentimes, these modeling approaches are less interested in hypothesis testing about an underlying data generation process, which is to say they tend to be somewhat atheoretical. In fact, mostly these sorts of training/testing splits just want to see if the model is over-fitting in terms of predictive performance. Of course, it is also possible to use a training/testing approach to see if a given model replicates in terms of which parameters are "significant," or to see if the parameter estimates fall within expected ranges in both instances. In theory, validating or invalidating models is what science, writ large, is supposed to be doing. Independent researchers, separately examining, generating, and testing hypotheses that support or refute arguments about a theory for why or under what circumstances an observable phenomenon occurs - that is the scientific enterprise in a nut shell (or at least in one overly long sentence). So to answer your question, to me, even training/testing splits are not "validating" a model. That is something that takes the weight of years of evidence amassed from multiple independent researchers studying the same set of phenomena. Though, I will grant that this take may be something of a difference in semantics about what I view model validation to mean versus what the term validation has come to mean in applied settings... but to get back to the root of your question more directly. Depending on your data and modeling approach, it may not always be appropriate from a statistical standpoint to split your sample into training and testing sets. For instance, small samples may be particularly difficult to apply this approach to. Additionally, some distributions may have certain properties making them difficult to model even with relatively large samples. Your zero-inflated case likely fits this latter description. If the goal is to get at an approximation of the "truth" about a set of relations or underlying processes thought to account for some phenomenon, you will not be well-served by knowingly taking an under-powered approach to testing a given hypothesis. So perhaps the first step is to perform a power analysis to see if you would even be likely to replicate the finding of interest in your subsetted data. If it is not appropriately powered, that you could be an argument against the testing/training split. Another option is to specify several models to see if they "better" explain the observed data. The goal here would be to identify the best model among a set of reasonable alternatives. This is a relative, not an absolute, argument you'd be making about your model. Essentially, you are admitting that there may be other models that could be posited to explain your data, but your model is the best of the tested set of alternatives (at least you hope so). All models in the set, including your hypothesized model, should be theoretically grounded; otherwise you run the risk of setting up a bunch of statistical straw men. There are also Bayes Factors in which you can compute the weight of evidence your model provides, given your data, for a specific hypothesis relative to alternative scenarios. This is far from an exhaustive list of options, but I hope it helps. I'll step down from the soapbox now. Just remember that every model in every published study about human behavior is incorrect. There are almost always relevant omitted variables, unmodeled interactions, imperfectly sampled populations, and just plain old sampling error at play obfuscating the underlying truth.
Is it mandatory to subset your data to validate a model?
To start, I would suggest that it is usually good to be wary of statements that there is only one way to do something. Splitting an obtained sample into a "training" and a "testing" data set is a comm
Is it mandatory to subset your data to validate a model? To start, I would suggest that it is usually good to be wary of statements that there is only one way to do something. Splitting an obtained sample into a "training" and a "testing" data set is a common approach in many machine learning/data science applications. Oftentimes, these modeling approaches are less interested in hypothesis testing about an underlying data generation process, which is to say they tend to be somewhat atheoretical. In fact, mostly these sorts of training/testing splits just want to see if the model is over-fitting in terms of predictive performance. Of course, it is also possible to use a training/testing approach to see if a given model replicates in terms of which parameters are "significant," or to see if the parameter estimates fall within expected ranges in both instances. In theory, validating or invalidating models is what science, writ large, is supposed to be doing. Independent researchers, separately examining, generating, and testing hypotheses that support or refute arguments about a theory for why or under what circumstances an observable phenomenon occurs - that is the scientific enterprise in a nut shell (or at least in one overly long sentence). So to answer your question, to me, even training/testing splits are not "validating" a model. That is something that takes the weight of years of evidence amassed from multiple independent researchers studying the same set of phenomena. Though, I will grant that this take may be something of a difference in semantics about what I view model validation to mean versus what the term validation has come to mean in applied settings... but to get back to the root of your question more directly. Depending on your data and modeling approach, it may not always be appropriate from a statistical standpoint to split your sample into training and testing sets. For instance, small samples may be particularly difficult to apply this approach to. Additionally, some distributions may have certain properties making them difficult to model even with relatively large samples. Your zero-inflated case likely fits this latter description. If the goal is to get at an approximation of the "truth" about a set of relations or underlying processes thought to account for some phenomenon, you will not be well-served by knowingly taking an under-powered approach to testing a given hypothesis. So perhaps the first step is to perform a power analysis to see if you would even be likely to replicate the finding of interest in your subsetted data. If it is not appropriately powered, that you could be an argument against the testing/training split. Another option is to specify several models to see if they "better" explain the observed data. The goal here would be to identify the best model among a set of reasonable alternatives. This is a relative, not an absolute, argument you'd be making about your model. Essentially, you are admitting that there may be other models that could be posited to explain your data, but your model is the best of the tested set of alternatives (at least you hope so). All models in the set, including your hypothesized model, should be theoretically grounded; otherwise you run the risk of setting up a bunch of statistical straw men. There are also Bayes Factors in which you can compute the weight of evidence your model provides, given your data, for a specific hypothesis relative to alternative scenarios. This is far from an exhaustive list of options, but I hope it helps. I'll step down from the soapbox now. Just remember that every model in every published study about human behavior is incorrect. There are almost always relevant omitted variables, unmodeled interactions, imperfectly sampled populations, and just plain old sampling error at play obfuscating the underlying truth.
Is it mandatory to subset your data to validate a model? To start, I would suggest that it is usually good to be wary of statements that there is only one way to do something. Splitting an obtained sample into a "training" and a "testing" data set is a comm
33,575
Is it mandatory to subset your data to validate a model?
Data splitting is in general a very non-competitive way to do internal validation. That's because of serious volatility - different 'final' model and different 'validation' upon re-splitting, and because the mean squared error of the estimate (of things like mean absolute prediction error and $R^2$) is higher than a good resampling procedure such as the bootstrap. I go into this in detail in my Regression Modeling Strategies book and course notes. Resampling has an additional major advantage: exposing volatility in feature selection.
Is it mandatory to subset your data to validate a model?
Data splitting is in general a very non-competitive way to do internal validation. That's because of serious volatility - different 'final' model and different 'validation' upon re-splitting, and bec
Is it mandatory to subset your data to validate a model? Data splitting is in general a very non-competitive way to do internal validation. That's because of serious volatility - different 'final' model and different 'validation' upon re-splitting, and because the mean squared error of the estimate (of things like mean absolute prediction error and $R^2$) is higher than a good resampling procedure such as the bootstrap. I go into this in detail in my Regression Modeling Strategies book and course notes. Resampling has an additional major advantage: exposing volatility in feature selection.
Is it mandatory to subset your data to validate a model? Data splitting is in general a very non-competitive way to do internal validation. That's because of serious volatility - different 'final' model and different 'validation' upon re-splitting, and bec
33,576
Is it mandatory to subset your data to validate a model?
I think the answers here diverge because the question is somewhat unclear, foremost: what do you mean by "validation"? A 70/30 split (or a cross-validation for that matter) is usually performed to assess the predictive performance of a model or an entire analysis chain (possibly including model selection). Such a validation is particularly important if you are comparing different modelling options in terms of their predictive performance. It's another case entirely if you don't want to select models, and are also not interested in predictive performance as such, but you are interested in inference (regression estimates / p-values), and want to validate if your model / error assumptions of the GLMM are adequate. In this case, it would be possible to predict to the hold-out and compare predictions to observed data, but the by far more common procedure is to do a residual analysis. If you need to prove this to your supervisor: this is basically what every stats textbooks teaches to do right after linear regression. See here for how to run a residual analysis for GLMMs (including zero-inflation with glmmTMB, which I would prefer over glmmadmb) with the DHARMa package (disclaimer: I am the maintainer).
Is it mandatory to subset your data to validate a model?
I think the answers here diverge because the question is somewhat unclear, foremost: what do you mean by "validation"? A 70/30 split (or a cross-validation for that matter) is usually performed to ass
Is it mandatory to subset your data to validate a model? I think the answers here diverge because the question is somewhat unclear, foremost: what do you mean by "validation"? A 70/30 split (or a cross-validation for that matter) is usually performed to assess the predictive performance of a model or an entire analysis chain (possibly including model selection). Such a validation is particularly important if you are comparing different modelling options in terms of their predictive performance. It's another case entirely if you don't want to select models, and are also not interested in predictive performance as such, but you are interested in inference (regression estimates / p-values), and want to validate if your model / error assumptions of the GLMM are adequate. In this case, it would be possible to predict to the hold-out and compare predictions to observed data, but the by far more common procedure is to do a residual analysis. If you need to prove this to your supervisor: this is basically what every stats textbooks teaches to do right after linear regression. See here for how to run a residual analysis for GLMMs (including zero-inflation with glmmTMB, which I would prefer over glmmadmb) with the DHARMa package (disclaimer: I am the maintainer).
Is it mandatory to subset your data to validate a model? I think the answers here diverge because the question is somewhat unclear, foremost: what do you mean by "validation"? A 70/30 split (or a cross-validation for that matter) is usually performed to ass
33,577
Is it mandatory to subset your data to validate a model?
The short answer is yes, you need to assess your model's performance on data not used in training. Modern model building techniques are extremely good at fitting data arbitrarily well and can easily find signal in noise. Thus a model's performance on training data is almost always biased. It is worth your time to explore the topic of cross validation (even if you are not tuning hyperparameters) to gain a better understanding of why we hold out data, when it works, what assumptions are involved, etc. One of my favorite papers is: No unbiased estimator of the variance of k-fold cross-validation
Is it mandatory to subset your data to validate a model?
The short answer is yes, you need to assess your model's performance on data not used in training. Modern model building techniques are extremely good at fitting data arbitrarily well and can easily
Is it mandatory to subset your data to validate a model? The short answer is yes, you need to assess your model's performance on data not used in training. Modern model building techniques are extremely good at fitting data arbitrarily well and can easily find signal in noise. Thus a model's performance on training data is almost always biased. It is worth your time to explore the topic of cross validation (even if you are not tuning hyperparameters) to gain a better understanding of why we hold out data, when it works, what assumptions are involved, etc. One of my favorite papers is: No unbiased estimator of the variance of k-fold cross-validation
Is it mandatory to subset your data to validate a model? The short answer is yes, you need to assess your model's performance on data not used in training. Modern model building techniques are extremely good at fitting data arbitrarily well and can easily
33,578
Random variable defined as A with 50% chance and B with 50% chance
Hopefully it's clear to you that C isn't guaranteed to be normal. However, part of your question was how to write down its PDF. @BallpointBen gave you a hint. If that's not enough, here are some more spoilers... Note that C can be written as: $$C = T \cdot A + (1-T) \cdot B$$ for a Bernoulli random $T$ with $P(T=0)=P(T=1)=1/2$ with $T$ independent of $(A,B)$. This is more or less the standard mathematical translation of the English statement "C is A with 50% chance and B with 50% chance". Now, determining the PDF of C directly from this seems hard, but you can make progress by writing down the distribution function $F_C$ of C. You can partition the event $C \leq X$ into two subevents (depending on the value of $T$) to write: $$ F_C(x) = P(C \leq x) = P(T = 0 \text{ and } C \leq x) + P(T = 1\text{ and C }\leq x) $$ and note that by the definition of C and the independence of T and B, you have: $$P(T=0\text{ and }C \leq x) = P(T=0\text{ and }B\leq x) = \frac12P(B\leq x) = \frac12 F_B(x)$$ You should be able to use a similar result in the $T=1$ case to write $F_C$ in terms of $F_A$ and $F_B$. To get the PDF of C, just differentiate $F_C$ with respect to x.
Random variable defined as A with 50% chance and B with 50% chance
Hopefully it's clear to you that C isn't guaranteed to be normal. However, part of your question was how to write down its PDF. @BallpointBen gave you a hint. If that's not enough, here are some mor
Random variable defined as A with 50% chance and B with 50% chance Hopefully it's clear to you that C isn't guaranteed to be normal. However, part of your question was how to write down its PDF. @BallpointBen gave you a hint. If that's not enough, here are some more spoilers... Note that C can be written as: $$C = T \cdot A + (1-T) \cdot B$$ for a Bernoulli random $T$ with $P(T=0)=P(T=1)=1/2$ with $T$ independent of $(A,B)$. This is more or less the standard mathematical translation of the English statement "C is A with 50% chance and B with 50% chance". Now, determining the PDF of C directly from this seems hard, but you can make progress by writing down the distribution function $F_C$ of C. You can partition the event $C \leq X$ into two subevents (depending on the value of $T$) to write: $$ F_C(x) = P(C \leq x) = P(T = 0 \text{ and } C \leq x) + P(T = 1\text{ and C }\leq x) $$ and note that by the definition of C and the independence of T and B, you have: $$P(T=0\text{ and }C \leq x) = P(T=0\text{ and }B\leq x) = \frac12P(B\leq x) = \frac12 F_B(x)$$ You should be able to use a similar result in the $T=1$ case to write $F_C$ in terms of $F_A$ and $F_B$. To get the PDF of C, just differentiate $F_C$ with respect to x.
Random variable defined as A with 50% chance and B with 50% chance Hopefully it's clear to you that C isn't guaranteed to be normal. However, part of your question was how to write down its PDF. @BallpointBen gave you a hint. If that's not enough, here are some mor
33,579
Random variable defined as A with 50% chance and B with 50% chance
Simulation of a random 50-50 mixture of $\mathsf{Norm}(\mu=90, \sigma=2)$ and $\mathsf{Norm}(\mu=100, \sigma=2)$ is illustrated below. Simulation in R. set.seed(827); m = 10^6 x1 = rnorm(m, 100, 2); x2 = rnorm(m, 90, 2) p = rbinom(m, 1, .5) x = x1; x[p==1] = x2[p==1] hist(x, prob=T, col="skyblue2", main="Random 50-50 Mixture of NORM(90,2) and NORM(100,2)") curve(.5*(dnorm(x, 100, 2) + dnorm(x, 90, 2)), add=T, col="red", lwd=2)
Random variable defined as A with 50% chance and B with 50% chance
Simulation of a random 50-50 mixture of $\mathsf{Norm}(\mu=90, \sigma=2)$ and $\mathsf{Norm}(\mu=100, \sigma=2)$ is illustrated below. Simulation in R. set.seed(827); m = 10^6 x1 = rnorm(m, 100, 2);
Random variable defined as A with 50% chance and B with 50% chance Simulation of a random 50-50 mixture of $\mathsf{Norm}(\mu=90, \sigma=2)$ and $\mathsf{Norm}(\mu=100, \sigma=2)$ is illustrated below. Simulation in R. set.seed(827); m = 10^6 x1 = rnorm(m, 100, 2); x2 = rnorm(m, 90, 2) p = rbinom(m, 1, .5) x = x1; x[p==1] = x2[p==1] hist(x, prob=T, col="skyblue2", main="Random 50-50 Mixture of NORM(90,2) and NORM(100,2)") curve(.5*(dnorm(x, 100, 2) + dnorm(x, 90, 2)), add=T, col="red", lwd=2)
Random variable defined as A with 50% chance and B with 50% chance Simulation of a random 50-50 mixture of $\mathsf{Norm}(\mu=90, \sigma=2)$ and $\mathsf{Norm}(\mu=100, \sigma=2)$ is illustrated below. Simulation in R. set.seed(827); m = 10^6 x1 = rnorm(m, 100, 2);
33,580
Random variable defined as A with 50% chance and B with 50% chance
One way you could work on that is to analyze it as the variance tends to 0. This way you would get a Bernoulli-like distribution, which is (clearly) not a normal distribution.
Random variable defined as A with 50% chance and B with 50% chance
One way you could work on that is to analyze it as the variance tends to 0. This way you would get a Bernoulli-like distribution, which is (clearly) not a normal distribution.
Random variable defined as A with 50% chance and B with 50% chance One way you could work on that is to analyze it as the variance tends to 0. This way you would get a Bernoulli-like distribution, which is (clearly) not a normal distribution.
Random variable defined as A with 50% chance and B with 50% chance One way you could work on that is to analyze it as the variance tends to 0. This way you would get a Bernoulli-like distribution, which is (clearly) not a normal distribution.
33,581
Random variable defined as A with 50% chance and B with 50% chance
This is the kind of problem where it is very helpful to use the concept of the CDF, the cumulative probability distribution function, of random variables, that totally unnecessary concept that professors drag in just to confuse students who are happy to just use pdfs. By definition, the value of the CDF $F_X(\alpha)$ of a random variable $X$ equals the probability that $X$ is no larger than the real number $\alpha$, that is, $$F_X(\alpha) = P\{X \leq \alpha\}, ~-\infty < \alpha < \infty.$$ Now, the law of total probability tells us that if $X$ is equally likely to be the same as a random variable $A$ or a random variable $B$, then $$P\{X \leq \alpha\} = \frac 12 P\{A \leq \alpha\} + \frac 12 P\{B \leq \alpha\},$$ or, in other words, $$F_X(\alpha\} = \frac 12 F_A(\alpha\} + \frac 12 F_B(\alpha\}.$$ Remembering how your professor boringly nattered on and on about how for continuous random variables the pdf is the derivative of the CDF, we get that $$f_X(\alpha\} = \frac 12 f_A(\alpha\} + \frac 12 f_B(\alpha\} \tag{1}$$ which answers one of your questions. For the special case of normal random variables $A$ and $B$, can you figure out whether $(1)$ gives a normal density for $X$ or not? If you are familiar with notions such as $$E[X] = \int_{-\infty}^\infty \alpha f_X(\alpha\} \, \mathrm d\alpha, \tag{2}$$ can you figure out, by substituting the right side of $(1)$ for the $f_X(\alpha)$ in $(2)$ and thinking about the expression, what $E[X]$ is in terms of $E[A]$ and $E[B]$?
Random variable defined as A with 50% chance and B with 50% chance
This is the kind of problem where it is very helpful to use the concept of the CDF, the cumulative probability distribution function, of random variables, that totally unnecessary concept that profess
Random variable defined as A with 50% chance and B with 50% chance This is the kind of problem where it is very helpful to use the concept of the CDF, the cumulative probability distribution function, of random variables, that totally unnecessary concept that professors drag in just to confuse students who are happy to just use pdfs. By definition, the value of the CDF $F_X(\alpha)$ of a random variable $X$ equals the probability that $X$ is no larger than the real number $\alpha$, that is, $$F_X(\alpha) = P\{X \leq \alpha\}, ~-\infty < \alpha < \infty.$$ Now, the law of total probability tells us that if $X$ is equally likely to be the same as a random variable $A$ or a random variable $B$, then $$P\{X \leq \alpha\} = \frac 12 P\{A \leq \alpha\} + \frac 12 P\{B \leq \alpha\},$$ or, in other words, $$F_X(\alpha\} = \frac 12 F_A(\alpha\} + \frac 12 F_B(\alpha\}.$$ Remembering how your professor boringly nattered on and on about how for continuous random variables the pdf is the derivative of the CDF, we get that $$f_X(\alpha\} = \frac 12 f_A(\alpha\} + \frac 12 f_B(\alpha\} \tag{1}$$ which answers one of your questions. For the special case of normal random variables $A$ and $B$, can you figure out whether $(1)$ gives a normal density for $X$ or not? If you are familiar with notions such as $$E[X] = \int_{-\infty}^\infty \alpha f_X(\alpha\} \, \mathrm d\alpha, \tag{2}$$ can you figure out, by substituting the right side of $(1)$ for the $f_X(\alpha)$ in $(2)$ and thinking about the expression, what $E[X]$ is in terms of $E[A]$ and $E[B]$?
Random variable defined as A with 50% chance and B with 50% chance This is the kind of problem where it is very helpful to use the concept of the CDF, the cumulative probability distribution function, of random variables, that totally unnecessary concept that profess
33,582
Random variable defined as A with 50% chance and B with 50% chance
$C$ is not normal distributed unless $A$ and $B$ are identically distributed. If $A$ and $B$ are identically distributed, however, $C$ will also be identically distributed. Proof Let $F_A$, $F_B$ and $F_C$ be the cumulative distribution functions (CDFs) of A, B and C, respectively, and $f_A$, $f_B$ and $f_C$ their probability density functions (PDFs), i.e. $$\begin{array}{l} F_A(x) = \Pr(A < x), \\ F_B(x) = \Pr(B < x), \\ F_C(x) = \Pr(C < x), \\ f_A(x) = \frac{d}{dx}F_A(x), \\ f_B(x) = \frac{d}{dx}F_B(x),\text{ and} \\ f_C(x) = \frac{d}{dx}F_C(x). \end{array}$$ We also have two events: $\Gamma_1$, which is when $C$ is defined as $A$, which occurs with probability $\gamma$ $\Gamma_2$, which is when $C$ is defined as $B$, which occurs with probability $1 - \gamma$ According to the law of total probability, $$\begin{array}{rl} F_C(x) \!\!\!\! & = Pr(C < x)\\ & = \Pr(C < x\ |\ \Gamma_1 )\Pr(\Gamma_1) + \Pr(C < x\ |\ \Gamma_2 )\Pr(\Gamma_2) \\ & = \Pr(A < x)\Pr(\Gamma_1) + \Pr(B < x)\Pr(\Gamma_2)\\ & = \gamma F_A(x) + (1 - \gamma) F_B(x). \end{array}$$ Therefore, $$\begin{array}{rl} f_C(x) \!\!\!\! & = \frac{d}{dx} F_C(x)\\ & = \frac{d}{dx}(\gamma F_A(x) + (1 - \gamma) F_B(x)) \\ & = \gamma\left(\frac{d}{dx} F_A(x)\right) + (1 - \gamma) \left(\frac{d}{dx}F_B(x)\right) \\ & = \gamma f_A(x) + (1 - \gamma) f_B(x), \end{array}$$ and since $\gamma = 0.5,$ $$f_C(x) = 0.5 f_A(x) + 0.5 f_B(x).$$ Also, since the PDF of a normal distribution is a positive Gaussian function, and the sum of two possitive Gaussian functions is a positive Gaussian function if and only if the two Gaussian functions are linearly dependent, $C$ is normally distributed if and only if $A$ and $B$ are identically distributed. If $A$ and $B$ are identically distributed, $f_A(x) = f_B(x) = f_C(x)$, so $C$ will also be identically distributed.
Random variable defined as A with 50% chance and B with 50% chance
$C$ is not normal distributed unless $A$ and $B$ are identically distributed. If $A$ and $B$ are identically distributed, however, $C$ will also be identically distributed. Proof Let $F_A$, $F_B$ and
Random variable defined as A with 50% chance and B with 50% chance $C$ is not normal distributed unless $A$ and $B$ are identically distributed. If $A$ and $B$ are identically distributed, however, $C$ will also be identically distributed. Proof Let $F_A$, $F_B$ and $F_C$ be the cumulative distribution functions (CDFs) of A, B and C, respectively, and $f_A$, $f_B$ and $f_C$ their probability density functions (PDFs), i.e. $$\begin{array}{l} F_A(x) = \Pr(A < x), \\ F_B(x) = \Pr(B < x), \\ F_C(x) = \Pr(C < x), \\ f_A(x) = \frac{d}{dx}F_A(x), \\ f_B(x) = \frac{d}{dx}F_B(x),\text{ and} \\ f_C(x) = \frac{d}{dx}F_C(x). \end{array}$$ We also have two events: $\Gamma_1$, which is when $C$ is defined as $A$, which occurs with probability $\gamma$ $\Gamma_2$, which is when $C$ is defined as $B$, which occurs with probability $1 - \gamma$ According to the law of total probability, $$\begin{array}{rl} F_C(x) \!\!\!\! & = Pr(C < x)\\ & = \Pr(C < x\ |\ \Gamma_1 )\Pr(\Gamma_1) + \Pr(C < x\ |\ \Gamma_2 )\Pr(\Gamma_2) \\ & = \Pr(A < x)\Pr(\Gamma_1) + \Pr(B < x)\Pr(\Gamma_2)\\ & = \gamma F_A(x) + (1 - \gamma) F_B(x). \end{array}$$ Therefore, $$\begin{array}{rl} f_C(x) \!\!\!\! & = \frac{d}{dx} F_C(x)\\ & = \frac{d}{dx}(\gamma F_A(x) + (1 - \gamma) F_B(x)) \\ & = \gamma\left(\frac{d}{dx} F_A(x)\right) + (1 - \gamma) \left(\frac{d}{dx}F_B(x)\right) \\ & = \gamma f_A(x) + (1 - \gamma) f_B(x), \end{array}$$ and since $\gamma = 0.5,$ $$f_C(x) = 0.5 f_A(x) + 0.5 f_B(x).$$ Also, since the PDF of a normal distribution is a positive Gaussian function, and the sum of two possitive Gaussian functions is a positive Gaussian function if and only if the two Gaussian functions are linearly dependent, $C$ is normally distributed if and only if $A$ and $B$ are identically distributed. If $A$ and $B$ are identically distributed, $f_A(x) = f_B(x) = f_C(x)$, so $C$ will also be identically distributed.
Random variable defined as A with 50% chance and B with 50% chance $C$ is not normal distributed unless $A$ and $B$ are identically distributed. If $A$ and $B$ are identically distributed, however, $C$ will also be identically distributed. Proof Let $F_A$, $F_B$ and
33,583
Why does treatment coding result in a correlation between random slope and intercept?
Treatment coding doesn't always or necessarily result in intercept/slope correlation, but it tends to more often than not. It's easiest to see why this is the case using pictures, and considering the case of a continuous rather than categorical predictor. Here's a picture of a normal-looking clustered dataset with approximately 0 correlation between the random intercepts and random slopes: But now look what happens when shift the predictor X far to the right by adding 3 to each X value: It's the same dataset in a deep sense -- if we zoomed in on the data points it would look identical to the first plot, but with the X axis relabeled -- but simply by shifting X we've induced an almost perfect negative correlation between the random intercepts and random slopes. This happens because when we shift X, we redefine the intercepts of each group. Remember that the intercepts always refer to the Y-values where the group-specific regression lines cross X=0. But now the X=0 point is far away from the center of the data. So we're essentially extrapolating outside the range of the observed data in order to compute the intercepts. The result, as you can see, is that the greater the slope is, the lower the intercept is, and vice versa. When you use treatment coding, it's like doing a less extreme version of the X-shifting depicted in the bottom graph. This is because the treatment codes {0,1} are just a shifted version of the deviation codes {-0.5, 0.5}, where a shift of +0.5 has been added. Edit 2018-08-29: this is now illustrated more clearly and directly in the second figure of this more recent answer of mine to another question. Like I said earlier, this is not true by necessity. It's possible to have a dataset similar to the above, but where the slopes and intercepts are uncorrelated on the shifted scale (where the intercepts refer to points far away from the data) and correlated on the centered scale. But the group-specific regression lines in such datasets will tend to exhibit "fanning out" patterns that, in practice, are just not that common in the real world.
Why does treatment coding result in a correlation between random slope and intercept?
Treatment coding doesn't always or necessarily result in intercept/slope correlation, but it tends to more often than not. It's easiest to see why this is the case using pictures, and considering the
Why does treatment coding result in a correlation between random slope and intercept? Treatment coding doesn't always or necessarily result in intercept/slope correlation, but it tends to more often than not. It's easiest to see why this is the case using pictures, and considering the case of a continuous rather than categorical predictor. Here's a picture of a normal-looking clustered dataset with approximately 0 correlation between the random intercepts and random slopes: But now look what happens when shift the predictor X far to the right by adding 3 to each X value: It's the same dataset in a deep sense -- if we zoomed in on the data points it would look identical to the first plot, but with the X axis relabeled -- but simply by shifting X we've induced an almost perfect negative correlation between the random intercepts and random slopes. This happens because when we shift X, we redefine the intercepts of each group. Remember that the intercepts always refer to the Y-values where the group-specific regression lines cross X=0. But now the X=0 point is far away from the center of the data. So we're essentially extrapolating outside the range of the observed data in order to compute the intercepts. The result, as you can see, is that the greater the slope is, the lower the intercept is, and vice versa. When you use treatment coding, it's like doing a less extreme version of the X-shifting depicted in the bottom graph. This is because the treatment codes {0,1} are just a shifted version of the deviation codes {-0.5, 0.5}, where a shift of +0.5 has been added. Edit 2018-08-29: this is now illustrated more clearly and directly in the second figure of this more recent answer of mine to another question. Like I said earlier, this is not true by necessity. It's possible to have a dataset similar to the above, but where the slopes and intercepts are uncorrelated on the shifted scale (where the intercepts refer to points far away from the data) and correlated on the centered scale. But the group-specific regression lines in such datasets will tend to exhibit "fanning out" patterns that, in practice, are just not that common in the real world.
Why does treatment coding result in a correlation between random slope and intercept? Treatment coding doesn't always or necessarily result in intercept/slope correlation, but it tends to more often than not. It's easiest to see why this is the case using pictures, and considering the
33,584
Why does treatment coding result in a correlation between random slope and intercept?
I believe it is because anything times zero is zero, so if you look at all four possible interactions (multiplications) of 0 and 1, three out of four are zero. On the other hand, two out of four interactions of -1 and 1 are 1 and two are -1.
Why does treatment coding result in a correlation between random slope and intercept?
I believe it is because anything times zero is zero, so if you look at all four possible interactions (multiplications) of 0 and 1, three out of four are zero. On the other hand, two out of four inter
Why does treatment coding result in a correlation between random slope and intercept? I believe it is because anything times zero is zero, so if you look at all four possible interactions (multiplications) of 0 and 1, three out of four are zero. On the other hand, two out of four interactions of -1 and 1 are 1 and two are -1.
Why does treatment coding result in a correlation between random slope and intercept? I believe it is because anything times zero is zero, so if you look at all four possible interactions (multiplications) of 0 and 1, three out of four are zero. On the other hand, two out of four inter
33,585
Time series analysis: since volatility depends on time, why are returns stationary?
I think your problem is that you confuse the UNconditional variance and the conditional variance. Indeed, you can have a time-varying conditional volatility but a constant unconditional variance. First, I illustrate what Dickey-Fuller does and why it is a very specific test. Second, I explain why you can have a time-varying conditional volatility but a constant unconditional variance. Firstly, consider the framework : $y_{t}=\rho y_{t-1}+\epsilon_{t}$ where $\epsilon_t\sim_{iid}\mathcal{N}(0,\sigma^2)$ for $t\in[1,T]$. If you compute the expectation and (unconditional) variance of $y_t$, you get $\mathbb{E}[y_t]=\rho^{t-1}y_{1}$ and $\mathbb{V}[y_t]=\sigma^2\sum_{l=0}^{t-1}\rho^{2l}$ Dickey-Fuller test performs $H0:"\rho=1"$ vs $H1:"\rho<1"$. If $\rho=1$, then $\mathbb{V}[y_t]=t\sigma^2$, what means the unconditional variance increases linearly with time. If it is inferior to 1, then the unconditional variance tends to be constant with time due to the geometric series of its expression. If $\rho<1$ and $t\rightarrow\infty$,$\mathbb{V}[y_t]\rightarrow\frac{\sigma^2}{1-\rho^2}<+\infty$ what implies it is covariance-stationary. That is why, if DF test rejects H0, you cannot accept that the unconditional variance increases linearly with time when compared with the covariance-stationnary hypothesis, but it just concerns a specific form of nonstationarity. Second, consider the following process (ARCH(1)): $y_{t}=\sigma_t\epsilon_t$ with $\sigma_t^2=\alpha+\beta y_{t-1}^2$ where $\alpha>0$ and $0<\beta< 1$, $\epsilon_t\sim_{iid}\mathcal{N}(0,1)$, $\sigma_t$ being independent of $\epsilon_t$. Here, you can see the volatility parameter $\sigma_t$ depends on time. However, this parameter is the variance of $y_t$ conditionally to the information we get at time $t$. Actually, the UNconditional variance of $y_t$ is: $\mathbb{V}[y_t]=\mathbb{E}[y_t^{2}]=\mathbb{E}[\sigma_t^2]=\alpha+\beta \mathbb{E}[y_{t-1}^2]$ If $y_t$ is covariance-stationary, $\mathbb{V}[y_t]=\mathbb{E}[y_t^{2}]=\mathbb{E}[y_{t-1}^{2}]$ what implies : $\mathbb{V}[y_t]=\frac{\alpha}{1-\beta}<+\infty$ So, $y_t$ can be covariance-stationary while displaying locally some clusters of volatility. To think further, you can go to see this paper proposing a framework to test if the UNconditional variance is constant or not: Sansó, A., Aragó, V. and Carrion-i-Silvestre, J. Ll. (2004): “Testing for Changes in the Unconditional Variance of Financial Time Series”.
Time series analysis: since volatility depends on time, why are returns stationary?
I think your problem is that you confuse the UNconditional variance and the conditional variance. Indeed, you can have a time-varying conditional volatility but a constant unconditional variance. Firs
Time series analysis: since volatility depends on time, why are returns stationary? I think your problem is that you confuse the UNconditional variance and the conditional variance. Indeed, you can have a time-varying conditional volatility but a constant unconditional variance. First, I illustrate what Dickey-Fuller does and why it is a very specific test. Second, I explain why you can have a time-varying conditional volatility but a constant unconditional variance. Firstly, consider the framework : $y_{t}=\rho y_{t-1}+\epsilon_{t}$ where $\epsilon_t\sim_{iid}\mathcal{N}(0,\sigma^2)$ for $t\in[1,T]$. If you compute the expectation and (unconditional) variance of $y_t$, you get $\mathbb{E}[y_t]=\rho^{t-1}y_{1}$ and $\mathbb{V}[y_t]=\sigma^2\sum_{l=0}^{t-1}\rho^{2l}$ Dickey-Fuller test performs $H0:"\rho=1"$ vs $H1:"\rho<1"$. If $\rho=1$, then $\mathbb{V}[y_t]=t\sigma^2$, what means the unconditional variance increases linearly with time. If it is inferior to 1, then the unconditional variance tends to be constant with time due to the geometric series of its expression. If $\rho<1$ and $t\rightarrow\infty$,$\mathbb{V}[y_t]\rightarrow\frac{\sigma^2}{1-\rho^2}<+\infty$ what implies it is covariance-stationary. That is why, if DF test rejects H0, you cannot accept that the unconditional variance increases linearly with time when compared with the covariance-stationnary hypothesis, but it just concerns a specific form of nonstationarity. Second, consider the following process (ARCH(1)): $y_{t}=\sigma_t\epsilon_t$ with $\sigma_t^2=\alpha+\beta y_{t-1}^2$ where $\alpha>0$ and $0<\beta< 1$, $\epsilon_t\sim_{iid}\mathcal{N}(0,1)$, $\sigma_t$ being independent of $\epsilon_t$. Here, you can see the volatility parameter $\sigma_t$ depends on time. However, this parameter is the variance of $y_t$ conditionally to the information we get at time $t$. Actually, the UNconditional variance of $y_t$ is: $\mathbb{V}[y_t]=\mathbb{E}[y_t^{2}]=\mathbb{E}[\sigma_t^2]=\alpha+\beta \mathbb{E}[y_{t-1}^2]$ If $y_t$ is covariance-stationary, $\mathbb{V}[y_t]=\mathbb{E}[y_t^{2}]=\mathbb{E}[y_{t-1}^{2}]$ what implies : $\mathbb{V}[y_t]=\frac{\alpha}{1-\beta}<+\infty$ So, $y_t$ can be covariance-stationary while displaying locally some clusters of volatility. To think further, you can go to see this paper proposing a framework to test if the UNconditional variance is constant or not: Sansó, A., Aragó, V. and Carrion-i-Silvestre, J. Ll. (2004): “Testing for Changes in the Unconditional Variance of Financial Time Series”.
Time series analysis: since volatility depends on time, why are returns stationary? I think your problem is that you confuse the UNconditional variance and the conditional variance. Indeed, you can have a time-varying conditional volatility but a constant unconditional variance. Firs
33,586
Time series analysis: since volatility depends on time, why are returns stationary?
The augmented Dickey-Fuller test assesses whether the time series under inspection has a unit root or not. The test is designed specifically for that purpose. It either rejects the null of unit root or fails to reject it. Rejection of the unit root should not be interpreted as presence of stationarity, though. Presence of a unit root is one form of nonstationarity, but absence of a unit root does not imply stationarity. For example, presence of a deterministic time trend or certain forms of conditional heteroskedasticity are also forms of nonstationarity and they may be characteristic to a time series regardless of whether it has a unit root or not. The takeaway message is, stationarity is never confirmed; we may just reject (or fail to reject) some forms of nonstationarity based on particular tests (but there will be other possible forms of nonstationarity that we have not tested for yet).
Time series analysis: since volatility depends on time, why are returns stationary?
The augmented Dickey-Fuller test assesses whether the time series under inspection has a unit root or not. The test is designed specifically for that purpose. It either rejects the null of unit root o
Time series analysis: since volatility depends on time, why are returns stationary? The augmented Dickey-Fuller test assesses whether the time series under inspection has a unit root or not. The test is designed specifically for that purpose. It either rejects the null of unit root or fails to reject it. Rejection of the unit root should not be interpreted as presence of stationarity, though. Presence of a unit root is one form of nonstationarity, but absence of a unit root does not imply stationarity. For example, presence of a deterministic time trend or certain forms of conditional heteroskedasticity are also forms of nonstationarity and they may be characteristic to a time series regardless of whether it has a unit root or not. The takeaway message is, stationarity is never confirmed; we may just reject (or fail to reject) some forms of nonstationarity based on particular tests (but there will be other possible forms of nonstationarity that we have not tested for yet).
Time series analysis: since volatility depends on time, why are returns stationary? The augmented Dickey-Fuller test assesses whether the time series under inspection has a unit root or not. The test is designed specifically for that purpose. It either rejects the null of unit root o
33,587
Time series analysis: since volatility depends on time, why are returns stationary?
Dickey-Fuller test does not test for stationarity of return volatilities. So, when you say "stationary" you could mean a lot of things. There is not a single test that checks for stationarity in the strict complete definition of this term. There are different tests checking different facets of stationarity. Intuitively, all that DF test checks for is whether $\theta_1=1$ holds in the processes like this $$r_t=\theta_1r_{t-1}+e_t$$ So, if returns are random walks (e.g. $\theta_1=1$), then DF could detect them. It doesn't test whether $\sigma_{e_t}$ is constant at all. So, if you think (hopefully not) that stock returns are random walks you should be surprised by DF result, otherwise it's the expected result. There are tests such as Engle's ARCH that test for changing volatility. UPDATE Take a look at this amazing paper: A MARKET ECONOMY IN THE EARLY ROMAN EMPIRE, Peter Temin, p.15. The loan rates were in the range of 4 to 12% thousands years ago in Ancient Egypt! It's the same rates as today. So, at least in levels (means) the returns got to be stationary.
Time series analysis: since volatility depends on time, why are returns stationary?
Dickey-Fuller test does not test for stationarity of return volatilities. So, when you say "stationary" you could mean a lot of things. There is not a single test that checks for stationarity in the s
Time series analysis: since volatility depends on time, why are returns stationary? Dickey-Fuller test does not test for stationarity of return volatilities. So, when you say "stationary" you could mean a lot of things. There is not a single test that checks for stationarity in the strict complete definition of this term. There are different tests checking different facets of stationarity. Intuitively, all that DF test checks for is whether $\theta_1=1$ holds in the processes like this $$r_t=\theta_1r_{t-1}+e_t$$ So, if returns are random walks (e.g. $\theta_1=1$), then DF could detect them. It doesn't test whether $\sigma_{e_t}$ is constant at all. So, if you think (hopefully not) that stock returns are random walks you should be surprised by DF result, otherwise it's the expected result. There are tests such as Engle's ARCH that test for changing volatility. UPDATE Take a look at this amazing paper: A MARKET ECONOMY IN THE EARLY ROMAN EMPIRE, Peter Temin, p.15. The loan rates were in the range of 4 to 12% thousands years ago in Ancient Egypt! It's the same rates as today. So, at least in levels (means) the returns got to be stationary.
Time series analysis: since volatility depends on time, why are returns stationary? Dickey-Fuller test does not test for stationarity of return volatilities. So, when you say "stationary" you could mean a lot of things. There is not a single test that checks for stationarity in the s
33,588
Time series analysis: since volatility depends on time, why are returns stationary?
What you have tested is first-order stationarity. On http://www.maths.bris.ac.uk/~guy/Research/LSTS/TOS.html you can find a list with some tests of Second-Order stationarity: The Priestley-Subba Rao (PSR) Test Wavelet Spectrum Test and even some code to run it in R.
Time series analysis: since volatility depends on time, why are returns stationary?
What you have tested is first-order stationarity. On http://www.maths.bris.ac.uk/~guy/Research/LSTS/TOS.html you can find a list with some tests of Second-Order stationarity: The Priestley-Subba Rao
Time series analysis: since volatility depends on time, why are returns stationary? What you have tested is first-order stationarity. On http://www.maths.bris.ac.uk/~guy/Research/LSTS/TOS.html you can find a list with some tests of Second-Order stationarity: The Priestley-Subba Rao (PSR) Test Wavelet Spectrum Test and even some code to run it in R.
Time series analysis: since volatility depends on time, why are returns stationary? What you have tested is first-order stationarity. On http://www.maths.bris.ac.uk/~guy/Research/LSTS/TOS.html you can find a list with some tests of Second-Order stationarity: The Priestley-Subba Rao
33,589
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1
You seem to want to use a fractional logit, i.e. a quasi-likelihood model for a proportion. The key here is that it is a quasi-likelihood model, so the family refers to the variance function and nothing else. In quasi-likelihood that variance is a nuisance parameter, which does not have to be correctly specified in your model if your dataset is large enough. So I would stick with the usual family for a fractional logit model, and use the binomial family.
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1
You seem to want to use a fractional logit, i.e. a quasi-likelihood model for a proportion. The key here is that it is a quasi-likelihood model, so the family refers to the variance function and nothi
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1 You seem to want to use a fractional logit, i.e. a quasi-likelihood model for a proportion. The key here is that it is a quasi-likelihood model, so the family refers to the variance function and nothing else. In quasi-likelihood that variance is a nuisance parameter, which does not have to be correctly specified in your model if your dataset is large enough. So I would stick with the usual family for a fractional logit model, and use the binomial family.
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1 You seem to want to use a fractional logit, i.e. a quasi-likelihood model for a proportion. The key here is that it is a quasi-likelihood model, so the family refers to the variance function and nothi
33,590
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1
If your data really are continuous proportions (the common example I see is % silt, clay, or sand in sediment samples - only one of these types for beta regression, all three for a Dirichlet regression) then a beta regression would suggest itself. It's not a GLM sensu McCullagh and Nelder, but it is part of the extended family of GLMs that look, walk, and quack like a GLM.
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1
If your data really are continuous proportions (the common example I see is % silt, clay, or sand in sediment samples - only one of these types for beta regression, all three for a Dirichlet regressio
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1 If your data really are continuous proportions (the common example I see is % silt, clay, or sand in sediment samples - only one of these types for beta regression, all three for a Dirichlet regression) then a beta regression would suggest itself. It's not a GLM sensu McCullagh and Nelder, but it is part of the extended family of GLMs that look, walk, and quack like a GLM.
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1 If your data really are continuous proportions (the common example I see is % silt, clay, or sand in sediment samples - only one of these types for beta regression, all three for a Dirichlet regressio
33,591
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1
Yes you can. The model parameters are still log-odds ratios, but they are estimated differently. Your model with such specifications is basically a nonlinear least squares, where a logit "S" curve is being fit to 0/1 outcomes so as to minimize the squared error. However, the contrasts to usual logistic regression are very well known: this approach puts very little weight on 0/1 outcomes since a proportional difference of 0.95 versus 0.96 is much larger when scaled by its binomial variance. Gaussian families do not assume any mean-variance relationship. That's why this approach is not often used. If the results given you are proportions, then the burning question is: do you have the denominators for these proportions? e.g. is the 0.43 percent calculated out of $n=100$ or $n=200$ participants and/or does this value differ between the various observations you've obtained? If so, weighting the binomial likelihood gives equivalent inference to fully observed 0/1 counts. In R, for instance, it will still give you warnings that you have used non-binary outcome variables, but the fitting algorithm does not "break" when inputting data of this format. Other software may prevent such approaches altogether so you will have to create product variables. However, without such counts in place, other robust error estimation methods should be used. Others' suggestions of quasilikelihood seems like a reasonable choice.
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1
Yes you can. The model parameters are still log-odds ratios, but they are estimated differently. Your model with such specifications is basically a nonlinear least squares, where a logit "S" curve is
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1 Yes you can. The model parameters are still log-odds ratios, but they are estimated differently. Your model with such specifications is basically a nonlinear least squares, where a logit "S" curve is being fit to 0/1 outcomes so as to minimize the squared error. However, the contrasts to usual logistic regression are very well known: this approach puts very little weight on 0/1 outcomes since a proportional difference of 0.95 versus 0.96 is much larger when scaled by its binomial variance. Gaussian families do not assume any mean-variance relationship. That's why this approach is not often used. If the results given you are proportions, then the burning question is: do you have the denominators for these proportions? e.g. is the 0.43 percent calculated out of $n=100$ or $n=200$ participants and/or does this value differ between the various observations you've obtained? If so, weighting the binomial likelihood gives equivalent inference to fully observed 0/1 counts. In R, for instance, it will still give you warnings that you have used non-binary outcome variables, but the fitting algorithm does not "break" when inputting data of this format. Other software may prevent such approaches altogether so you will have to create product variables. However, without such counts in place, other robust error estimation methods should be used. Others' suggestions of quasilikelihood seems like a reasonable choice.
GLM with logit link and Gaussian family to predict a continuous DV between 0 and 1 Yes you can. The model parameters are still log-odds ratios, but they are estimated differently. Your model with such specifications is basically a nonlinear least squares, where a logit "S" curve is
33,592
What is the definition of expected counts in chi square tests?
Expected counts are the projected frequencies in each cell if the null hypothesis is true (aka, no association between the variables.) Given the follow 2x2 table of outcome (O) and exposure (E) as an example, a, b, c, and d are all observed counts: The expected count for each cell would be the product of the corresponding row and column totals divided by the sample size. For example, the expected count for O+E+ would be: $$\frac{(a+b) \times (a+c)}{a+b+c+d}$$ (see red arrows for the meaning of "corresponding") Then the expected counts will be contrast with the observed counts, cell by cell. The more the difference, the higher the resultant statistics, which is the $\chi^2$.
What is the definition of expected counts in chi square tests?
Expected counts are the projected frequencies in each cell if the null hypothesis is true (aka, no association between the variables.) Given the follow 2x2 table of outcome (O) and exposure (E) as an
What is the definition of expected counts in chi square tests? Expected counts are the projected frequencies in each cell if the null hypothesis is true (aka, no association between the variables.) Given the follow 2x2 table of outcome (O) and exposure (E) as an example, a, b, c, and d are all observed counts: The expected count for each cell would be the product of the corresponding row and column totals divided by the sample size. For example, the expected count for O+E+ would be: $$\frac{(a+b) \times (a+c)}{a+b+c+d}$$ (see red arrows for the meaning of "corresponding") Then the expected counts will be contrast with the observed counts, cell by cell. The more the difference, the higher the resultant statistics, which is the $\chi^2$.
What is the definition of expected counts in chi square tests? Expected counts are the projected frequencies in each cell if the null hypothesis is true (aka, no association between the variables.) Given the follow 2x2 table of outcome (O) and exposure (E) as an
33,593
What is the definition of expected counts in chi square tests?
Suppose, you have observed data arranged. The total data = n. But, you want to test whether actual outcomes follows any distribution(standard or got-from-expert). So, you can get: $$\text{Expected outcome}=n\times Pr(\text{that outcome})$$ or for expected values in contingency table: $$\text{Expected outcome}=\frac{(\text{sum of data in that row})\times(\text{sum of data in that column})}{\text{total data}}$$
What is the definition of expected counts in chi square tests?
Suppose, you have observed data arranged. The total data = n. But, you want to test whether actual outcomes follows any distribution(standard or got-from-expert). So, you can get: $$\text{Expected out
What is the definition of expected counts in chi square tests? Suppose, you have observed data arranged. The total data = n. But, you want to test whether actual outcomes follows any distribution(standard or got-from-expert). So, you can get: $$\text{Expected outcome}=n\times Pr(\text{that outcome})$$ or for expected values in contingency table: $$\text{Expected outcome}=\frac{(\text{sum of data in that row})\times(\text{sum of data in that column})}{\text{total data}}$$
What is the definition of expected counts in chi square tests? Suppose, you have observed data arranged. The total data = n. But, you want to test whether actual outcomes follows any distribution(standard or got-from-expert). So, you can get: $$\text{Expected out
33,594
What is the definition of expected counts in chi square tests?
The other answers don't really explain where the formula for the expected counts comes from. Here's my attempt. Consider the following example (data taken from this site). \begin{bmatrix} \ & \text{Effect 1} & \text{Effect 2} & \text{Totals}\\ \text{group A} & 300 & 460 & 760\\ \text{group B} & 249 & 95 & 344\\ \text{Totals} & 549 & 555 & 1104\\ \end{bmatrix} In a Chi-squared test, we want to compare the observed counts vs the expected counts under the assumption of independence. But how do we determine the expected counts? Firstly, observe that $\frac{760}{1104}$ of the individuals are in group A. Likewise, observe that $\frac{549}{1104}$ have effect 1. If we assume that these two events are independent, then the probability of these two events is the product of the probabilities. I.e. if we call these events $A,B$, then assuming they are independent then $P(A\cap B)=P(A)\cdot P(B)$. Thus in our example, if the independence assumption holds, we have that the probability of being in group A and having effect 1 is: $$ \frac{760}{1104} \cdot \frac{549}{1104} = 34.23\%$$ Since there are 1104 people total, and 34.23% of them are expected to be in group A and have effect 1, we expect $$ 1104\cdot.3423 = 377.93$$ people to be in the relevant cell of the table (as opposed to the 300 we actually observed). Combining these two steps and simplifying with algebra the formula becomes: $$ \underbrace{\frac{760}{1104} \cdot \frac{549}{1104}}_{=34.23\%} \cdot 1104 = \frac{760\cdot 549}{1104} = 377.93$$ Thus, we've shown $$\text{Expected count}=\frac{(\text{sum of data in that row})\times(\text{sum of data in that column})}{\text{total data}}$$ as claimed. Try to calculate the expected values for the other cells in the table. The answers are shown here.
What is the definition of expected counts in chi square tests?
The other answers don't really explain where the formula for the expected counts comes from. Here's my attempt. Consider the following example (data taken from this site). \begin{bmatrix} \ & \text{E
What is the definition of expected counts in chi square tests? The other answers don't really explain where the formula for the expected counts comes from. Here's my attempt. Consider the following example (data taken from this site). \begin{bmatrix} \ & \text{Effect 1} & \text{Effect 2} & \text{Totals}\\ \text{group A} & 300 & 460 & 760\\ \text{group B} & 249 & 95 & 344\\ \text{Totals} & 549 & 555 & 1104\\ \end{bmatrix} In a Chi-squared test, we want to compare the observed counts vs the expected counts under the assumption of independence. But how do we determine the expected counts? Firstly, observe that $\frac{760}{1104}$ of the individuals are in group A. Likewise, observe that $\frac{549}{1104}$ have effect 1. If we assume that these two events are independent, then the probability of these two events is the product of the probabilities. I.e. if we call these events $A,B$, then assuming they are independent then $P(A\cap B)=P(A)\cdot P(B)$. Thus in our example, if the independence assumption holds, we have that the probability of being in group A and having effect 1 is: $$ \frac{760}{1104} \cdot \frac{549}{1104} = 34.23\%$$ Since there are 1104 people total, and 34.23% of them are expected to be in group A and have effect 1, we expect $$ 1104\cdot.3423 = 377.93$$ people to be in the relevant cell of the table (as opposed to the 300 we actually observed). Combining these two steps and simplifying with algebra the formula becomes: $$ \underbrace{\frac{760}{1104} \cdot \frac{549}{1104}}_{=34.23\%} \cdot 1104 = \frac{760\cdot 549}{1104} = 377.93$$ Thus, we've shown $$\text{Expected count}=\frac{(\text{sum of data in that row})\times(\text{sum of data in that column})}{\text{total data}}$$ as claimed. Try to calculate the expected values for the other cells in the table. The answers are shown here.
What is the definition of expected counts in chi square tests? The other answers don't really explain where the formula for the expected counts comes from. Here's my attempt. Consider the following example (data taken from this site). \begin{bmatrix} \ & \text{E
33,595
Caret package in R - get top Variable of Importance [closed]
What is the issue with #1? It runs fine for me and the result of the call to varImp() produces the following, ordered most to least important: > varImp(modelFit) rpart variable importance Overall V5 100.000 V4 38.390 V3 38.362 V2 5.581 V1 0.000 EDIT Based on Question clarification: I am sure there are better ways, but here is how I might do it: ImpMeasure<-data.frame(varImp(modelFit)$importance) ImpMeasure$Vars<-row.names(ImpMeasure) ImpMeasure[order(-ImpMeasure$Overall),][1:3,] Regarding #2, you need to add importance=TRUE in order to tell randomForest to calculate them. > modelFit <- train( V6~.,data=training, method="rf" ,importance = TRUE) > varImp(modelFit) rf variable importance Overall V5 100.000 V3 22.746 V2 21.136 V4 3.797 V1 0.000
Caret package in R - get top Variable of Importance [closed]
What is the issue with #1? It runs fine for me and the result of the call to varImp() produces the following, ordered most to least important: > varImp(modelFit) rpart variable importance Overall
Caret package in R - get top Variable of Importance [closed] What is the issue with #1? It runs fine for me and the result of the call to varImp() produces the following, ordered most to least important: > varImp(modelFit) rpart variable importance Overall V5 100.000 V4 38.390 V3 38.362 V2 5.581 V1 0.000 EDIT Based on Question clarification: I am sure there are better ways, but here is how I might do it: ImpMeasure<-data.frame(varImp(modelFit)$importance) ImpMeasure$Vars<-row.names(ImpMeasure) ImpMeasure[order(-ImpMeasure$Overall),][1:3,] Regarding #2, you need to add importance=TRUE in order to tell randomForest to calculate them. > modelFit <- train( V6~.,data=training, method="rf" ,importance = TRUE) > varImp(modelFit) rf variable importance Overall V5 100.000 V3 22.746 V2 21.136 V4 3.797 V1 0.000
Caret package in R - get top Variable of Importance [closed] What is the issue with #1? It runs fine for me and the result of the call to varImp() produces the following, ordered most to least important: > varImp(modelFit) rpart variable importance Overall
33,596
Caret package in R - get top Variable of Importance [closed]
Below is a dplyr option using pipes. It does seems strange that this is so hard to access. library(dplyr) col_index <- varImp(modelFit)$importance %>% mutate(names=row.names(.)) %>% arrange(-Overall) If you want the top three, then this should work: imp_names <- col_index$names[1:3] You can also subset the original data frame like this: Sonar_imp <- Sonar[,imp_names]
Caret package in R - get top Variable of Importance [closed]
Below is a dplyr option using pipes. It does seems strange that this is so hard to access. library(dplyr) col_index <- varImp(modelFit)$importance %>% mutate(names=row.names(.)) %>% arrange(-Ove
Caret package in R - get top Variable of Importance [closed] Below is a dplyr option using pipes. It does seems strange that this is so hard to access. library(dplyr) col_index <- varImp(modelFit)$importance %>% mutate(names=row.names(.)) %>% arrange(-Overall) If you want the top three, then this should work: imp_names <- col_index$names[1:3] You can also subset the original data frame like this: Sonar_imp <- Sonar[,imp_names]
Caret package in R - get top Variable of Importance [closed] Below is a dplyr option using pipes. It does seems strange that this is so hard to access. library(dplyr) col_index <- varImp(modelFit)$importance %>% mutate(names=row.names(.)) %>% arrange(-Ove
33,597
Caret package in R - get top Variable of Importance [closed]
This should do the trick: rownames(varImp(modelFit)$importance)[1:3]
Caret package in R - get top Variable of Importance [closed]
This should do the trick: rownames(varImp(modelFit)$importance)[1:3]
Caret package in R - get top Variable of Importance [closed] This should do the trick: rownames(varImp(modelFit)$importance)[1:3]
Caret package in R - get top Variable of Importance [closed] This should do the trick: rownames(varImp(modelFit)$importance)[1:3]
33,598
Why is a zero-intercept linear regression model predicts better than a model with an intercept?
Look carefully at how the rmse or other statistic is computed when comparing no-intercept models to intercept models. Sometimes the assumptions and calculations are different between the 2 models and one may fit worse, but look better because it is being divided by something much larger. Without a reproducible example it is difficult to tell what may be contributing.
Why is a zero-intercept linear regression model predicts better than a model with an intercept?
Look carefully at how the rmse or other statistic is computed when comparing no-intercept models to intercept models. Sometimes the assumptions and calculations are different between the 2 models and
Why is a zero-intercept linear regression model predicts better than a model with an intercept? Look carefully at how the rmse or other statistic is computed when comparing no-intercept models to intercept models. Sometimes the assumptions and calculations are different between the 2 models and one may fit worse, but look better because it is being divided by something much larger. Without a reproducible example it is difficult to tell what may be contributing.
Why is a zero-intercept linear regression model predicts better than a model with an intercept? Look carefully at how the rmse or other statistic is computed when comparing no-intercept models to intercept models. Sometimes the assumptions and calculations are different between the 2 models and
33,599
Why is a zero-intercept linear regression model predicts better than a model with an intercept?
I don't think you should choose models simply because they work better in a particular sample, although it is good that you used a training and validation sample. Rather, look at what the models say about your situation. In some cases a zero-intercept model makes sense. If the DV ought to be 0 when all the IVs are 0, then use a zero-intercept model. Otherwise, don't. Substantive knowledge should guide statistics, not the other way around
Why is a zero-intercept linear regression model predicts better than a model with an intercept?
I don't think you should choose models simply because they work better in a particular sample, although it is good that you used a training and validation sample. Rather, look at what the models say a
Why is a zero-intercept linear regression model predicts better than a model with an intercept? I don't think you should choose models simply because they work better in a particular sample, although it is good that you used a training and validation sample. Rather, look at what the models say about your situation. In some cases a zero-intercept model makes sense. If the DV ought to be 0 when all the IVs are 0, then use a zero-intercept model. Otherwise, don't. Substantive knowledge should guide statistics, not the other way around
Why is a zero-intercept linear regression model predicts better than a model with an intercept? I don't think you should choose models simply because they work better in a particular sample, although it is good that you used a training and validation sample. Rather, look at what the models say a
33,600
Why is a zero-intercept linear regression model predicts better than a model with an intercept?
A no intercept model may make sense if two conditions are met. First, there should be a reasonable subject matter knowledge expectation for the intercept to be zero. Second, there should be a reasonable subject matter knowledge expection for the regression line to remain a straight line as you approach zero. Even if both conditions are satisfied, it is wise to run an analysis with an intercept term and verify that the intercept is not significantly different from zero. (I am assuming that you are talking about a continuous Y and a continuous X.)
Why is a zero-intercept linear regression model predicts better than a model with an intercept?
A no intercept model may make sense if two conditions are met. First, there should be a reasonable subject matter knowledge expectation for the intercept to be zero. Second, there should be a reason
Why is a zero-intercept linear regression model predicts better than a model with an intercept? A no intercept model may make sense if two conditions are met. First, there should be a reasonable subject matter knowledge expectation for the intercept to be zero. Second, there should be a reasonable subject matter knowledge expection for the regression line to remain a straight line as you approach zero. Even if both conditions are satisfied, it is wise to run an analysis with an intercept term and verify that the intercept is not significantly different from zero. (I am assuming that you are talking about a continuous Y and a continuous X.)
Why is a zero-intercept linear regression model predicts better than a model with an intercept? A no intercept model may make sense if two conditions are met. First, there should be a reasonable subject matter knowledge expectation for the intercept to be zero. Second, there should be a reason