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
11,801
Whether to delete cases that are flagged as outliers by statistical software when performing multiple regression?
(late add: this topic has some whiskers on it. But I'm just seeing it for the first time.) I disagree strongly with some of User603's premises. Some of this reinforces what Charlie said above. In the abstract, there is no OBJECTIVE definition of an outlier, UNTIL you mentally or formally propose a data-generating model. I view outliers as the gods possibly trying to tell me I'm not as smart as I think I am, unless I can attribute those outliers, with very high certainty, to measurement or data collection errors. Tossing data that inconveniently does not fit your model is a very dubious practice, because it makes the model look stronger and more certain than it really is. Even when explanation is the goal, if you suspect outliers may be present, then re-sampling 500 times is a good technique for demonstrating how certain/uncertain you really are with your model. In a production mode for predictive models, I am opposed to tossing even KNOWN BAD DATA from the training dataset ... UNLESS the cause of the bad data has been fixed, so that similar bad data will not be showing up in the future, in the data to be scored. Real world model performance tracking has to include how well your model does on bad data, as long as similar bad data is still flowing in as part of the data stream.
Whether to delete cases that are flagged as outliers by statistical software when performing multipl
(late add: this topic has some whiskers on it. But I'm just seeing it for the first time.) I disagree strongly with some of User603's premises. Some of this reinforces what Charlie said above. In the
Whether to delete cases that are flagged as outliers by statistical software when performing multiple regression? (late add: this topic has some whiskers on it. But I'm just seeing it for the first time.) I disagree strongly with some of User603's premises. Some of this reinforces what Charlie said above. In the abstract, there is no OBJECTIVE definition of an outlier, UNTIL you mentally or formally propose a data-generating model. I view outliers as the gods possibly trying to tell me I'm not as smart as I think I am, unless I can attribute those outliers, with very high certainty, to measurement or data collection errors. Tossing data that inconveniently does not fit your model is a very dubious practice, because it makes the model look stronger and more certain than it really is. Even when explanation is the goal, if you suspect outliers may be present, then re-sampling 500 times is a good technique for demonstrating how certain/uncertain you really are with your model. In a production mode for predictive models, I am opposed to tossing even KNOWN BAD DATA from the training dataset ... UNLESS the cause of the bad data has been fixed, so that similar bad data will not be showing up in the future, in the data to be scored. Real world model performance tracking has to include how well your model does on bad data, as long as similar bad data is still flowing in as part of the data stream.
Whether to delete cases that are flagged as outliers by statistical software when performing multipl (late add: this topic has some whiskers on it. But I'm just seeing it for the first time.) I disagree strongly with some of User603's premises. Some of this reinforces what Charlie said above. In the
11,802
Best term for made-up data?
I would probably call this "synthetic" or "artificial" data, though I might also call it "simulated" (the simulation is just very simple).
Best term for made-up data?
I would probably call this "synthetic" or "artificial" data, though I might also call it "simulated" (the simulation is just very simple).
Best term for made-up data? I would probably call this "synthetic" or "artificial" data, though I might also call it "simulated" (the simulation is just very simple).
Best term for made-up data? I would probably call this "synthetic" or "artificial" data, though I might also call it "simulated" (the simulation is just very simple).
11,803
Best term for made-up data?
If you want to refer to your data as fictitious you'd be in good company, as that's the term Francis Anscombe used to describe his now famous quartet. From Anscombe, F. J. (1973). "Graphs in Statistical Analysis", Am. Stat. 27 (1): Some of these points are illustrated by four fictitious data sets, each consisting of eleven (x, y) pairs, shown in the table. But I think your caution is well placed, as my OED (v4) seems to indicates that this use of fictitious is obsolete fictitious, a. (fɪkˈtɪʃəs) [f. L. fictīci-us (f. fingĕre to fashion, feign) + -ous: see -itious.] 1.1 †a.1.a Artificial as opposed to natural (obs.). b.1.b Counterfeit, ‘imitation’, sham; not genuine.
Best term for made-up data?
If you want to refer to your data as fictitious you'd be in good company, as that's the term Francis Anscombe used to describe his now famous quartet. From Anscombe, F. J. (1973). "Graphs in Statisti
Best term for made-up data? If you want to refer to your data as fictitious you'd be in good company, as that's the term Francis Anscombe used to describe his now famous quartet. From Anscombe, F. J. (1973). "Graphs in Statistical Analysis", Am. Stat. 27 (1): Some of these points are illustrated by four fictitious data sets, each consisting of eleven (x, y) pairs, shown in the table. But I think your caution is well placed, as my OED (v4) seems to indicates that this use of fictitious is obsolete fictitious, a. (fɪkˈtɪʃəs) [f. L. fictīci-us (f. fingĕre to fashion, feign) + -ous: see -itious.] 1.1 †a.1.a Artificial as opposed to natural (obs.). b.1.b Counterfeit, ‘imitation’, sham; not genuine.
Best term for made-up data? If you want to refer to your data as fictitious you'd be in good company, as that's the term Francis Anscombe used to describe his now famous quartet. From Anscombe, F. J. (1973). "Graphs in Statisti
11,804
Best term for made-up data?
In IT we often call it mockup data, which can presented through a mockup (application). The mockup data can also be presented through a fully functional application, for instance to test the functionality of the application in a controlled manner.
Best term for made-up data?
In IT we often call it mockup data, which can presented through a mockup (application). The mockup data can also be presented through a fully functional application, for instance to test the functiona
Best term for made-up data? In IT we often call it mockup data, which can presented through a mockup (application). The mockup data can also be presented through a fully functional application, for instance to test the functionality of the application in a controlled manner.
Best term for made-up data? In IT we often call it mockup data, which can presented through a mockup (application). The mockup data can also be presented through a fully functional application, for instance to test the functiona
11,805
Best term for made-up data?
I've seen repeated suggestions for the term "synthetic data". That term however has a broadly used, and very different meaning from what you want to express: https://en.wikipedia.org/wiki/Synthetic_data I am not sure there is a generally accepted scientific term, but the term "example data" seems hard to misunderstand?
Best term for made-up data?
I've seen repeated suggestions for the term "synthetic data". That term however has a broadly used, and very different meaning from what you want to express: https://en.wikipedia.org/wiki/Synthetic_da
Best term for made-up data? I've seen repeated suggestions for the term "synthetic data". That term however has a broadly used, and very different meaning from what you want to express: https://en.wikipedia.org/wiki/Synthetic_data I am not sure there is a generally accepted scientific term, but the term "example data" seems hard to misunderstand?
Best term for made-up data? I've seen repeated suggestions for the term "synthetic data". That term however has a broadly used, and very different meaning from what you want to express: https://en.wikipedia.org/wiki/Synthetic_da
11,806
Best term for made-up data?
I've encountered the term 'fake data' a fair amount. I guess it could have some negative connotations but I've heard it often enough that it doesn't register negatively at all for me. FWIW, Andrew Gelman uses it too: https://statmodeling.stat.columbia.edu/2009/09/04/fake-data_simul/ https://statmodeling.stat.columbia.edu/2019/03/23/yes-i-really-really-really-like-fake-data-simulation-and-i-cant-stop-talking-about-it/ https://books.google.dk/books?id=lV3DIdV0F9AC&pg=PA155&lpg=PA155&dq=fake+data+simulation&source=bl&ots=6ljKB6StQ4&sig=ACfU3U17GLP_84q_HfIQB4u5O6wV0yA2Aw&hl=en&sa=X&ved=2ahUKEwiF2_eB0uvjAhWswcQBHSn5Cn04ChDoATAAegQICRAB#v=onepage&q=fake%20data%20simulation&f=false A quick google search for 'fake data' turns up a lot of results that seem to be using the term similarly: https://scientistseessquirrel.wordpress.com/2016/03/10/good-uses-for-fake-data-part-1/ http://modernstatisticalworkflow.blogspot.com/2017/04/an-easy-way-to-simulate-fake-data-from.html https://clayford.github.io/dwir/dwr_12_generating_data.html And there's even a fakeR package, which suggests that this is relatively common: https://cran.r-project.org/web/packages/fakeR/fakeR.pdf
Best term for made-up data?
I've encountered the term 'fake data' a fair amount. I guess it could have some negative connotations but I've heard it often enough that it doesn't register negatively at all for me. FWIW, Andrew Ge
Best term for made-up data? I've encountered the term 'fake data' a fair amount. I guess it could have some negative connotations but I've heard it often enough that it doesn't register negatively at all for me. FWIW, Andrew Gelman uses it too: https://statmodeling.stat.columbia.edu/2009/09/04/fake-data_simul/ https://statmodeling.stat.columbia.edu/2019/03/23/yes-i-really-really-really-like-fake-data-simulation-and-i-cant-stop-talking-about-it/ https://books.google.dk/books?id=lV3DIdV0F9AC&pg=PA155&lpg=PA155&dq=fake+data+simulation&source=bl&ots=6ljKB6StQ4&sig=ACfU3U17GLP_84q_HfIQB4u5O6wV0yA2Aw&hl=en&sa=X&ved=2ahUKEwiF2_eB0uvjAhWswcQBHSn5Cn04ChDoATAAegQICRAB#v=onepage&q=fake%20data%20simulation&f=false A quick google search for 'fake data' turns up a lot of results that seem to be using the term similarly: https://scientistseessquirrel.wordpress.com/2016/03/10/good-uses-for-fake-data-part-1/ http://modernstatisticalworkflow.blogspot.com/2017/04/an-easy-way-to-simulate-fake-data-from.html https://clayford.github.io/dwir/dwr_12_generating_data.html And there's even a fakeR package, which suggests that this is relatively common: https://cran.r-project.org/web/packages/fakeR/fakeR.pdf
Best term for made-up data? I've encountered the term 'fake data' a fair amount. I guess it could have some negative connotations but I've heard it often enough that it doesn't register negatively at all for me. FWIW, Andrew Ge
11,807
Best term for made-up data?
I use a different word depending on the manner in which I use the data. If I have found the made-up dataset lying around and have pointed my algorithm at it in a confirmatory manner, then the word "synthetic" is fine. However, oftentimes whenever I use this type of data, I have invented the data with the specific intent of showing off the capabilities of my algorithm. In other words, I invented data for the specific purpose of getting "good results". In such circumstances, I am fond of the term "contrived" along with an explanation of my expectations for the data. This is because I don't want anyone to make the mistake of thinking that I pointed my algorithm at some arbitrary synthetic dataset I found lying around and it really worked out well. If I have cherry-picked data (to the point of actually making it up) specifically to make my algorithm work out well, I say so. This is because such results provide evidence that my algorithm can work out well, but provide only very weak evidence that one might expect the algorithm to work out well in general. The word "contrived" really sums up nicely the fact that I have chosen the data with "good results" in mind, a priori. "does that give the impression of fraudulent data?" No, but, it is important to be clear about the source of any dataset and your a priori expectations as the experimenter when reporting your results on any dataset. The term "fraud" explicitly includes an aspect of having covered something up or having outright lied. The #1 way to avoid commission of fraud in science is to simply be honest and forthright about the nature of your data and your expectations. In other words, if your data are fabricated and you fail to say as much in any way, and there is some kind of expectation that the data are not fabricated or, worse, you claim that the data are gathered in some non-fabricated sort of way, then that is "fraud". Don't do that thing. If you want to use some synonym for the term "fabricated" that "sounds better", such as "synthetic", nobody will fault you, but at the same time I don't think that anyone will notice the difference except for you. A side note: Less obvious are circumstances where one claims to have had a priori expectations that are actually post hoc explanations. This is also fraudulent analysis of data. There is a danger of this when one chooses data specifically with the intent of "showing off" the capabilities of an algorithm, which is frequently the case with synthetic data. To be clear about why this is the case, consider that the "normal" scientific method works something like so: 1) A population $D$ is chosen 2) A hypothesis $H$ is concieved 3) $H$ is tested against $D$ (or some sample chosen from $D$). Science doesn't have to work within this narrow definition, but this is what is called "confirmatory" analysis, and is generally considered the strongest form of evidence one can provide. Since the order of events correlates with the strength of evidence, it is important to specifically document them. Notably, in the case of "contrived" data, the process often works more like so: 1) A hypothesis $H$ is conceived, 2) A population $D$ is chosen, 3) $H$ is tested against $D$. If you are testing an algorithm, for example, then the hypothesis that your fancy new algorithm "does a good job" might occur prior to the invention of the synthetic dataset. If this is the case, you should mention it. At the very least you should not purport that events transpired in a "confirmatory" manner, because that would lead readers to conclude that your evidence is stronger than it actually is. There is no problem with doing this, so long as you are honest and forthright about what you have done. If you have gone through pains to create a dataset that gives "good results", do say so. As long as you let the reader know the steps that you have taken in your data analysis, they have the information necessary to effectively weigh the evidence for or against your hypotheses. When you are not honest or are not forthright, then this may give the impression that your evidence is stronger than it really is. When you are KNOWINGLY less than honest and forthright for the sake of making your evidence seem stronger than it really is, then that is, indeed, fraudulent. In any case, this is why I prefer the term "contrived" for such datasets, along with a short explanation that they are, indeed, chosen with a hypothesis in mind. "Contrived" conveys the sense that not only did I create a synthetic dataset, but I did so with particular intentions that reflect the fact that my hypothesis was already in place before the creation of my dataset. To illustrate by an example: You create an algorithm for analysis of arbitrary time-series. You hypothesize that this algorithm will give "good results" when pointed at time-series. Consider, now, the following two possibilities: 1) You create some synthetic data that looks like the sort of thing that you expect your algorithm to perform well on. You analyze this data and the algorithm performs well. 2) You grab some synthetic datasets because they are available why not. You analyze this data and the algorithm performs well. Which of these two circumstances provides the better evidence that your algorithm performs well on arbitrary time-series? Clearly, it is option 2. However, it might be easy to report in either option 1 or option 2 that "we applied algorithm $A$ to synthetic dataset $D$. Results are shown in Figure $x.y$." In the absence of any context, a reader might reasonably assume that these results are confirmatory (option 2), when, in the case of option 1, they are not. The reader has therefore, in option 1, been given the impression that the evidence is stronger than it really is. tl;dr Use whatever term you like, "synthetic", "contrived", "fabricated", "fictitious". However, the term that you use is insufficient to ensure that your results are not misleading. Ensure that you are clear in your report about how the data came about, including your expectations for the data and the reasons why you chose the data that you chose.
Best term for made-up data?
I use a different word depending on the manner in which I use the data. If I have found the made-up dataset lying around and have pointed my algorithm at it in a confirmatory manner, then the word "s
Best term for made-up data? I use a different word depending on the manner in which I use the data. If I have found the made-up dataset lying around and have pointed my algorithm at it in a confirmatory manner, then the word "synthetic" is fine. However, oftentimes whenever I use this type of data, I have invented the data with the specific intent of showing off the capabilities of my algorithm. In other words, I invented data for the specific purpose of getting "good results". In such circumstances, I am fond of the term "contrived" along with an explanation of my expectations for the data. This is because I don't want anyone to make the mistake of thinking that I pointed my algorithm at some arbitrary synthetic dataset I found lying around and it really worked out well. If I have cherry-picked data (to the point of actually making it up) specifically to make my algorithm work out well, I say so. This is because such results provide evidence that my algorithm can work out well, but provide only very weak evidence that one might expect the algorithm to work out well in general. The word "contrived" really sums up nicely the fact that I have chosen the data with "good results" in mind, a priori. "does that give the impression of fraudulent data?" No, but, it is important to be clear about the source of any dataset and your a priori expectations as the experimenter when reporting your results on any dataset. The term "fraud" explicitly includes an aspect of having covered something up or having outright lied. The #1 way to avoid commission of fraud in science is to simply be honest and forthright about the nature of your data and your expectations. In other words, if your data are fabricated and you fail to say as much in any way, and there is some kind of expectation that the data are not fabricated or, worse, you claim that the data are gathered in some non-fabricated sort of way, then that is "fraud". Don't do that thing. If you want to use some synonym for the term "fabricated" that "sounds better", such as "synthetic", nobody will fault you, but at the same time I don't think that anyone will notice the difference except for you. A side note: Less obvious are circumstances where one claims to have had a priori expectations that are actually post hoc explanations. This is also fraudulent analysis of data. There is a danger of this when one chooses data specifically with the intent of "showing off" the capabilities of an algorithm, which is frequently the case with synthetic data. To be clear about why this is the case, consider that the "normal" scientific method works something like so: 1) A population $D$ is chosen 2) A hypothesis $H$ is concieved 3) $H$ is tested against $D$ (or some sample chosen from $D$). Science doesn't have to work within this narrow definition, but this is what is called "confirmatory" analysis, and is generally considered the strongest form of evidence one can provide. Since the order of events correlates with the strength of evidence, it is important to specifically document them. Notably, in the case of "contrived" data, the process often works more like so: 1) A hypothesis $H$ is conceived, 2) A population $D$ is chosen, 3) $H$ is tested against $D$. If you are testing an algorithm, for example, then the hypothesis that your fancy new algorithm "does a good job" might occur prior to the invention of the synthetic dataset. If this is the case, you should mention it. At the very least you should not purport that events transpired in a "confirmatory" manner, because that would lead readers to conclude that your evidence is stronger than it actually is. There is no problem with doing this, so long as you are honest and forthright about what you have done. If you have gone through pains to create a dataset that gives "good results", do say so. As long as you let the reader know the steps that you have taken in your data analysis, they have the information necessary to effectively weigh the evidence for or against your hypotheses. When you are not honest or are not forthright, then this may give the impression that your evidence is stronger than it really is. When you are KNOWINGLY less than honest and forthright for the sake of making your evidence seem stronger than it really is, then that is, indeed, fraudulent. In any case, this is why I prefer the term "contrived" for such datasets, along with a short explanation that they are, indeed, chosen with a hypothesis in mind. "Contrived" conveys the sense that not only did I create a synthetic dataset, but I did so with particular intentions that reflect the fact that my hypothesis was already in place before the creation of my dataset. To illustrate by an example: You create an algorithm for analysis of arbitrary time-series. You hypothesize that this algorithm will give "good results" when pointed at time-series. Consider, now, the following two possibilities: 1) You create some synthetic data that looks like the sort of thing that you expect your algorithm to perform well on. You analyze this data and the algorithm performs well. 2) You grab some synthetic datasets because they are available why not. You analyze this data and the algorithm performs well. Which of these two circumstances provides the better evidence that your algorithm performs well on arbitrary time-series? Clearly, it is option 2. However, it might be easy to report in either option 1 or option 2 that "we applied algorithm $A$ to synthetic dataset $D$. Results are shown in Figure $x.y$." In the absence of any context, a reader might reasonably assume that these results are confirmatory (option 2), when, in the case of option 1, they are not. The reader has therefore, in option 1, been given the impression that the evidence is stronger than it really is. tl;dr Use whatever term you like, "synthetic", "contrived", "fabricated", "fictitious". However, the term that you use is insufficient to ensure that your results are not misleading. Ensure that you are clear in your report about how the data came about, including your expectations for the data and the reasons why you chose the data that you chose.
Best term for made-up data? I use a different word depending on the manner in which I use the data. If I have found the made-up dataset lying around and have pointed my algorithm at it in a confirmatory manner, then the word "s
11,808
Best term for made-up data?
First, there's no reason to not call it a "dataset". There is no universally agreed upon term(s) for "fake" vs "simulated" vs ... data. If the goal is to be completely clear, it's best to actually devote a sentence, rather than a word, to qualify what this dataset is. After that, you can relax the designation and just refer to your data as data. "Synthetic", "artificial" does not distinguish from other MCMC sampled "simulated" datasets in my mind. Using a quasirandom number generator with a fixed seed (as proper training would dictate) also creates a synthetic or artificial dataset. If the point of curating a dataset for a specific illustration, rather than generating an instance or realization from a probability model, I think it's better to call such a dataset an "example dataset". Data like these are akin to Anscombe's quartet: totally abstract and not-plausible, but meant to illustrate a point.
Best term for made-up data?
First, there's no reason to not call it a "dataset". There is no universally agreed upon term(s) for "fake" vs "simulated" vs ... data. If the goal is to be completely clear, it's best to actually dev
Best term for made-up data? First, there's no reason to not call it a "dataset". There is no universally agreed upon term(s) for "fake" vs "simulated" vs ... data. If the goal is to be completely clear, it's best to actually devote a sentence, rather than a word, to qualify what this dataset is. After that, you can relax the designation and just refer to your data as data. "Synthetic", "artificial" does not distinguish from other MCMC sampled "simulated" datasets in my mind. Using a quasirandom number generator with a fixed seed (as proper training would dictate) also creates a synthetic or artificial dataset. If the point of curating a dataset for a specific illustration, rather than generating an instance or realization from a probability model, I think it's better to call such a dataset an "example dataset". Data like these are akin to Anscombe's quartet: totally abstract and not-plausible, but meant to illustrate a point.
Best term for made-up data? First, there's no reason to not call it a "dataset". There is no universally agreed upon term(s) for "fake" vs "simulated" vs ... data. If the goal is to be completely clear, it's best to actually dev
11,809
Best term for made-up data?
In biology, analyses are sometimes demonstrated using a dataset of mythical animals. Whether or not to explicitly state that the data are simulated is up to the author/reviewer. An ecologist’s guide to the animal model, 2009 These tutorials describe a series of quantitative genetic analyses on a population of gryphons (reflecting a compromise between the avian and mammalian biases of the authors). As the gryphon is a mythical beast the data provided were necessarily simulated. Fixed effect variance and the estimation of repeatabilities and heritabilities:Issues and solutions, 2017 To illustrate this, let us go back to Wilson (2008)’s unicorn dataset. It is a known fact that in unicorns, horn length varies according to the individual body mass (slope: β = 0.403 for a full model including age, sex and their interaction).
Best term for made-up data?
In biology, analyses are sometimes demonstrated using a dataset of mythical animals. Whether or not to explicitly state that the data are simulated is up to the author/reviewer. An ecologist’s guide t
Best term for made-up data? In biology, analyses are sometimes demonstrated using a dataset of mythical animals. Whether or not to explicitly state that the data are simulated is up to the author/reviewer. An ecologist’s guide to the animal model, 2009 These tutorials describe a series of quantitative genetic analyses on a population of gryphons (reflecting a compromise between the avian and mammalian biases of the authors). As the gryphon is a mythical beast the data provided were necessarily simulated. Fixed effect variance and the estimation of repeatabilities and heritabilities:Issues and solutions, 2017 To illustrate this, let us go back to Wilson (2008)’s unicorn dataset. It is a known fact that in unicorns, horn length varies according to the individual body mass (slope: β = 0.403 for a full model including age, sex and their interaction).
Best term for made-up data? In biology, analyses are sometimes demonstrated using a dataset of mythical animals. Whether or not to explicitly state that the data are simulated is up to the author/reviewer. An ecologist’s guide t
11,810
Best term for made-up data?
Intuitively I would go to the term 'Dummy data', in the same sense that "Lorem ipsum..." is called 'Dummy text'. The word 'Dummy' is quite general and easy to understand for people from various backgrounds and is therfore less likely to be misinterpreted by readers of a less statistical background.
Best term for made-up data?
Intuitively I would go to the term 'Dummy data', in the same sense that "Lorem ipsum..." is called 'Dummy text'. The word 'Dummy' is quite general and easy to understand for people from various backgr
Best term for made-up data? Intuitively I would go to the term 'Dummy data', in the same sense that "Lorem ipsum..." is called 'Dummy text'. The word 'Dummy' is quite general and easy to understand for people from various backgrounds and is therfore less likely to be misinterpreted by readers of a less statistical background.
Best term for made-up data? Intuitively I would go to the term 'Dummy data', in the same sense that "Lorem ipsum..." is called 'Dummy text'. The word 'Dummy' is quite general and easy to understand for people from various backgr
11,811
Best term for made-up data?
Data is Latin for given, that is used in modern times as a shorthand for given set of recorded facts. So in a way referring to fabricated recordings as some sort of given facts would be an open contradiction. However, due to the increasing use of data to refer simply to recordings - regardless of the original presumption of records being of facts - we happily understand each other when talking about recordings that may or may not be truthful - hence real/fake data. I will summarise my experience of ways to address fabricated recordings below. The label used depends whether one is assuming that we are talking of data as fabricated recordings that are intended to look reasonably realistic to enable further analysis, or data as a computational load. In analytics/data science/strategic consultancies circles, people address most frequently a fabricated set of recordings generated under realistic assumptions as synthetic data - and occasionally simulated data. Fabricated recordings created using crude assumptions are referred to as toy dataset. Among software engineers, fake data, dummy data, made-up data and mock-up data are frequent labels that mainly hint to recordings not necessarily meant to have realistic properties, but only share basic properties with the original data (age data is always numerical, email addresses always strings that contain “@“). Academic researchers would refer to a realistic set of fabricated recordings as pseudo-data, or simulated data. In some circles, if the fabricated set of observations is the result of a Monte Carlo simulation, it may be referred to colloquially as Monte Carlo. Semi-realistic recordings are commonly used for illustrative purpose or testing alternate hypotheses, and referred to as toy dataset
Best term for made-up data?
Data is Latin for given, that is used in modern times as a shorthand for given set of recorded facts. So in a way referring to fabricated recordings as some sort of given facts would be an open contra
Best term for made-up data? Data is Latin for given, that is used in modern times as a shorthand for given set of recorded facts. So in a way referring to fabricated recordings as some sort of given facts would be an open contradiction. However, due to the increasing use of data to refer simply to recordings - regardless of the original presumption of records being of facts - we happily understand each other when talking about recordings that may or may not be truthful - hence real/fake data. I will summarise my experience of ways to address fabricated recordings below. The label used depends whether one is assuming that we are talking of data as fabricated recordings that are intended to look reasonably realistic to enable further analysis, or data as a computational load. In analytics/data science/strategic consultancies circles, people address most frequently a fabricated set of recordings generated under realistic assumptions as synthetic data - and occasionally simulated data. Fabricated recordings created using crude assumptions are referred to as toy dataset. Among software engineers, fake data, dummy data, made-up data and mock-up data are frequent labels that mainly hint to recordings not necessarily meant to have realistic properties, but only share basic properties with the original data (age data is always numerical, email addresses always strings that contain “@“). Academic researchers would refer to a realistic set of fabricated recordings as pseudo-data, or simulated data. In some circles, if the fabricated set of observations is the result of a Monte Carlo simulation, it may be referred to colloquially as Monte Carlo. Semi-realistic recordings are commonly used for illustrative purpose or testing alternate hypotheses, and referred to as toy dataset
Best term for made-up data? Data is Latin for given, that is used in modern times as a shorthand for given set of recorded facts. So in a way referring to fabricated recordings as some sort of given facts would be an open contra
11,812
Whats the relationship between $R^2$ and F-Test?
If all the assumptions hold and you have the correct form for $R^2$ then the usual F statistic can be computed as $F = \frac{ R^2 }{ 1- R^2} \times \frac{ \text{df}_2 }{ \text{df}_1 }$. This value can then be compared to the appropriate F distribution to do an F test. This can be derived/confirmed with basic algebra.
Whats the relationship between $R^2$ and F-Test?
If all the assumptions hold and you have the correct form for $R^2$ then the usual F statistic can be computed as $F = \frac{ R^2 }{ 1- R^2} \times \frac{ \text{df}_2 }{ \text{df}_1 }$. This value ca
Whats the relationship between $R^2$ and F-Test? If all the assumptions hold and you have the correct form for $R^2$ then the usual F statistic can be computed as $F = \frac{ R^2 }{ 1- R^2} \times \frac{ \text{df}_2 }{ \text{df}_1 }$. This value can then be compared to the appropriate F distribution to do an F test. This can be derived/confirmed with basic algebra.
Whats the relationship between $R^2$ and F-Test? If all the assumptions hold and you have the correct form for $R^2$ then the usual F statistic can be computed as $F = \frac{ R^2 }{ 1- R^2} \times \frac{ \text{df}_2 }{ \text{df}_1 }$. This value ca
11,813
Whats the relationship between $R^2$ and F-Test?
Recall that in a regression setting, the F statistic is expressed in the following way. $$ F = \frac{(TSS - RSS)/(p-1)}{RSS/(n-p)} $$ where TSS = total sum of squares and RSS = residual sum of squares, $p$ is the number of predictors (including the constant) and $n$ is the number of observations. This statistic has an $F$ distribution with degrees of freedom $p-1$ and $n-p$. Also recall that $$ R^2 = 1 - \frac{RSS}{TSS} = \frac{TSS - RSS}{TSS} $$ simple algebra will tell you that $$ R^2 = 1 - (1 + F \cdot \frac{p-1}{n-p})^{-1} $$ where F is the F statistic from above. This is the theoretical relationship between the F statistic (or the F test) and $R^2$. The practical interpretation is that a bigger $R^2$ lead to high values of F, so if $R^2$ is big (which means that a linear model fits the data well), then the corresponding F statistic should be large, which means that that there should be strong evidence that at least some of the coefficients are non-zero.
Whats the relationship between $R^2$ and F-Test?
Recall that in a regression setting, the F statistic is expressed in the following way. $$ F = \frac{(TSS - RSS)/(p-1)}{RSS/(n-p)} $$ where TSS = total sum of squares and RSS = residual sum of squares
Whats the relationship between $R^2$ and F-Test? Recall that in a regression setting, the F statistic is expressed in the following way. $$ F = \frac{(TSS - RSS)/(p-1)}{RSS/(n-p)} $$ where TSS = total sum of squares and RSS = residual sum of squares, $p$ is the number of predictors (including the constant) and $n$ is the number of observations. This statistic has an $F$ distribution with degrees of freedom $p-1$ and $n-p$. Also recall that $$ R^2 = 1 - \frac{RSS}{TSS} = \frac{TSS - RSS}{TSS} $$ simple algebra will tell you that $$ R^2 = 1 - (1 + F \cdot \frac{p-1}{n-p})^{-1} $$ where F is the F statistic from above. This is the theoretical relationship between the F statistic (or the F test) and $R^2$. The practical interpretation is that a bigger $R^2$ lead to high values of F, so if $R^2$ is big (which means that a linear model fits the data well), then the corresponding F statistic should be large, which means that that there should be strong evidence that at least some of the coefficients are non-zero.
Whats the relationship between $R^2$ and F-Test? Recall that in a regression setting, the F statistic is expressed in the following way. $$ F = \frac{(TSS - RSS)/(p-1)}{RSS/(n-p)} $$ where TSS = total sum of squares and RSS = residual sum of squares
11,814
Whats the relationship between $R^2$ and F-Test?
Intuitively, I like to think that the result of the F-ratio first gives a yes-no response to the the question, 'can I reject $H_0$?' (this is determined if the ratio is much larger than 1, or the p-value < $\alpha$). Then if I determine I can reject $H_0$, $R^2$ then indicates the strength of the relationship between. In other words, a large F-ratio indicates that there is a relationship. High $R^2$ then indicates how strong that relationship is.
Whats the relationship between $R^2$ and F-Test?
Intuitively, I like to think that the result of the F-ratio first gives a yes-no response to the the question, 'can I reject $H_0$?' (this is determined if the ratio is much larger than 1, or the p-va
Whats the relationship between $R^2$ and F-Test? Intuitively, I like to think that the result of the F-ratio first gives a yes-no response to the the question, 'can I reject $H_0$?' (this is determined if the ratio is much larger than 1, or the p-value < $\alpha$). Then if I determine I can reject $H_0$, $R^2$ then indicates the strength of the relationship between. In other words, a large F-ratio indicates that there is a relationship. High $R^2$ then indicates how strong that relationship is.
Whats the relationship between $R^2$ and F-Test? Intuitively, I like to think that the result of the F-ratio first gives a yes-no response to the the question, 'can I reject $H_0$?' (this is determined if the ratio is much larger than 1, or the p-va
11,815
Whats the relationship between $R^2$ and F-Test?
Also, quickly: R2 = F / (F + n-p/p-1) Eg, The R2 of a 1df F test = 2.53 with sample size 21, would be: R2 = 2.53 / (2.53+19) R2 = .1175
Whats the relationship between $R^2$ and F-Test?
Also, quickly: R2 = F / (F + n-p/p-1) Eg, The R2 of a 1df F test = 2.53 with sample size 21, would be: R2 = 2.53 / (2.53+19) R2 = .1175
Whats the relationship between $R^2$ and F-Test? Also, quickly: R2 = F / (F + n-p/p-1) Eg, The R2 of a 1df F test = 2.53 with sample size 21, would be: R2 = 2.53 / (2.53+19) R2 = .1175
Whats the relationship between $R^2$ and F-Test? Also, quickly: R2 = F / (F + n-p/p-1) Eg, The R2 of a 1df F test = 2.53 with sample size 21, would be: R2 = 2.53 / (2.53+19) R2 = .1175
11,816
Does mean = median imply that a unimodal distribution is symmetric?
Here is a small counterexample that is not symmetric: -3, -2, 0, 0, 1, 4 is unimodal with mode = median = mean = 0. Edit: An even smaller example is -2, -1, 0, 0, 3. If you want to imagine a random variable rather than a sample, take the support as {-2, -1, 0, 3} with probability mass function 0.2 on all of them except for 0 where it is 0.4.
Does mean = median imply that a unimodal distribution is symmetric?
Here is a small counterexample that is not symmetric: -3, -2, 0, 0, 1, 4 is unimodal with mode = median = mean = 0. Edit: An even smaller example is -2, -1, 0, 0, 3. If you want to imagine a random va
Does mean = median imply that a unimodal distribution is symmetric? Here is a small counterexample that is not symmetric: -3, -2, 0, 0, 1, 4 is unimodal with mode = median = mean = 0. Edit: An even smaller example is -2, -1, 0, 0, 3. If you want to imagine a random variable rather than a sample, take the support as {-2, -1, 0, 3} with probability mass function 0.2 on all of them except for 0 where it is 0.4.
Does mean = median imply that a unimodal distribution is symmetric? Here is a small counterexample that is not symmetric: -3, -2, 0, 0, 1, 4 is unimodal with mode = median = mean = 0. Edit: An even smaller example is -2, -1, 0, 0, 3. If you want to imagine a random va
11,817
Does mean = median imply that a unimodal distribution is symmetric?
This began as a comment but grew too long; I decided to make it into more of an answer. Alexis' fine answer deals with the immediate question (in short: i. that logically ${A\implies B}$ doesn't mean $B\implies A$; and ii. the reverse statement is actually false in general), and Silverfish gives counterexamples. I'd like to deal with some additional issues and point out some extensive answers already here which are related to some extent. The statement on the Wikipedia page that you quote is not strictly true either. Consider, for example, the Cauchy distribution, which is certainly symmetric about its median, but which doesn't have a mean. The statement needs a qualifier such as 'provided the mean and skewness are finite'. Even if we reduce it to the weaker statement in the first half of the first sentence, it still needs "provided the mean is finite". Your question partly conflates symmetry with zero skewness (I assume you intend third moment skewness, but a similar discussion could be written for other skewness measures). Having 0 skewness doesn't imply symmetry. The later part of your quote and the section from Wikipedia quoted by Alexis mention this, though the explanation given in the second quote could use some tweaking. This answer shows that the relationship between third moment skewness and the direction of the relationship between mean and median is weak (third moment skewness and second-Pearson skewness needn't correspond). Item 1. on this answer gives a discrete counterexample, similar to but different from the one given by Silverfish. Edit: I finally dug up the unimodal example I was actually looking for earlier. In this answer I mention the following family: $\frac{1}{24}\exp(-x^{1/4}) [1 -\alpha \sin(x^{1/4})]$ Taking two specific members (say the blue and green densities in the specific example at that linked answer, which have $\alpha=0$, and $\alpha=\frac{_1}{^2}$ respectively), and flipping one about the x-axis and taking a 50-50 mixture of the two, we would get a unimodal asymmetric density with all odd moments zero: (grey lines show the blue density flipped about the x-axis to make the asymmetry plain) Whuber gives another example here with zero skewness that's continuous, unimodal and asymmetric. I've reproduced his diagram: which shows the example and the same flipped about the mean (to clearly show the asymmetry) but you should go read the original, which contains a lot of useful information. [Whuber's answer here gives another asymmetric continuous family of distributions with all the same moments. Doing the same "choose two, flip one and take a 50-50 mixture" trick has the same outcome of asymmetric with all odd moments zero, but I think it doesn't give unimodal results here (though perhaps there are some examples).] The answer here discusses the relationship between mean, median and mode. This answer discusses hypothesis tests of symmetry.
Does mean = median imply that a unimodal distribution is symmetric?
This began as a comment but grew too long; I decided to make it into more of an answer. Alexis' fine answer deals with the immediate question (in short: i. that logically ${A\implies B}$ doesn't mean
Does mean = median imply that a unimodal distribution is symmetric? This began as a comment but grew too long; I decided to make it into more of an answer. Alexis' fine answer deals with the immediate question (in short: i. that logically ${A\implies B}$ doesn't mean $B\implies A$; and ii. the reverse statement is actually false in general), and Silverfish gives counterexamples. I'd like to deal with some additional issues and point out some extensive answers already here which are related to some extent. The statement on the Wikipedia page that you quote is not strictly true either. Consider, for example, the Cauchy distribution, which is certainly symmetric about its median, but which doesn't have a mean. The statement needs a qualifier such as 'provided the mean and skewness are finite'. Even if we reduce it to the weaker statement in the first half of the first sentence, it still needs "provided the mean is finite". Your question partly conflates symmetry with zero skewness (I assume you intend third moment skewness, but a similar discussion could be written for other skewness measures). Having 0 skewness doesn't imply symmetry. The later part of your quote and the section from Wikipedia quoted by Alexis mention this, though the explanation given in the second quote could use some tweaking. This answer shows that the relationship between third moment skewness and the direction of the relationship between mean and median is weak (third moment skewness and second-Pearson skewness needn't correspond). Item 1. on this answer gives a discrete counterexample, similar to but different from the one given by Silverfish. Edit: I finally dug up the unimodal example I was actually looking for earlier. In this answer I mention the following family: $\frac{1}{24}\exp(-x^{1/4}) [1 -\alpha \sin(x^{1/4})]$ Taking two specific members (say the blue and green densities in the specific example at that linked answer, which have $\alpha=0$, and $\alpha=\frac{_1}{^2}$ respectively), and flipping one about the x-axis and taking a 50-50 mixture of the two, we would get a unimodal asymmetric density with all odd moments zero: (grey lines show the blue density flipped about the x-axis to make the asymmetry plain) Whuber gives another example here with zero skewness that's continuous, unimodal and asymmetric. I've reproduced his diagram: which shows the example and the same flipped about the mean (to clearly show the asymmetry) but you should go read the original, which contains a lot of useful information. [Whuber's answer here gives another asymmetric continuous family of distributions with all the same moments. Doing the same "choose two, flip one and take a 50-50 mixture" trick has the same outcome of asymmetric with all odd moments zero, but I think it doesn't give unimodal results here (though perhaps there are some examples).] The answer here discusses the relationship between mean, median and mode. This answer discusses hypothesis tests of symmetry.
Does mean = median imply that a unimodal distribution is symmetric? This began as a comment but grew too long; I decided to make it into more of an answer. Alexis' fine answer deals with the immediate question (in short: i. that logically ${A\implies B}$ doesn't mean
11,818
Does mean = median imply that a unimodal distribution is symmetric?
No. If, in addition, the distribution is unimodal, then the mean = median = mode. In the same way that "If the baby animal is a chicken, then its origin is an egg" does not imply that "If the origin is an egg, then the baby animal is a chicken." From the same Wikipedia article: In cases where one tail is long but the other tail is fat, skewness does not obey a simple rule. For example, a zero value indicates that the tails on both sides of the mean balance out, which is the case both for a symmetric distribution, and for asymmetric distributions where the asymmetries even out, such as one tail being long but thin, and the other being short but fat.
Does mean = median imply that a unimodal distribution is symmetric?
No. If, in addition, the distribution is unimodal, then the mean = median = mode. In the same way that "If the baby animal is a chicken, then its origin is an egg" does not imply that "If the origin
Does mean = median imply that a unimodal distribution is symmetric? No. If, in addition, the distribution is unimodal, then the mean = median = mode. In the same way that "If the baby animal is a chicken, then its origin is an egg" does not imply that "If the origin is an egg, then the baby animal is a chicken." From the same Wikipedia article: In cases where one tail is long but the other tail is fat, skewness does not obey a simple rule. For example, a zero value indicates that the tails on both sides of the mean balance out, which is the case both for a symmetric distribution, and for asymmetric distributions where the asymmetries even out, such as one tail being long but thin, and the other being short but fat.
Does mean = median imply that a unimodal distribution is symmetric? No. If, in addition, the distribution is unimodal, then the mean = median = mode. In the same way that "If the baby animal is a chicken, then its origin is an egg" does not imply that "If the origin
11,819
Does mean = median imply that a unimodal distribution is symmetric?
Interesting and easy to understand examples come from the binomial distribution. Here are binomial probabilities for 0(1)5 successes in 5 trials when the probability of success is 0.2. It's immediate that the mean is 0.2 $\times$ 5 $=$ 1, which inspection of probabilities confirms as also the median and the (single) mode, but the distribution is clearly not symmetric. There are naturally many other examples of skewed binomials with mean a positive integer. 1 2 +-------------------+ 1 | 0 .32768 | 2 | 1 .4096 | 3 | 2 .2048 | 4 | 3 .0512 | 5 | 4 .0064 | 6 | 5 .00032 | +-------------------+ Stata code for this display was mata : (0..5)' , binomialp(5, (0..5), 0.2)' and presumably it is as simple or simpler in any statistical software worth mentioning. As a matter of psychology rather than logic, this example can't be convincingly dismissed as pathological (as in other problems one might discount distributions for which certain moments do not even exist) or as a bizarre or trivial example contrived for the purpose (as for example the invented data described by @Silverfish or 0, 0, 1, 1, 1, 3).
Does mean = median imply that a unimodal distribution is symmetric?
Interesting and easy to understand examples come from the binomial distribution. Here are binomial probabilities for 0(1)5 successes in 5 trials when the probability of success is 0.2. It's immediate
Does mean = median imply that a unimodal distribution is symmetric? Interesting and easy to understand examples come from the binomial distribution. Here are binomial probabilities for 0(1)5 successes in 5 trials when the probability of success is 0.2. It's immediate that the mean is 0.2 $\times$ 5 $=$ 1, which inspection of probabilities confirms as also the median and the (single) mode, but the distribution is clearly not symmetric. There are naturally many other examples of skewed binomials with mean a positive integer. 1 2 +-------------------+ 1 | 0 .32768 | 2 | 1 .4096 | 3 | 2 .2048 | 4 | 3 .0512 | 5 | 4 .0064 | 6 | 5 .00032 | +-------------------+ Stata code for this display was mata : (0..5)' , binomialp(5, (0..5), 0.2)' and presumably it is as simple or simpler in any statistical software worth mentioning. As a matter of psychology rather than logic, this example can't be convincingly dismissed as pathological (as in other problems one might discount distributions for which certain moments do not even exist) or as a bizarre or trivial example contrived for the purpose (as for example the invented data described by @Silverfish or 0, 0, 1, 1, 1, 3).
Does mean = median imply that a unimodal distribution is symmetric? Interesting and easy to understand examples come from the binomial distribution. Here are binomial probabilities for 0(1)5 successes in 5 trials when the probability of success is 0.2. It's immediate
11,820
Does mean = median imply that a unimodal distribution is symmetric?
This answer follows the same idea as Glen B, but with some slightly different story and visual examples The median and the mean are both measures that can be seen as splitting a distribution into two parts that have equal weights on both sides. For the mean and the median, these weights on both sides are different measures. They consider different absolute partial moments. They are both integrals of the absolute difference $|x-m|$ but with different powers. Symmetric distributions For symmetric distributions, these two sides are automatically the same when the split is made in the plane of symmetry. It works the same for mean as for the median which are integrals of a left side and a right side that become equal if the two sides have the same shape. So the point of the plane of symmetry is equal to the mean and it is equal to the median. And the median and mean will be equal (but they do not need this symmetry to be equal) Asymmetric distributions For asymmetric distribution, we do not need to have automatically that the dividing plane for the median (giving equal weights of probability on both sides) is also the dividing plane for the mean (giving equal weights of average distance on both sides), and vice-versa. It is also very typical for asymmetric distributions to have unequal mean and variance. The only counter-example among common asymmetric distributions that comes to my mind is the binomial distribution where $np$ is an integer and $p \neq 0.5$ (a worked-out example is in Nick Cox's answer with $n=5$ and $p=0.2$) such that median and mean are the same while the distribution is asymmetric. For continuous distributions, I do not know a common distribution that is both asymmetric and has equal mean and median. However, it is not difficult to construct a counter-example. The only thing that is needed is to transform a distribution and scale the distances on the left and right sides appropriately such that they have both equal mass and also the equal average distance. Below is a counterexample where we have a hypothetical distribution that is composed of an equal fifty-fifty mixture of two distributions, on the right side a $\chi^2$-distribution and on the left side a Weibull distribution. By selecting parameters of these distributions such that the means are equal, we get that this left and right side have the same weights. The distribution is obviously asymmetric but both sides have the same absolute 0-th and 1-th partial moment, namely both sides have 50% of the probability mass and the average absolute distance from the center is 5. In this sense, the question looks a bit similar like, "Is it possible to have distributions with different shapes but with the same mean?". Unimodal Edit: I missed the 'unimodal' specification. To get this we can do the same trick and use a mixture distribution. But this time we need to have both sides with the same mode as well. To find this example I took three distributions with each a mean equal to 1 (exponential distribution, half-logistic distribution scaled by $log(4)$, half-normal distribution scaled by $\sqrt{2/\pi}$) and add two of them together in order to get the same peak height.
Does mean = median imply that a unimodal distribution is symmetric?
This answer follows the same idea as Glen B, but with some slightly different story and visual examples The median and the mean are both measures that can be seen as splitting a distribution into two
Does mean = median imply that a unimodal distribution is symmetric? This answer follows the same idea as Glen B, but with some slightly different story and visual examples The median and the mean are both measures that can be seen as splitting a distribution into two parts that have equal weights on both sides. For the mean and the median, these weights on both sides are different measures. They consider different absolute partial moments. They are both integrals of the absolute difference $|x-m|$ but with different powers. Symmetric distributions For symmetric distributions, these two sides are automatically the same when the split is made in the plane of symmetry. It works the same for mean as for the median which are integrals of a left side and a right side that become equal if the two sides have the same shape. So the point of the plane of symmetry is equal to the mean and it is equal to the median. And the median and mean will be equal (but they do not need this symmetry to be equal) Asymmetric distributions For asymmetric distribution, we do not need to have automatically that the dividing plane for the median (giving equal weights of probability on both sides) is also the dividing plane for the mean (giving equal weights of average distance on both sides), and vice-versa. It is also very typical for asymmetric distributions to have unequal mean and variance. The only counter-example among common asymmetric distributions that comes to my mind is the binomial distribution where $np$ is an integer and $p \neq 0.5$ (a worked-out example is in Nick Cox's answer with $n=5$ and $p=0.2$) such that median and mean are the same while the distribution is asymmetric. For continuous distributions, I do not know a common distribution that is both asymmetric and has equal mean and median. However, it is not difficult to construct a counter-example. The only thing that is needed is to transform a distribution and scale the distances on the left and right sides appropriately such that they have both equal mass and also the equal average distance. Below is a counterexample where we have a hypothetical distribution that is composed of an equal fifty-fifty mixture of two distributions, on the right side a $\chi^2$-distribution and on the left side a Weibull distribution. By selecting parameters of these distributions such that the means are equal, we get that this left and right side have the same weights. The distribution is obviously asymmetric but both sides have the same absolute 0-th and 1-th partial moment, namely both sides have 50% of the probability mass and the average absolute distance from the center is 5. In this sense, the question looks a bit similar like, "Is it possible to have distributions with different shapes but with the same mean?". Unimodal Edit: I missed the 'unimodal' specification. To get this we can do the same trick and use a mixture distribution. But this time we need to have both sides with the same mode as well. To find this example I took three distributions with each a mean equal to 1 (exponential distribution, half-logistic distribution scaled by $log(4)$, half-normal distribution scaled by $\sqrt{2/\pi}$) and add two of them together in order to get the same peak height.
Does mean = median imply that a unimodal distribution is symmetric? This answer follows the same idea as Glen B, but with some slightly different story and visual examples The median and the mean are both measures that can be seen as splitting a distribution into two
11,821
How should we do boxplots with small samples?
What R implementations (should) do is for developers and users of that software. I wish to comment more broadly on limitations of box plots. This overlaps a little with points made in other answers, and I am happy to note agreements. But at the risk of some repetition I wanted this answer to seem coherent, at least to me. Box plots as known at present owe most to a re-invention by J.W. Tukey in the 1970s (most visibly in Exploratory Data Analysis, 1977) of dispersion diagrams used by geographers routinely from the 1930s, which in turn were channelling an idea stretching back through A.L. Bowley to Francis Galton that (in modern terms) plots, or more generally reports on data, that were based on particular quantiles could give useful summaries and helpful detail as well. This history is poorly understood, partly because few non-geographers are well read in geographical literature, although Tukey himself was aware of it. The meme that Tukey invented box plots is at best supplemented by an unhistorical mention of Marion E. Spear on range-bar plots. Spear herself was using but not citing earlier work by Kenneth W. Haemer, which itself ignored geographical predecessors, and Bowley, and Galton. But no one can be expected to know about all previous uses of statistical graphics anywhere. The precursors of box plots in many cases showed much more detail than bare box plots do, often all data points. In contrast, the focus of Tukey's work on box plots was whatever could be done quickly with pen and paper alone, with some expectation that a user was able and willing to do some simple calculations, such as averaging two numbers or multiplying by 1.5. As someone aged 25 in 1977, I still benefit from years of schooling in "mental arithmetic" (no workings on paper allowed, let alone slide rules or calculators or any other aid) as well as "mechanical arithmetic" (working on paper allowed). This is almost never anyone's routine situation with data analysis 50 years later. Further, the aim of a box plot was mostly exploratory, for example to identify data points that need thinking about, and possibly some action such as a transformation. Tukey himself would never have defended the box plot as fit for all kinds of data. Problem areas include, and are not limited to, Very small samples, as in the question. Discrete outcomes (e.g. counted or categorical data). For example, there are many threads here arising from puzzlement when either whisker is not shown or some other element of a box plot is apparently missing. The data don't have to be pathological or bizarre to produce a weird-looking box plot that is hard for many newcomers to decode. For example, suppose 60% of values are 0, 30% of values are 1, 10% of values are 2. Then the minimum, lower quartile and median coincide, the IQR is 1 and the 2s just show implicitly at the end of one whisker. Now suppose 80% of values are 0..... U-shaped distributions. Tukey gave an example of Rayleigh's data (which led to the discovery of argon) which fall in two clumps, so that the box is long and the whiskers short. Beyond that, long boxes and short whiskers are often misinterpreted as distributions with short thin tails too, people forgetting that if 50% of the distribution is inside the box, then 50% is outside, and the average density outside the box can be (much) higher. In all these cases, there are simple ripostes, to use something else instead or to think a little harder (or to provide a better story). As far as the question is concerned: Programmers (me too in other contexts) need to think about what is the default behaviour of their programs. I wouldn't recommend a threshold sample size below which the box plot is ignored and something else is done. I might recommend an option to do that. As above, most of the difficulties are avoided by plotting box plots routinely with some other representation juxtaposed or superimposed, either a dot or strip plot or a quantile plot (or occasionally a histogram). There are many variants of this idea already. The most popular seem based on jittering otherwise identical data points apart. I favour stacking in some sense, as jittering isn't so easy to decode in terms of a local density. Here is an example in the same spirit as the question. So long as data points are shown directly, it becomes trivial to decode puzzling box plots, or to ignore them as unhelpful. With larger samples, not the question but clearly important too, you can use most of the space for direct representation of the data and let the box plots be thin summaries. Detail: If you show all the data, the need to follow rules like "Plot data points individually whenever any is more than 1.5 IQR from the nearer quartile" diminishes, if it doesn't disappear. Such rules are in any case routinely not well explained, not well understood, or both. So, the whiskers can just extend to the extremes, or (as is quite often done) you can just have the whiskers extend to say the 5% and 95% points, so long as you explain your convention. The stark contrast between thick box and thin whiskers that is conventional overstates the importance of quartiles as thresholds or even as summaries. Naturally, this is familiar to anyone preferring a density plot or even a histogram. With this style there is no need to vary box width, as different group sizes are shown by the number of data points. It is often helpful in any case to add text of the form $ n = 15$ at some convenient place. As a further signal of possibilities, consider this design for a larger dataset in which tied data values make essential either stacking (as here) or jittering (if you prefer) if you want to see the detail of all data points. The box plot here is a box plot without a box and based on a 1983 suggestion by Edward R. Tufte. He called the design a quartile plot. Others have used the term midgap plot. The name is unimportant except for Googling mentions. Tufte's original goal seems most of all a minimal display using as little ink as possible. I too like its minimalism, but suggest a more statistical motive: it helpfully shifts emphasis from middles to tails. Often, if not most often, what is going on in the tails is as or more important to track as is what is going on in the middles of distributions. I use a marker or point symbol for the median that is more prominent than the point symbols used by Tufte. Minimalism like almost any other virtue can be carried to excess. Ironically, or otherwise, in his 2020 book Tufte comes out against this earlier design and enjoins showing the data in detail. But as I do that too with this hybrid design I feel no guilt on that score.
How should we do boxplots with small samples?
What R implementations (should) do is for developers and users of that software. I wish to comment more broadly on limitations of box plots. This overlaps a little with points made in other answers, a
How should we do boxplots with small samples? What R implementations (should) do is for developers and users of that software. I wish to comment more broadly on limitations of box plots. This overlaps a little with points made in other answers, and I am happy to note agreements. But at the risk of some repetition I wanted this answer to seem coherent, at least to me. Box plots as known at present owe most to a re-invention by J.W. Tukey in the 1970s (most visibly in Exploratory Data Analysis, 1977) of dispersion diagrams used by geographers routinely from the 1930s, which in turn were channelling an idea stretching back through A.L. Bowley to Francis Galton that (in modern terms) plots, or more generally reports on data, that were based on particular quantiles could give useful summaries and helpful detail as well. This history is poorly understood, partly because few non-geographers are well read in geographical literature, although Tukey himself was aware of it. The meme that Tukey invented box plots is at best supplemented by an unhistorical mention of Marion E. Spear on range-bar plots. Spear herself was using but not citing earlier work by Kenneth W. Haemer, which itself ignored geographical predecessors, and Bowley, and Galton. But no one can be expected to know about all previous uses of statistical graphics anywhere. The precursors of box plots in many cases showed much more detail than bare box plots do, often all data points. In contrast, the focus of Tukey's work on box plots was whatever could be done quickly with pen and paper alone, with some expectation that a user was able and willing to do some simple calculations, such as averaging two numbers or multiplying by 1.5. As someone aged 25 in 1977, I still benefit from years of schooling in "mental arithmetic" (no workings on paper allowed, let alone slide rules or calculators or any other aid) as well as "mechanical arithmetic" (working on paper allowed). This is almost never anyone's routine situation with data analysis 50 years later. Further, the aim of a box plot was mostly exploratory, for example to identify data points that need thinking about, and possibly some action such as a transformation. Tukey himself would never have defended the box plot as fit for all kinds of data. Problem areas include, and are not limited to, Very small samples, as in the question. Discrete outcomes (e.g. counted or categorical data). For example, there are many threads here arising from puzzlement when either whisker is not shown or some other element of a box plot is apparently missing. The data don't have to be pathological or bizarre to produce a weird-looking box plot that is hard for many newcomers to decode. For example, suppose 60% of values are 0, 30% of values are 1, 10% of values are 2. Then the minimum, lower quartile and median coincide, the IQR is 1 and the 2s just show implicitly at the end of one whisker. Now suppose 80% of values are 0..... U-shaped distributions. Tukey gave an example of Rayleigh's data (which led to the discovery of argon) which fall in two clumps, so that the box is long and the whiskers short. Beyond that, long boxes and short whiskers are often misinterpreted as distributions with short thin tails too, people forgetting that if 50% of the distribution is inside the box, then 50% is outside, and the average density outside the box can be (much) higher. In all these cases, there are simple ripostes, to use something else instead or to think a little harder (or to provide a better story). As far as the question is concerned: Programmers (me too in other contexts) need to think about what is the default behaviour of their programs. I wouldn't recommend a threshold sample size below which the box plot is ignored and something else is done. I might recommend an option to do that. As above, most of the difficulties are avoided by plotting box plots routinely with some other representation juxtaposed or superimposed, either a dot or strip plot or a quantile plot (or occasionally a histogram). There are many variants of this idea already. The most popular seem based on jittering otherwise identical data points apart. I favour stacking in some sense, as jittering isn't so easy to decode in terms of a local density. Here is an example in the same spirit as the question. So long as data points are shown directly, it becomes trivial to decode puzzling box plots, or to ignore them as unhelpful. With larger samples, not the question but clearly important too, you can use most of the space for direct representation of the data and let the box plots be thin summaries. Detail: If you show all the data, the need to follow rules like "Plot data points individually whenever any is more than 1.5 IQR from the nearer quartile" diminishes, if it doesn't disappear. Such rules are in any case routinely not well explained, not well understood, or both. So, the whiskers can just extend to the extremes, or (as is quite often done) you can just have the whiskers extend to say the 5% and 95% points, so long as you explain your convention. The stark contrast between thick box and thin whiskers that is conventional overstates the importance of quartiles as thresholds or even as summaries. Naturally, this is familiar to anyone preferring a density plot or even a histogram. With this style there is no need to vary box width, as different group sizes are shown by the number of data points. It is often helpful in any case to add text of the form $ n = 15$ at some convenient place. As a further signal of possibilities, consider this design for a larger dataset in which tied data values make essential either stacking (as here) or jittering (if you prefer) if you want to see the detail of all data points. The box plot here is a box plot without a box and based on a 1983 suggestion by Edward R. Tufte. He called the design a quartile plot. Others have used the term midgap plot. The name is unimportant except for Googling mentions. Tufte's original goal seems most of all a minimal display using as little ink as possible. I too like its minimalism, but suggest a more statistical motive: it helpfully shifts emphasis from middles to tails. Often, if not most often, what is going on in the tails is as or more important to track as is what is going on in the middles of distributions. I use a marker or point symbol for the median that is more prominent than the point symbols used by Tufte. Minimalism like almost any other virtue can be carried to excess. Ironically, or otherwise, in his 2020 book Tufte comes out against this earlier design and enjoins showing the data in detail. But as I do that too with this hybrid design I feel no guilt on that score.
How should we do boxplots with small samples? What R implementations (should) do is for developers and users of that software. I wish to comment more broadly on limitations of box plots. This overlaps a little with points made in other answers, a
11,822
How should we do boxplots with small samples?
I believe that this is a case where software misleads users. So my answer to (1) is "no." When we try to "summarize" a sample of 2 values, or even 5, with a display containing 5 elements, that can only be classed as a distortion, not a summary. The goal of statistical methods is to clarify, not obfuscate; so I think the software examples we see here are actually harmful to statistical practice. For question (2), a very simple alternative is to simply plot the points instead of the boxplot when the sample size is small. Such a one-dimensional scatterplot (or dotplot) fits on the same scale as the boxplot, so such a solution does not create any complications in the graphical layout. Nor does it complicate a user's interpretation because it is self-explanatory. I think a decent boxplot routine should implement a threshold below which a 1-dimensional scatterplot is produced instead of a box. I suggest the default threshold be at $n = 8$ or $n = 10$. Moreover some care should be taken (say, by offsetting points in the perpendicular direction of the scale) to ensure that every one of points is visible when there are overlapping values. This should be simple, given that only a small number of values is involved. Appendix Here is a hack for the standard graphics function: guts = boxplot(y ~ group, data = foo, plot = FALSE) guts$stats[,1] = guts$stats[3,1] guts$stats[,2] = guts$stats[3,2] guts$out = foo$y[1:7] guts$group = foo$group[1:7] bxp(guts, main = "Alternative boxplots", ylab = "y", xlab = "group") This made all 5 numbers of the 5-number summary equal to the median for the first two groups, and designated as outliers all the data values for those groups. Put another way, the box heights and whisker lengths for the small-data groups are set to zero, and all the values are regarded as outliers. I think this is a much more acceptable way to present those first two groups.
How should we do boxplots with small samples?
I believe that this is a case where software misleads users. So my answer to (1) is "no." When we try to "summarize" a sample of 2 values, or even 5, with a display containing 5 elements, that can onl
How should we do boxplots with small samples? I believe that this is a case where software misleads users. So my answer to (1) is "no." When we try to "summarize" a sample of 2 values, or even 5, with a display containing 5 elements, that can only be classed as a distortion, not a summary. The goal of statistical methods is to clarify, not obfuscate; so I think the software examples we see here are actually harmful to statistical practice. For question (2), a very simple alternative is to simply plot the points instead of the boxplot when the sample size is small. Such a one-dimensional scatterplot (or dotplot) fits on the same scale as the boxplot, so such a solution does not create any complications in the graphical layout. Nor does it complicate a user's interpretation because it is self-explanatory. I think a decent boxplot routine should implement a threshold below which a 1-dimensional scatterplot is produced instead of a box. I suggest the default threshold be at $n = 8$ or $n = 10$. Moreover some care should be taken (say, by offsetting points in the perpendicular direction of the scale) to ensure that every one of points is visible when there are overlapping values. This should be simple, given that only a small number of values is involved. Appendix Here is a hack for the standard graphics function: guts = boxplot(y ~ group, data = foo, plot = FALSE) guts$stats[,1] = guts$stats[3,1] guts$stats[,2] = guts$stats[3,2] guts$out = foo$y[1:7] guts$group = foo$group[1:7] bxp(guts, main = "Alternative boxplots", ylab = "y", xlab = "group") This made all 5 numbers of the 5-number summary equal to the median for the first two groups, and designated as outliers all the data values for those groups. Put another way, the box heights and whisker lengths for the small-data groups are set to zero, and all the values are regarded as outliers. I think this is a much more acceptable way to present those first two groups.
How should we do boxplots with small samples? I believe that this is a case where software misleads users. So my answer to (1) is "no." When we try to "summarize" a sample of 2 values, or even 5, with a display containing 5 elements, that can onl
11,823
How should we do boxplots with small samples?
This question touches on the intersection of statistics and software engineering. The statistical part of the question is uncontroversial: the boxplots, like many other statistics and data visualization methods, don't have much sense below some sample size. The software engineering part is more tricky and less obvious. There are many possible solutions, each with its pros and cons: You could do nothing as it happens right now in the examples. One of the important software design principles is the principle of least surprise, to avoid the wat! moments, summarised here as Simply put, this principle holds that a given operation’s result should be, “obvious, consistent, and predictable, based upon the name of the operation and other clues.” The "boxplot" function ought to create a boxplot, so it should create a boxplot, not more, not less. Producing the plot in such a case leads to garbage-in, garbage-out result. We are letting the user shoot themselves in a foot if that is what they want to do. I agree with you that the above is not the most pretty solution. On another hand, it acknowledges the fact that users may be using your software in hard to foresee ways (e.g. to create teaching examples “how not to make boxplots”). If we want to be slightly more empathetic with the user, we can warn them that what they are trying to do is not the best thing to do. If we decide that we cannot produce a plot for the small sample size, we can fail with an error. This is consistent with the idea of failing fast. Imagine you are auto-generating a report. Due to a bug in your code, you accidentally pass a smaller sample than intended to the boxplot function. If the function has some special handling of such cases (e.g. producing a different plot) the problem may end up undetected, or you might be wasting a lot of time on debugging the reason why the plot is not what you expected. (The same thing happens when you choose the "do nothing" approach.) Another solution is for the function to run in degraded mode in case of insufficient data. We can't produce a boxplot, but we can show something like a degraded boxplot, for example with three points showing only the minimum, maximum, and the mode (the elements of boxplot), or show all of the points as outliers. With more points, but still not enough for a boxplot, you could add some other elements if sufficient. Again, you can (if not should), combine this with a warning. Finally, you could produce a different plot for such data. I'd say, this falls into the realm of failing silently, which is an anti-pattern in general.
How should we do boxplots with small samples?
This question touches on the intersection of statistics and software engineering. The statistical part of the question is uncontroversial: the boxplots, like many other statistics and data visualizati
How should we do boxplots with small samples? This question touches on the intersection of statistics and software engineering. The statistical part of the question is uncontroversial: the boxplots, like many other statistics and data visualization methods, don't have much sense below some sample size. The software engineering part is more tricky and less obvious. There are many possible solutions, each with its pros and cons: You could do nothing as it happens right now in the examples. One of the important software design principles is the principle of least surprise, to avoid the wat! moments, summarised here as Simply put, this principle holds that a given operation’s result should be, “obvious, consistent, and predictable, based upon the name of the operation and other clues.” The "boxplot" function ought to create a boxplot, so it should create a boxplot, not more, not less. Producing the plot in such a case leads to garbage-in, garbage-out result. We are letting the user shoot themselves in a foot if that is what they want to do. I agree with you that the above is not the most pretty solution. On another hand, it acknowledges the fact that users may be using your software in hard to foresee ways (e.g. to create teaching examples “how not to make boxplots”). If we want to be slightly more empathetic with the user, we can warn them that what they are trying to do is not the best thing to do. If we decide that we cannot produce a plot for the small sample size, we can fail with an error. This is consistent with the idea of failing fast. Imagine you are auto-generating a report. Due to a bug in your code, you accidentally pass a smaller sample than intended to the boxplot function. If the function has some special handling of such cases (e.g. producing a different plot) the problem may end up undetected, or you might be wasting a lot of time on debugging the reason why the plot is not what you expected. (The same thing happens when you choose the "do nothing" approach.) Another solution is for the function to run in degraded mode in case of insufficient data. We can't produce a boxplot, but we can show something like a degraded boxplot, for example with three points showing only the minimum, maximum, and the mode (the elements of boxplot), or show all of the points as outliers. With more points, but still not enough for a boxplot, you could add some other elements if sufficient. Again, you can (if not should), combine this with a warning. Finally, you could produce a different plot for such data. I'd say, this falls into the realm of failing silently, which is an anti-pattern in general.
How should we do boxplots with small samples? This question touches on the intersection of statistics and software engineering. The statistical part of the question is uncontroversial: the boxplots, like many other statistics and data visualizati
11,824
How should we do boxplots with small samples?
I consider the question "What's the smallest sample size for which a box-and-whiskers plot is a useful visual summary" to be about a rule-of-thumb for making good plots. (The question "Should implementations of a box-and-whiskers plot enforce a minimum sample size" does seem to be about opinions rather than practice.) I looked for advice in a few books about statistical graphics. It seems straight advice is hard to find. So far I have: [1] J. Tukey. Exploratory Data Analysis (1977) First a general comment on page 29: If we are to select a few easily-found numbers to tell something about a batch as a whole, (...) we would like these values to be easy to find and write down, whether the total count of the batch is 8, or 82, or 208. And more specifically about boxplots, which Tukey calls schematic plots, in reference to visualizing 15 weight measurements from a 1893-94 experiment by Lord Rayleigh: Here the main issue (...) is made quite clear by the individual values of the dot plot--and almost completely covered by the schematic plot. (Only almost, because the experienced viewer--finding the whiskers so short, in comparison with the box length--is likely to become suspicious that he should see more detail.) Clearly we cannot rely on schematic plots to call our attention to structure near the center of the batch (...) Exhibit 11 uses the schematic plots for one of the purposes for which they are best fitted: comparison of two or more batches. In it, the two batches of Rayleigh's weights (one batch of 7 from air and another batch of 8 from other sources) are set out and compared. [2] F. J. Anscombe. Graphs in statistical analysis. The American Statistician, 27(1):17–21, 1973. Each datasets in the famous quartet has 11 points, so Anscombe's implicit advice is to not summarize fewer than 12 points? Summary: John Tukey suggests indirectly to have at least 8 points for a box-and-whishers plot. He also has a hint about catching out a misapplied boxplot.
How should we do boxplots with small samples?
I consider the question "What's the smallest sample size for which a box-and-whiskers plot is a useful visual summary" to be about a rule-of-thumb for making good plots. (The question "Should implemen
How should we do boxplots with small samples? I consider the question "What's the smallest sample size for which a box-and-whiskers plot is a useful visual summary" to be about a rule-of-thumb for making good plots. (The question "Should implementations of a box-and-whiskers plot enforce a minimum sample size" does seem to be about opinions rather than practice.) I looked for advice in a few books about statistical graphics. It seems straight advice is hard to find. So far I have: [1] J. Tukey. Exploratory Data Analysis (1977) First a general comment on page 29: If we are to select a few easily-found numbers to tell something about a batch as a whole, (...) we would like these values to be easy to find and write down, whether the total count of the batch is 8, or 82, or 208. And more specifically about boxplots, which Tukey calls schematic plots, in reference to visualizing 15 weight measurements from a 1893-94 experiment by Lord Rayleigh: Here the main issue (...) is made quite clear by the individual values of the dot plot--and almost completely covered by the schematic plot. (Only almost, because the experienced viewer--finding the whiskers so short, in comparison with the box length--is likely to become suspicious that he should see more detail.) Clearly we cannot rely on schematic plots to call our attention to structure near the center of the batch (...) Exhibit 11 uses the schematic plots for one of the purposes for which they are best fitted: comparison of two or more batches. In it, the two batches of Rayleigh's weights (one batch of 7 from air and another batch of 8 from other sources) are set out and compared. [2] F. J. Anscombe. Graphs in statistical analysis. The American Statistician, 27(1):17–21, 1973. Each datasets in the famous quartet has 11 points, so Anscombe's implicit advice is to not summarize fewer than 12 points? Summary: John Tukey suggests indirectly to have at least 8 points for a box-and-whishers plot. He also has a hint about catching out a misapplied boxplot.
How should we do boxplots with small samples? I consider the question "What's the smallest sample size for which a box-and-whiskers plot is a useful visual summary" to be about a rule-of-thumb for making good plots. (The question "Should implemen
11,825
How should we do boxplots with small samples?
Just curious -- Looking outside of R with the same data... Stata SPSS SAS Enterprise Guide MATLAB (Statistics and Machine Learning tools) Minitab I was most curious about Minitab, but our virtual desktop access seemed to require a license. I'd be curious if somebody could fill this one in... Summary I see lots of different styles, some I like a whole lot better than others, but all programs tested were happy to make boxplots with 2 data values.
How should we do boxplots with small samples?
Just curious -- Looking outside of R with the same data... Stata SPSS SAS Enterprise Guide MATLAB (Statistics and Machine Learning tools) Minitab I was most curious about Minitab, but our virtual
How should we do boxplots with small samples? Just curious -- Looking outside of R with the same data... Stata SPSS SAS Enterprise Guide MATLAB (Statistics and Machine Learning tools) Minitab I was most curious about Minitab, but our virtual desktop access seemed to require a license. I'd be curious if somebody could fill this one in... Summary I see lots of different styles, some I like a whole lot better than others, but all programs tested were happy to make boxplots with 2 data values.
How should we do boxplots with small samples? Just curious -- Looking outside of R with the same data... Stata SPSS SAS Enterprise Guide MATLAB (Statistics and Machine Learning tools) Minitab I was most curious about Minitab, but our virtual
11,826
Confidence interval for GAM model
In the usual way: p <- predict(mod, newdata, type = "link", se.fit = TRUE) Then note that p contains a component $se.fit with standard errors of the predictions for observations in newdata. You can then form CI by multipliying the SE by a value appropriate to your desired level. E.g. an approximate 95% confidence interval is formed as: upr <- p$fit + (2 * p$se.fit) lwr <- p$fit - (2 * p$se.fit) You substitute in an appropriate value from a $t$ or Gaussian distribution for the interval you need. Note that I use type = "link" as you don't say if you have a GAM or just an AM. In the GAM, you need to form the confidence interval on the scale of the linear predictor and then transform that to the scale of the response by applying the inverse of the link function: upr <- mod$family$linkinv(upr) lwr <- mod$family$linkinv(lwr) Now note that these are very approximate intervals. In addition these intervals are point-wise on the predicted values and they don't take into account the fact that the smoothness selection was performed. A simultaneous confidence interval can be computed via simulation from the posterior distribution of the parameters. I have an example of that on my blog. If you want a confidence interval that is not conditional upon the smoothing parameters (i.e. one that takes into account that we do not know, but instead estimate, the values of the smoothness parameters), then add unconditional = TRUE to the predict() call. Also, if you don't want to do this yourself, note that newer versions of mgcv have a plot.gam() function that returns an object with all data used to create the plots of the smooths and their confidence intervals. You can just save the output from plot.gam() in an obj obj <- plot(model, ....) and then inspect obj, which is a list with one component per smooth. Add seWithMean = TRUE to the plot() call to get confidence intervals that are not conditional upon smoothness parameter.
Confidence interval for GAM model
In the usual way: p <- predict(mod, newdata, type = "link", se.fit = TRUE) Then note that p contains a component $se.fit with standard errors of the predictions for observations in newdata. You can t
Confidence interval for GAM model In the usual way: p <- predict(mod, newdata, type = "link", se.fit = TRUE) Then note that p contains a component $se.fit with standard errors of the predictions for observations in newdata. You can then form CI by multipliying the SE by a value appropriate to your desired level. E.g. an approximate 95% confidence interval is formed as: upr <- p$fit + (2 * p$se.fit) lwr <- p$fit - (2 * p$se.fit) You substitute in an appropriate value from a $t$ or Gaussian distribution for the interval you need. Note that I use type = "link" as you don't say if you have a GAM or just an AM. In the GAM, you need to form the confidence interval on the scale of the linear predictor and then transform that to the scale of the response by applying the inverse of the link function: upr <- mod$family$linkinv(upr) lwr <- mod$family$linkinv(lwr) Now note that these are very approximate intervals. In addition these intervals are point-wise on the predicted values and they don't take into account the fact that the smoothness selection was performed. A simultaneous confidence interval can be computed via simulation from the posterior distribution of the parameters. I have an example of that on my blog. If you want a confidence interval that is not conditional upon the smoothing parameters (i.e. one that takes into account that we do not know, but instead estimate, the values of the smoothness parameters), then add unconditional = TRUE to the predict() call. Also, if you don't want to do this yourself, note that newer versions of mgcv have a plot.gam() function that returns an object with all data used to create the plots of the smooths and their confidence intervals. You can just save the output from plot.gam() in an obj obj <- plot(model, ....) and then inspect obj, which is a list with one component per smooth. Add seWithMean = TRUE to the plot() call to get confidence intervals that are not conditional upon smoothness parameter.
Confidence interval for GAM model In the usual way: p <- predict(mod, newdata, type = "link", se.fit = TRUE) Then note that p contains a component $se.fit with standard errors of the predictions for observations in newdata. You can t
11,827
Confidence interval for GAM model
If you just want to plot them the plot.gam function has shading that defaults to confidence intervals using the shade argument. Also see gam.vcomp for getting the intervals.
Confidence interval for GAM model
If you just want to plot them the plot.gam function has shading that defaults to confidence intervals using the shade argument. Also see gam.vcomp for getting the intervals.
Confidence interval for GAM model If you just want to plot them the plot.gam function has shading that defaults to confidence intervals using the shade argument. Also see gam.vcomp for getting the intervals.
Confidence interval for GAM model If you just want to plot them the plot.gam function has shading that defaults to confidence intervals using the shade argument. Also see gam.vcomp for getting the intervals.
11,828
Confidence interval for GAM model
The package mgcv (newer than gam) readily plots credible intervals. This Bayesian approach is different from confidence intervals, but the results are almost the same, as numerical simulations have shown (see the paper by Marra and Wood linked in mgcv).
Confidence interval for GAM model
The package mgcv (newer than gam) readily plots credible intervals. This Bayesian approach is different from confidence intervals, but the results are almost the same, as numerical simulations have sh
Confidence interval for GAM model The package mgcv (newer than gam) readily plots credible intervals. This Bayesian approach is different from confidence intervals, but the results are almost the same, as numerical simulations have shown (see the paper by Marra and Wood linked in mgcv).
Confidence interval for GAM model The package mgcv (newer than gam) readily plots credible intervals. This Bayesian approach is different from confidence intervals, but the results are almost the same, as numerical simulations have sh
11,829
Is the Dice coefficient the same as accuracy?
These are not the same thing and they are often used in different contexts. The Dice score is often used to quantify the performance of image segmentation methods. There you annotate some ground truth region in your image and then make an automated algorithm to do it. You validate the algorithm by calculating the Dice score, which is a measure of how similar the objects are. So it is the size of the overlap of the two segmentations divided by the total size of the two objects. Using the same terms as describing accuracy, the Dice score is: $$ \frac{2\cdot \text{number of true positives}}{2 \cdot \text{number of true positives + number of false positives + number of false negatives}} $$ To explain the terms: Number of true positives: number of positive points that your method classifies as positive Number of false positives: number of negative points that your method classifies as positive Number of positives: total number of positives points The Dice score is not only a measure of how many positives you find, but it also penalizes for the false positives that the method finds, similar to precision. So it is more similar to precision than accuracy. The only difference is the denominator, where you have the total number of positives instead of only the positives that the method finds. So the Dice score is also penalizing for the positives that your algorithm/method could not find. Edit: In the case of image segmentation, let's say that you have a mask with ground truth, let's call the mask $A$ like you suggest. So the mask has values 1 in the pixels where there is something you are trying to find and else zero. Now you have an algorithm to generate image/mask $B$, which also has to be a binary image, i.e. you create a mask for you segmentation. Then we have the following: Number of positives is the total number of pixels that have intensity 1 in image $A$ Number of true positives is the total number of pixels which have the value 1 in both $A$ and $B$. So it the intersection of the regions of ones in $A$ and $B$. It is the same as using the AND operator on $A$ and $B$. Number of false positives is the number of pixels which appear as 1 in $B$ but zero in $A$. If you are doing this for a publication, then write Dice with a capital D, because it is named after a guy named Dice. EDIT: Regarding the comment about a correction: I do not use the traditional formula to calculate the Dice coefficient, but if I translate it to the notation in the other answer it becomes: $$ \text{Dice score} = \frac{2\cdot|A\cap B|}{2\cdot|A\cap B| + |B\backslash A| + |A\backslash B|} = \frac{2\cdot|A\cap B|}{|A| + |B|} $$ Which is equivalent to the traditional definition. It is more convenient to write it the way I wrote it originally to state the formula in terms of false positives. The backslash is the set minus.
Is the Dice coefficient the same as accuracy?
These are not the same thing and they are often used in different contexts. The Dice score is often used to quantify the performance of image segmentation methods. There you annotate some ground truth
Is the Dice coefficient the same as accuracy? These are not the same thing and they are often used in different contexts. The Dice score is often used to quantify the performance of image segmentation methods. There you annotate some ground truth region in your image and then make an automated algorithm to do it. You validate the algorithm by calculating the Dice score, which is a measure of how similar the objects are. So it is the size of the overlap of the two segmentations divided by the total size of the two objects. Using the same terms as describing accuracy, the Dice score is: $$ \frac{2\cdot \text{number of true positives}}{2 \cdot \text{number of true positives + number of false positives + number of false negatives}} $$ To explain the terms: Number of true positives: number of positive points that your method classifies as positive Number of false positives: number of negative points that your method classifies as positive Number of positives: total number of positives points The Dice score is not only a measure of how many positives you find, but it also penalizes for the false positives that the method finds, similar to precision. So it is more similar to precision than accuracy. The only difference is the denominator, where you have the total number of positives instead of only the positives that the method finds. So the Dice score is also penalizing for the positives that your algorithm/method could not find. Edit: In the case of image segmentation, let's say that you have a mask with ground truth, let's call the mask $A$ like you suggest. So the mask has values 1 in the pixels where there is something you are trying to find and else zero. Now you have an algorithm to generate image/mask $B$, which also has to be a binary image, i.e. you create a mask for you segmentation. Then we have the following: Number of positives is the total number of pixels that have intensity 1 in image $A$ Number of true positives is the total number of pixels which have the value 1 in both $A$ and $B$. So it the intersection of the regions of ones in $A$ and $B$. It is the same as using the AND operator on $A$ and $B$. Number of false positives is the number of pixels which appear as 1 in $B$ but zero in $A$. If you are doing this for a publication, then write Dice with a capital D, because it is named after a guy named Dice. EDIT: Regarding the comment about a correction: I do not use the traditional formula to calculate the Dice coefficient, but if I translate it to the notation in the other answer it becomes: $$ \text{Dice score} = \frac{2\cdot|A\cap B|}{2\cdot|A\cap B| + |B\backslash A| + |A\backslash B|} = \frac{2\cdot|A\cap B|}{|A| + |B|} $$ Which is equivalent to the traditional definition. It is more convenient to write it the way I wrote it originally to state the formula in terms of false positives. The backslash is the set minus.
Is the Dice coefficient the same as accuracy? These are not the same thing and they are often used in different contexts. The Dice score is often used to quantify the performance of image segmentation methods. There you annotate some ground truth
11,830
Is the Dice coefficient the same as accuracy?
The Dice coefficient (also known as Dice similarity index) is the same as the F1 score, but it's not the same as accuracy. The main difference might be the fact that accuracy takes into account true negatives while Dice coefficient and many other measures just handle true negatives as uninteresting defaults (see The Basics of Classifier Evaluation, Part 1). As far as I can tell, the Dice coefficient isn't computed as described by a previous answer, which actually contains the formula for the Jaccard index (also known as "intersection over union" in computer vision). $$ \begin{align*} \text{Dice}(A,B) &= \frac{2|A\cdot B|}{ |A| + |B| } \\ F1(A,B) &= \frac{2}{|A|/|A \cdot B| + |B|/|A\cdot B|} \\ \text{Jaccard}(A,B) &= \frac{|A\cdot B|}{|\max(A,B)|} = \frac{|A\cdot B|}{|A|+|B|-|A\cdot B|}\\ \text{Accuracy}(A,B) &= \frac{|A\cdot B|+|\overline{A} \cdot \overline{B}|}{|\text{All}|} \\ \end{align*} $$ Where $A,B$ binary vectors (with values of 1 for elements inside a group and 0 otherwise), one signify the ground truth and the other signify the classification result, and $All$ is just all elements considerred (a binary vector of 1's of the same length). For example, $ |A \cdot B|$ (inner product of $A$ and $B$) is the number of true positives, $ |\overline{A} \cdot \overline{B}|$ (inner product of the complement of $A$ and the complement of $B$) is the number of true negatives. The Dice coefficient and Jaccard index are monotonically related, and the Tversky index generalizes them both, to read more about it see F-scores, Dice, and Jaccard set similarity. The Dice coefficient is also the harmonic mean of Sensitivity and Precision, to see why it makes sense, read Why is the F-Measure a harmonic mean and not an arithmetic mean of the Precision and Recall measures?. To read more about many of the terms in this answer and their relationships, see Evaluation of binary classifiers.
Is the Dice coefficient the same as accuracy?
The Dice coefficient (also known as Dice similarity index) is the same as the F1 score, but it's not the same as accuracy. The main difference might be the fact that accuracy takes into account true n
Is the Dice coefficient the same as accuracy? The Dice coefficient (also known as Dice similarity index) is the same as the F1 score, but it's not the same as accuracy. The main difference might be the fact that accuracy takes into account true negatives while Dice coefficient and many other measures just handle true negatives as uninteresting defaults (see The Basics of Classifier Evaluation, Part 1). As far as I can tell, the Dice coefficient isn't computed as described by a previous answer, which actually contains the formula for the Jaccard index (also known as "intersection over union" in computer vision). $$ \begin{align*} \text{Dice}(A,B) &= \frac{2|A\cdot B|}{ |A| + |B| } \\ F1(A,B) &= \frac{2}{|A|/|A \cdot B| + |B|/|A\cdot B|} \\ \text{Jaccard}(A,B) &= \frac{|A\cdot B|}{|\max(A,B)|} = \frac{|A\cdot B|}{|A|+|B|-|A\cdot B|}\\ \text{Accuracy}(A,B) &= \frac{|A\cdot B|+|\overline{A} \cdot \overline{B}|}{|\text{All}|} \\ \end{align*} $$ Where $A,B$ binary vectors (with values of 1 for elements inside a group and 0 otherwise), one signify the ground truth and the other signify the classification result, and $All$ is just all elements considerred (a binary vector of 1's of the same length). For example, $ |A \cdot B|$ (inner product of $A$ and $B$) is the number of true positives, $ |\overline{A} \cdot \overline{B}|$ (inner product of the complement of $A$ and the complement of $B$) is the number of true negatives. The Dice coefficient and Jaccard index are monotonically related, and the Tversky index generalizes them both, to read more about it see F-scores, Dice, and Jaccard set similarity. The Dice coefficient is also the harmonic mean of Sensitivity and Precision, to see why it makes sense, read Why is the F-Measure a harmonic mean and not an arithmetic mean of the Precision and Recall measures?. To read more about many of the terms in this answer and their relationships, see Evaluation of binary classifiers.
Is the Dice coefficient the same as accuracy? The Dice coefficient (also known as Dice similarity index) is the same as the F1 score, but it's not the same as accuracy. The main difference might be the fact that accuracy takes into account true n
11,831
Is the Dice coefficient the same as accuracy?
The Dice coefficient (also known as the Sørensen–Dice coefficient and F1 score) is defined as two times the area of the intersection of A and B, divided by the sum of the areas of A and B: Dice = 2 |A∩B| / (|A|+|B|) = 2 TP / (2 TP + FP + FN) (TP=True Positives, FP=False Positives, FN=False Negatives) Dice score is a performance metric for image segmentation problems. This is different from accuracy where the objective is to match the values, unlike dice which matches the value + position.
Is the Dice coefficient the same as accuracy?
The Dice coefficient (also known as the Sørensen–Dice coefficient and F1 score) is defined as two times the area of the intersection of A and B, divided by the sum of the areas of A and B: Dice = 2 |A
Is the Dice coefficient the same as accuracy? The Dice coefficient (also known as the Sørensen–Dice coefficient and F1 score) is defined as two times the area of the intersection of A and B, divided by the sum of the areas of A and B: Dice = 2 |A∩B| / (|A|+|B|) = 2 TP / (2 TP + FP + FN) (TP=True Positives, FP=False Positives, FN=False Negatives) Dice score is a performance metric for image segmentation problems. This is different from accuracy where the objective is to match the values, unlike dice which matches the value + position.
Is the Dice coefficient the same as accuracy? The Dice coefficient (also known as the Sørensen–Dice coefficient and F1 score) is defined as two times the area of the intersection of A and B, divided by the sum of the areas of A and B: Dice = 2 |A
11,832
How to generate random categorical data?
Do you want the proportions in the sample to be exactly the proportions stated? or to represent the idea of sampling from a very large population with those proportions (so the sample proportions will be close but not exact)? If you want the exact proportions then you can follow Brandon's suggestion and use the R sample function to randomize the order of a vector that has the exact proportions. If you want to sample from the population, but not restrict the proportions to be exact then you can still use the sample function in R with the prob argument like so: > x <- sample( LETTERS[1:4], 10000, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) ) > prop.table(table(x)) x A B C D 0.0965 0.1972 0.6544 0.0519
How to generate random categorical data?
Do you want the proportions in the sample to be exactly the proportions stated? or to represent the idea of sampling from a very large population with those proportions (so the sample proportions will
How to generate random categorical data? Do you want the proportions in the sample to be exactly the proportions stated? or to represent the idea of sampling from a very large population with those proportions (so the sample proportions will be close but not exact)? If you want the exact proportions then you can follow Brandon's suggestion and use the R sample function to randomize the order of a vector that has the exact proportions. If you want to sample from the population, but not restrict the proportions to be exact then you can still use the sample function in R with the prob argument like so: > x <- sample( LETTERS[1:4], 10000, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) ) > prop.table(table(x)) x A B C D 0.0965 0.1972 0.6544 0.0519
How to generate random categorical data? Do you want the proportions in the sample to be exactly the proportions stated? or to represent the idea of sampling from a very large population with those proportions (so the sample proportions will
11,833
How to generate random categorical data?
Using R (http://cran.r-project.org/). All I'm doing here is creating a random list with the proportions you specified. x <- c(rep("A",0.1*10000),rep("B",0.2*10000),rep("C",0.65*10000),rep("D",0.05*10000)) # cheating x <- sample(x, 10000) prop.table(summary(as.factor(x))) /me Waits patiently for argument over how truly random this is
How to generate random categorical data?
Using R (http://cran.r-project.org/). All I'm doing here is creating a random list with the proportions you specified. x <- c(rep("A",0.1*10000),rep("B",0.2*10000),rep("C",0.65*10000),rep("D",0.05*10
How to generate random categorical data? Using R (http://cran.r-project.org/). All I'm doing here is creating a random list with the proportions you specified. x <- c(rep("A",0.1*10000),rep("B",0.2*10000),rep("C",0.65*10000),rep("D",0.05*10000)) # cheating x <- sample(x, 10000) prop.table(summary(as.factor(x))) /me Waits patiently for argument over how truly random this is
How to generate random categorical data? Using R (http://cran.r-project.org/). All I'm doing here is creating a random list with the proportions you specified. x <- c(rep("A",0.1*10000),rep("B",0.2*10000),rep("C",0.65*10000),rep("D",0.05*10
11,834
How to generate random categorical data?
n <- 10000 blah <- character(n) u <- runif(n) blah[u<=0.1] <- "A" blah[u>0.1 & u<=0.3] <- "B" blah[u>0.3 & u<=0.95] <- "C" blah[u>0.95] <- "D" table(blah) prop.table(summary(as.factor(blah))) I have no doubt this is truly random. I mean, to the extent that runif() is random :)
How to generate random categorical data?
n <- 10000 blah <- character(n) u <- runif(n) blah[u<=0.1] <- "A" blah[u>0.1 & u<=0.3] <- "B" blah[u>0.3 & u<=0.95] <- "C" blah[u>0.95] <- "D" table(blah) prop.table(su
How to generate random categorical data? n <- 10000 blah <- character(n) u <- runif(n) blah[u<=0.1] <- "A" blah[u>0.1 & u<=0.3] <- "B" blah[u>0.3 & u<=0.95] <- "C" blah[u>0.95] <- "D" table(blah) prop.table(summary(as.factor(blah))) I have no doubt this is truly random. I mean, to the extent that runif() is random :)
How to generate random categorical data? n <- 10000 blah <- character(n) u <- runif(n) blah[u<=0.1] <- "A" blah[u>0.1 & u<=0.3] <- "B" blah[u>0.3 & u<=0.95] <- "C" blah[u>0.95] <- "D" table(blah) prop.table(su
11,835
How to generate random categorical data?
If you're a SAS user, recent versions provide a similar ability to pull from what it calls a "table" distribution - which is what you are looking for, as part of the Rand() function. See http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a001466748.htm
How to generate random categorical data?
If you're a SAS user, recent versions provide a similar ability to pull from what it calls a "table" distribution - which is what you are looking for, as part of the Rand() function. See http://suppor
How to generate random categorical data? If you're a SAS user, recent versions provide a similar ability to pull from what it calls a "table" distribution - which is what you are looking for, as part of the Rand() function. See http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a001466748.htm
How to generate random categorical data? If you're a SAS user, recent versions provide a similar ability to pull from what it calls a "table" distribution - which is what you are looking for, as part of the Rand() function. See http://suppor
11,836
What does PAC learning theory mean?
Probably approximately correct (PAC) learning theory helps analyze whether and under what conditions a learner $L$ will probably output an approximately correct classifier. (You'll see some sources use $A$ in place of $L$.) First, let's define "approximate." A hypothesis $h \in H$ is approximately correct if its error over the distribution of inputs is bounded by some $\epsilon, 0 \le \epsilon \le \frac{1}{2}.$ I.e., $error_D(h)\lt \epsilon$, where $D$ is the distribution over inputs. Next, "probably." If $L$ will output such a classifier with probability $1 - \delta$, with $0 \le \delta \le \frac{1}{2}$, we call that classifier probably approximately correct. Knowing that a target concept is PAC-learnable allows you to bound the sample size necessary to probably learn an approximately correct classifier, which is what's shown in the formula you've reproduced: $$m \ge\frac{1}{\epsilon}(ln|H| + ln\frac{1}{\delta})$$ To gain some intuition about this, note the effects on $m$ when you alter variables in the right-hand side. As allowable error decreases, the necessary sample size grows. Likewise, it grows with the probability of an approximately correct learner, and with the size of the hypothesis space $H$. (Loosely, a hypothesis space is the set of classifiers your algorithm considers.) More plainly, as you consider more possible classifiers, or desire a lower error or higher probability of correctness, you need more data to distinguish between them. For more, this and other related videos may be helpful, as might this lengthy introduction or one of many machine learning texts, say Mitchell, for example.
What does PAC learning theory mean?
Probably approximately correct (PAC) learning theory helps analyze whether and under what conditions a learner $L$ will probably output an approximately correct classifier. (You'll see some sources us
What does PAC learning theory mean? Probably approximately correct (PAC) learning theory helps analyze whether and under what conditions a learner $L$ will probably output an approximately correct classifier. (You'll see some sources use $A$ in place of $L$.) First, let's define "approximate." A hypothesis $h \in H$ is approximately correct if its error over the distribution of inputs is bounded by some $\epsilon, 0 \le \epsilon \le \frac{1}{2}.$ I.e., $error_D(h)\lt \epsilon$, where $D$ is the distribution over inputs. Next, "probably." If $L$ will output such a classifier with probability $1 - \delta$, with $0 \le \delta \le \frac{1}{2}$, we call that classifier probably approximately correct. Knowing that a target concept is PAC-learnable allows you to bound the sample size necessary to probably learn an approximately correct classifier, which is what's shown in the formula you've reproduced: $$m \ge\frac{1}{\epsilon}(ln|H| + ln\frac{1}{\delta})$$ To gain some intuition about this, note the effects on $m$ when you alter variables in the right-hand side. As allowable error decreases, the necessary sample size grows. Likewise, it grows with the probability of an approximately correct learner, and with the size of the hypothesis space $H$. (Loosely, a hypothesis space is the set of classifiers your algorithm considers.) More plainly, as you consider more possible classifiers, or desire a lower error or higher probability of correctness, you need more data to distinguish between them. For more, this and other related videos may be helpful, as might this lengthy introduction or one of many machine learning texts, say Mitchell, for example.
What does PAC learning theory mean? Probably approximately correct (PAC) learning theory helps analyze whether and under what conditions a learner $L$ will probably output an approximately correct classifier. (You'll see some sources us
11,837
What does PAC learning theory mean?
The definition of probably approximately correct is due to Valiant. It is meant to give a mathematically rigorous definition of what is machine learning. Let me ramble a bit. While PAC uses the term 'hypothesis', mostly people use the word model instead of hypothesis. With a nod to the statistics community I prefer model, but I'll attempt to use both. Machine learning starts with some data, $(x_i, y_i)$ and one wants to find a hypothesis or model that will, given the inputs $x_i$ return $y_i$ or something very close. More importantly given new data $\tilde{x}$ the model will compute or predict the corresponding $\tilde{y}$ . Really one isn't interested in how accurate the hypothesis is on the given (training) data except that it is hard to believe that a model that was created using some data will not accurately reflect that data set, but will be accurate on any future data sets. The two important caveats are that one cannot predict new data with 100% accuracy and there is also the possibility that the data examples one has seen miss something important. A toy example would be that if I gave you the 'data' 1,2,3,4 one would 'predict' that 5 would be the next number. If you tested this by asking people what was the next number in the sequence, most people would say 5. Someone could say 1,000,000 though. If you were given the sequence 1,2,3,...999,999 one would be surer that the next number is 1,000,000. However the next number could be 999,999.5, or even 5. The point is that the more data one sees, the more sure one can be that one has produced an accurate model, but one can never be absolutely certain. The definition of probably approximately correct gives a mathematically precise version of this idea. Given data $x_i, 1 \leq i \leq m$ with output $y_i$ and a class of models $f_{\theta} $ which constitute the hypotheses one can ask 2 questions. Can we use the data to find a specific hypothesis $f_{\Theta}$ that is likely to be really accurate in predicting new values ? Further how likely is it that the model is as accurate as we expect it to be ? That is can we train a model that is highly likely to be very accurate. As in Sean Easter's answer, we say a class of hypotheses (class of models) is PAC if we can do an 'epsilon, delta' argument. That is we can say with probability $ p >1-\delta $ that our model $f_{\Theta}$ is accurate to within $\epsilon$ . How much data one must see to satisfy a specific pair $(\delta,\epsilon) $ depends on the actual $(\delta,\epsilon) $ and how complex the given class of hypothesis are. More precisely, a class of hypotheses $\mathcal{H}$ or models $f_{\theta}$ is PAC if for any pair $(\epsilon, \delta)$ with $ 0 < \epsilon,\delta , <.5 $ there is a specific model $f_{\Theta}$ such that any new data $\tilde{x}, \tilde{y} $, this model will satisfy $Err(f_{\Theta}(\tilde{x}) ,\tilde{y} ) < \epsilon$ with probability $ p > 1-\delta $ if the model was selected (trained) with at least $ m = m(\delta,\epsilon,\mathcal{H}) $ training examples. Here Err is the chosen loss function which is usually $(f_{\Theta}(\tilde{x}) -\tilde{y})^2$. The diagram you have gives a formula for how much data one needs to train on for a given class of hypotheses to satisfy a given pair $(\delta,\epsilon) $. I could be wrong, but I believe that this definition was given by Valiant in a paper called "A Theory of the Learnable" and was in part responsible for Valiant winning the Turing prize.
What does PAC learning theory mean?
The definition of probably approximately correct is due to Valiant. It is meant to give a mathematically rigorous definition of what is machine learning. Let me ramble a bit. While PAC uses the ter
What does PAC learning theory mean? The definition of probably approximately correct is due to Valiant. It is meant to give a mathematically rigorous definition of what is machine learning. Let me ramble a bit. While PAC uses the term 'hypothesis', mostly people use the word model instead of hypothesis. With a nod to the statistics community I prefer model, but I'll attempt to use both. Machine learning starts with some data, $(x_i, y_i)$ and one wants to find a hypothesis or model that will, given the inputs $x_i$ return $y_i$ or something very close. More importantly given new data $\tilde{x}$ the model will compute or predict the corresponding $\tilde{y}$ . Really one isn't interested in how accurate the hypothesis is on the given (training) data except that it is hard to believe that a model that was created using some data will not accurately reflect that data set, but will be accurate on any future data sets. The two important caveats are that one cannot predict new data with 100% accuracy and there is also the possibility that the data examples one has seen miss something important. A toy example would be that if I gave you the 'data' 1,2,3,4 one would 'predict' that 5 would be the next number. If you tested this by asking people what was the next number in the sequence, most people would say 5. Someone could say 1,000,000 though. If you were given the sequence 1,2,3,...999,999 one would be surer that the next number is 1,000,000. However the next number could be 999,999.5, or even 5. The point is that the more data one sees, the more sure one can be that one has produced an accurate model, but one can never be absolutely certain. The definition of probably approximately correct gives a mathematically precise version of this idea. Given data $x_i, 1 \leq i \leq m$ with output $y_i$ and a class of models $f_{\theta} $ which constitute the hypotheses one can ask 2 questions. Can we use the data to find a specific hypothesis $f_{\Theta}$ that is likely to be really accurate in predicting new values ? Further how likely is it that the model is as accurate as we expect it to be ? That is can we train a model that is highly likely to be very accurate. As in Sean Easter's answer, we say a class of hypotheses (class of models) is PAC if we can do an 'epsilon, delta' argument. That is we can say with probability $ p >1-\delta $ that our model $f_{\Theta}$ is accurate to within $\epsilon$ . How much data one must see to satisfy a specific pair $(\delta,\epsilon) $ depends on the actual $(\delta,\epsilon) $ and how complex the given class of hypothesis are. More precisely, a class of hypotheses $\mathcal{H}$ or models $f_{\theta}$ is PAC if for any pair $(\epsilon, \delta)$ with $ 0 < \epsilon,\delta , <.5 $ there is a specific model $f_{\Theta}$ such that any new data $\tilde{x}, \tilde{y} $, this model will satisfy $Err(f_{\Theta}(\tilde{x}) ,\tilde{y} ) < \epsilon$ with probability $ p > 1-\delta $ if the model was selected (trained) with at least $ m = m(\delta,\epsilon,\mathcal{H}) $ training examples. Here Err is the chosen loss function which is usually $(f_{\Theta}(\tilde{x}) -\tilde{y})^2$. The diagram you have gives a formula for how much data one needs to train on for a given class of hypotheses to satisfy a given pair $(\delta,\epsilon) $. I could be wrong, but I believe that this definition was given by Valiant in a paper called "A Theory of the Learnable" and was in part responsible for Valiant winning the Turing prize.
What does PAC learning theory mean? The definition of probably approximately correct is due to Valiant. It is meant to give a mathematically rigorous definition of what is machine learning. Let me ramble a bit. While PAC uses the ter
11,838
Scatterplot with contour/heat overlay
Here is my take, using base functions only for drawing stuff: library(MASS) # in case it is not already loaded set.seed(101) n <- 1000 X <- mvrnorm(n, mu=c(.5,2.5), Sigma=matrix(c(1,.6,.6,1), ncol=2)) ## some pretty colors library(RColorBrewer) k <- 11 my.cols <- rev(brewer.pal(k, "RdYlBu")) ## compute 2D kernel density, see MASS book, pp. 130-131 z <- kde2d(X[,1], X[,2], n=50) plot(X, xlab="X label", ylab="Y label", pch=19, cex=.4) contour(z, drawlabels=FALSE, nlevels=k, col=my.cols, add=TRUE) abline(h=mean(X[,2]), v=mean(X[,1]), lwd=2) legend("topleft", paste("R=", round(cor(X)[1,2],2)), bty="n") For more fancy rendering, you might want to have a look at ggplot2 and stat_density2d(). Another function I like is smoothScatter(): smoothScatter(X, nrpoints=.3*n, colramp=colorRampPalette(my.cols), pch=19, cex=.8)
Scatterplot with contour/heat overlay
Here is my take, using base functions only for drawing stuff: library(MASS) # in case it is not already loaded set.seed(101) n <- 1000 X <- mvrnorm(n, mu=c(.5,2.5), Sigma=matrix(c(1,.6,.6,1), ncol=2
Scatterplot with contour/heat overlay Here is my take, using base functions only for drawing stuff: library(MASS) # in case it is not already loaded set.seed(101) n <- 1000 X <- mvrnorm(n, mu=c(.5,2.5), Sigma=matrix(c(1,.6,.6,1), ncol=2)) ## some pretty colors library(RColorBrewer) k <- 11 my.cols <- rev(brewer.pal(k, "RdYlBu")) ## compute 2D kernel density, see MASS book, pp. 130-131 z <- kde2d(X[,1], X[,2], n=50) plot(X, xlab="X label", ylab="Y label", pch=19, cex=.4) contour(z, drawlabels=FALSE, nlevels=k, col=my.cols, add=TRUE) abline(h=mean(X[,2]), v=mean(X[,1]), lwd=2) legend("topleft", paste("R=", round(cor(X)[1,2],2)), bty="n") For more fancy rendering, you might want to have a look at ggplot2 and stat_density2d(). Another function I like is smoothScatter(): smoothScatter(X, nrpoints=.3*n, colramp=colorRampPalette(my.cols), pch=19, cex=.8)
Scatterplot with contour/heat overlay Here is my take, using base functions only for drawing stuff: library(MASS) # in case it is not already loaded set.seed(101) n <- 1000 X <- mvrnorm(n, mu=c(.5,2.5), Sigma=matrix(c(1,.6,.6,1), ncol=2
11,839
Scatterplot with contour/heat overlay
No-one has suggested ggplot2 for this?? library(MASS) library(ggplot2) n <- 1000 x <- mvrnorm(n, mu=c(.5,2.5), Sigma=matrix(c(1,.6,.6,1), ncol=2)) df = data.frame(x); colnames(df) = c("x","y") commonTheme = list(labs(color="Density",fill="Density", x="RNA-seq Expression", y="Microarray Expression"), theme_bw(), theme(legend.position=c(0,1), legend.justification=c(0,1))) ggplot(data=df,aes(x,y)) + geom_density2d(aes(colour=..level..)) + scale_colour_gradient(low="green",high="red") + geom_point() + commonTheme Which produces the following: However, other stuff can be done too, quite easily, such as the following: ggplot(data=df,aes(x,y)) + stat_density2d(aes(fill=..level..,alpha=..level..),geom='polygon',colour='black') + scale_fill_continuous(low="green",high="red") + geom_smooth(method=lm,linetype=2,colour="red",se=F) + guides(alpha="none") + geom_point() + commonTheme Which produces the following:
Scatterplot with contour/heat overlay
No-one has suggested ggplot2 for this?? library(MASS) library(ggplot2) n <- 1000 x <- mvrnorm(n, mu=c(.5,2.5), Sigma=matrix(c(1,.6,.6,1), ncol=2)) df = data.frame(x); colnames(df) = c("x","y") common
Scatterplot with contour/heat overlay No-one has suggested ggplot2 for this?? library(MASS) library(ggplot2) n <- 1000 x <- mvrnorm(n, mu=c(.5,2.5), Sigma=matrix(c(1,.6,.6,1), ncol=2)) df = data.frame(x); colnames(df) = c("x","y") commonTheme = list(labs(color="Density",fill="Density", x="RNA-seq Expression", y="Microarray Expression"), theme_bw(), theme(legend.position=c(0,1), legend.justification=c(0,1))) ggplot(data=df,aes(x,y)) + geom_density2d(aes(colour=..level..)) + scale_colour_gradient(low="green",high="red") + geom_point() + commonTheme Which produces the following: However, other stuff can be done too, quite easily, such as the following: ggplot(data=df,aes(x,y)) + stat_density2d(aes(fill=..level..,alpha=..level..),geom='polygon',colour='black') + scale_fill_continuous(low="green",high="red") + geom_smooth(method=lm,linetype=2,colour="red",se=F) + guides(alpha="none") + geom_point() + commonTheme Which produces the following:
Scatterplot with contour/heat overlay No-one has suggested ggplot2 for this?? library(MASS) library(ggplot2) n <- 1000 x <- mvrnorm(n, mu=c(.5,2.5), Sigma=matrix(c(1,.6,.6,1), ncol=2)) df = data.frame(x); colnames(df) = c("x","y") common
11,840
Comparing non nested models with AIC
The AIC can be applied with non nested models. In fact, this is one of the most extended myths (misunderstandings?) about AIC. See: Akaike Information Criterion AIC MYTHS AND MISUNDERSTANDINGS One thing you have to be careful about is to include all the normalising constants, since these are different for the different (non-nested) models: See also: Non-nested model selection AIC for non-nested models: normalizing constant In the context of GLMM a more delicate question is how reliable is the AIC for comparing this sort of models (see also @BenBolker's). Other versions of the AIC are discussed and compared in the following paper: On the behaviour of marginal and conditional AIC in linear mixed models
Comparing non nested models with AIC
The AIC can be applied with non nested models. In fact, this is one of the most extended myths (misunderstandings?) about AIC. See: Akaike Information Criterion AIC MYTHS AND MISUNDERSTANDINGS One t
Comparing non nested models with AIC The AIC can be applied with non nested models. In fact, this is one of the most extended myths (misunderstandings?) about AIC. See: Akaike Information Criterion AIC MYTHS AND MISUNDERSTANDINGS One thing you have to be careful about is to include all the normalising constants, since these are different for the different (non-nested) models: See also: Non-nested model selection AIC for non-nested models: normalizing constant In the context of GLMM a more delicate question is how reliable is the AIC for comparing this sort of models (see also @BenBolker's). Other versions of the AIC are discussed and compared in the following paper: On the behaviour of marginal and conditional AIC in linear mixed models
Comparing non nested models with AIC The AIC can be applied with non nested models. In fact, this is one of the most extended myths (misunderstandings?) about AIC. See: Akaike Information Criterion AIC MYTHS AND MISUNDERSTANDINGS One t
11,841
Comparing non nested models with AIC
For reference, a counterargument: Brian Ripley states in "Selecting amongst large classes of models" pp. 6-7 Crucial assumptions ... The models are nested (footnote: see the bottom of page 615 in the reprint of Akaike (1973)). – AIC is widely used when they are not The relevant passage (also p. 204 of another reprint of Akaike), starts I think with the phrase "The problem of statistical model identification is often formulated as the problem of selection of $f(x|_k\theta$) ...") is not quite available here; I'm looking for a PDF of the paper so I can quote the passage here ... (I've quoted it below, although honestly at this point I can't see how it supports Ripley's point - it certainly discusses the derivation in the context of nested models but ... ???) Ripley, B. D. 2004. “Selecting amongst Large Classes of Models.” In Methods and Models in Statistics, edited by N. Adams, M. Crowder, D. J Hand, and D. Stephens, 155–70. London, England: Imperial College Press. Akaike, H. (1973) Information theory and an extension of the maximum likelihood principle. In Second International Symposium on Information Theory (Eds B. N. Petrov and F. Cáski), pp. 267–281, Budapest. Akademiai Kaidó. Reprinted in Breakthroughs in Statistics , eds Kotz,S. & Johnson, N. L. (1992), volume I, pp. 599–624. New York: Springer. For reference, see also this post on MathOverflow.
Comparing non nested models with AIC
For reference, a counterargument: Brian Ripley states in "Selecting amongst large classes of models" pp. 6-7 Crucial assumptions ... The models are nested (footnote: see the bottom of page 615 in th
Comparing non nested models with AIC For reference, a counterargument: Brian Ripley states in "Selecting amongst large classes of models" pp. 6-7 Crucial assumptions ... The models are nested (footnote: see the bottom of page 615 in the reprint of Akaike (1973)). – AIC is widely used when they are not The relevant passage (also p. 204 of another reprint of Akaike), starts I think with the phrase "The problem of statistical model identification is often formulated as the problem of selection of $f(x|_k\theta$) ...") is not quite available here; I'm looking for a PDF of the paper so I can quote the passage here ... (I've quoted it below, although honestly at this point I can't see how it supports Ripley's point - it certainly discusses the derivation in the context of nested models but ... ???) Ripley, B. D. 2004. “Selecting amongst Large Classes of Models.” In Methods and Models in Statistics, edited by N. Adams, M. Crowder, D. J Hand, and D. Stephens, 155–70. London, England: Imperial College Press. Akaike, H. (1973) Information theory and an extension of the maximum likelihood principle. In Second International Symposium on Information Theory (Eds B. N. Petrov and F. Cáski), pp. 267–281, Budapest. Akademiai Kaidó. Reprinted in Breakthroughs in Statistics , eds Kotz,S. & Johnson, N. L. (1992), volume I, pp. 599–624. New York: Springer. For reference, see also this post on MathOverflow.
Comparing non nested models with AIC For reference, a counterargument: Brian Ripley states in "Selecting amongst large classes of models" pp. 6-7 Crucial assumptions ... The models are nested (footnote: see the bottom of page 615 in th
11,842
Comparing non nested models with AIC
It appears Akaike thought AIC was a useful tool for comparing non-nested models. "One important observation about AIC is that it is defined without specific reference to the true model [ f(x|kθ) ]. Thus, for any finite number of parametric models, we may always consider an extended model that will play the role of [ f(x|kθ) ] This suggests that AIC can be useful, at least in principle, for the comparison of models which are nonnested, i.e., the situation where the conventional log likelihood-ratio test is not applicable." (Akaike 1985, pg. 399) Akaike, Hirotugu. "Prediction and entropy." Selected Papers of Hirotugu Akaike. Springer, New York, NY, 1985. 387-410.
Comparing non nested models with AIC
It appears Akaike thought AIC was a useful tool for comparing non-nested models. "One important observation about AIC is that it is defined without specific reference to the true model [ f(x|kθ) ]. T
Comparing non nested models with AIC It appears Akaike thought AIC was a useful tool for comparing non-nested models. "One important observation about AIC is that it is defined without specific reference to the true model [ f(x|kθ) ]. Thus, for any finite number of parametric models, we may always consider an extended model that will play the role of [ f(x|kθ) ] This suggests that AIC can be useful, at least in principle, for the comparison of models which are nonnested, i.e., the situation where the conventional log likelihood-ratio test is not applicable." (Akaike 1985, pg. 399) Akaike, Hirotugu. "Prediction and entropy." Selected Papers of Hirotugu Akaike. Springer, New York, NY, 1985. 387-410.
Comparing non nested models with AIC It appears Akaike thought AIC was a useful tool for comparing non-nested models. "One important observation about AIC is that it is defined without specific reference to the true model [ f(x|kθ) ]. T
11,843
Ljung-Box Statistics for ARIMA residuals in R: confusing test results
You've interpreted the test wrong. If the p value is greater than 0.05 then the residuals are independent which we want for the model to be correct. If you simulate a white noise time series using the code below and use the same test for it then the p value will be greater than 0.05. m = c(ar, ma) w = arima.sim(m, 120) w = ts(w) plot(w) Box.test(w, type="Ljung-Box")
Ljung-Box Statistics for ARIMA residuals in R: confusing test results
You've interpreted the test wrong. If the p value is greater than 0.05 then the residuals are independent which we want for the model to be correct. If you simulate a white noise time series using the
Ljung-Box Statistics for ARIMA residuals in R: confusing test results You've interpreted the test wrong. If the p value is greater than 0.05 then the residuals are independent which we want for the model to be correct. If you simulate a white noise time series using the code below and use the same test for it then the p value will be greater than 0.05. m = c(ar, ma) w = arima.sim(m, 120) w = ts(w) plot(w) Box.test(w, type="Ljung-Box")
Ljung-Box Statistics for ARIMA residuals in R: confusing test results You've interpreted the test wrong. If the p value is greater than 0.05 then the residuals are independent which we want for the model to be correct. If you simulate a white noise time series using the
11,844
Ljung-Box Statistics for ARIMA residuals in R: confusing test results
Many statistical tests are used to try to reject some null hypothesis. In this particular case the Ljung-Box test tries to reject the independence of some values. What does it mean? If p-value < 0.051: You can reject the null hypothesis assuming a 5% chance of making a mistake. So you can assume that your values are showing dependence on each other. If p-value > 0.051: You don't have enough statistical evidence to reject the null hypothesis. So you can not assume that your values are dependent. This could mean that your values are dependent anyway or it can mean that your values are independent. But you are not proving any specific possibility, what your test actually said is that you can not assert the dependence of the values, neither can you assert the independence of the values. In general, what is important here is to keep in mind that p-value < 0.05 lets you reject of the null-hypothesis, but a p-value > 0.05 does not let you confirm the null-hypothesis. In particular, you can not proof the independence of the values of Time Series using the Ljung-Box test. You can only prove the dependence. 1: I assumed $\alpha = 0.05$, which is a standard value of risk.
Ljung-Box Statistics for ARIMA residuals in R: confusing test results
Many statistical tests are used to try to reject some null hypothesis. In this particular case the Ljung-Box test tries to reject the independence of some values. What does it mean? If p-value < 0.05
Ljung-Box Statistics for ARIMA residuals in R: confusing test results Many statistical tests are used to try to reject some null hypothesis. In this particular case the Ljung-Box test tries to reject the independence of some values. What does it mean? If p-value < 0.051: You can reject the null hypothesis assuming a 5% chance of making a mistake. So you can assume that your values are showing dependence on each other. If p-value > 0.051: You don't have enough statistical evidence to reject the null hypothesis. So you can not assume that your values are dependent. This could mean that your values are dependent anyway or it can mean that your values are independent. But you are not proving any specific possibility, what your test actually said is that you can not assert the dependence of the values, neither can you assert the independence of the values. In general, what is important here is to keep in mind that p-value < 0.05 lets you reject of the null-hypothesis, but a p-value > 0.05 does not let you confirm the null-hypothesis. In particular, you can not proof the independence of the values of Time Series using the Ljung-Box test. You can only prove the dependence. 1: I assumed $\alpha = 0.05$, which is a standard value of risk.
Ljung-Box Statistics for ARIMA residuals in R: confusing test results Many statistical tests are used to try to reject some null hypothesis. In this particular case the Ljung-Box test tries to reject the independence of some values. What does it mean? If p-value < 0.05
11,845
Ljung-Box Statistics for ARIMA residuals in R: confusing test results
According to the ACF graphs, it is obviously that the fit 1 is better since the correlation coefficient at lag k(k>1) drops sharply, and close to 0.
Ljung-Box Statistics for ARIMA residuals in R: confusing test results
According to the ACF graphs, it is obviously that the fit 1 is better since the correlation coefficient at lag k(k>1) drops sharply, and close to 0.
Ljung-Box Statistics for ARIMA residuals in R: confusing test results According to the ACF graphs, it is obviously that the fit 1 is better since the correlation coefficient at lag k(k>1) drops sharply, and close to 0.
Ljung-Box Statistics for ARIMA residuals in R: confusing test results According to the ACF graphs, it is obviously that the fit 1 is better since the correlation coefficient at lag k(k>1) drops sharply, and close to 0.
11,846
Ljung-Box Statistics for ARIMA residuals in R: confusing test results
If you are judging with ACF then fit 1 is more appropriate. Instead of being confused on Ljung test you can still use the correlogram of the residuals to ascertain the best fit between fit1 and fit2
Ljung-Box Statistics for ARIMA residuals in R: confusing test results
If you are judging with ACF then fit 1 is more appropriate. Instead of being confused on Ljung test you can still use the correlogram of the residuals to ascertain the best fit between fit1 and fit2
Ljung-Box Statistics for ARIMA residuals in R: confusing test results If you are judging with ACF then fit 1 is more appropriate. Instead of being confused on Ljung test you can still use the correlogram of the residuals to ascertain the best fit between fit1 and fit2
Ljung-Box Statistics for ARIMA residuals in R: confusing test results If you are judging with ACF then fit 1 is more appropriate. Instead of being confused on Ljung test you can still use the correlogram of the residuals to ascertain the best fit between fit1 and fit2
11,847
Ljung-Box Statistics for ARIMA residuals in R: confusing test results
The Ljung-Box test uses the following hypotheses: H0: The residuals are independently distributed. HA: The residuals are not independently distributed; they exhibit serial correlation. Ideally, we would like to be unable to reject the null hypothesis. That is, we would like to see a p-value greater than 0.05 because this means the residuals for our time series model are independent, which is often an assumption we make when creating a model.
Ljung-Box Statistics for ARIMA residuals in R: confusing test results
The Ljung-Box test uses the following hypotheses: H0: The residuals are independently distributed. HA: The residuals are not independently distributed; they exhibit serial correlation. Ideally, we wou
Ljung-Box Statistics for ARIMA residuals in R: confusing test results The Ljung-Box test uses the following hypotheses: H0: The residuals are independently distributed. HA: The residuals are not independently distributed; they exhibit serial correlation. Ideally, we would like to be unable to reject the null hypothesis. That is, we would like to see a p-value greater than 0.05 because this means the residuals for our time series model are independent, which is often an assumption we make when creating a model.
Ljung-Box Statistics for ARIMA residuals in R: confusing test results The Ljung-Box test uses the following hypotheses: H0: The residuals are independently distributed. HA: The residuals are not independently distributed; they exhibit serial correlation. Ideally, we wou
11,848
R-squared is equal to 81% means what?
As a matter of fact, this last explanation is the best one: r-squared is the percentage of variation in 'Y' that is accounted for by its regression on 'X' Yes, it is quite abstract. Let's try to understand it. Here is some simulated data. R code: set.seed(1) xx <- runif(100) yy <- 1-xx^2+rnorm(length(xx),0,0.1) plot(xx,yy,pch=19) What we are mainly interested in is the variation in the dependent variable $y$. In a first step, let's disregard the predictor $x$. In this very simple "model", the variation in $y$ is the sum of the squared differences between the entries of $y$ and the mean of $y$, $\overline{y}$: abline(h=mean(yy),col="red",lwd=2) lines(rbind(xx,xx,NA),rbind(yy,mean(yy),NA),col="gray") This sum of squares turns out to be: sum((yy-mean(yy))^2) [1] 8.14846 Now, we try a slightly more sophisticated model: we regress $y$ on $x$ and check how much variation remains after that. That is, we now calculate the sums of squared differences between the $y$ and the regression line: plot(xx,yy,pch=19) model <- lm(yy~xx) abline(model,col="red",lwd=2) lines(rbind(xx,xx,NA),rbind(yy,predict(model),NA),col="gray") Note how the differences - the gray lines - are much smaller now than before! And here is the sum of squared differences between the $y$ and the regression line: sum(residuals(model)^2) [1] 1.312477 It turns out that this is only about 16% of the sums of squared residuals we had above: sum(residuals(model)^2)/sum((yy-mean(yy))^2) [1] 0.1610705 Thus, our regression line model reduced the unexplained variation in the observed data $y$ by 100%-16% = 84%. And this number is precisely the $R^2$ that R will report to us: summary(model) Call: lm(formula = yy ~ xx) ... snip ... Multiple R-squared: 0.8389, Adjusted R-squared: 0.8373 Now, one question you might have is why we calculate variation as a sum of squares. Wouldn't it be easier to just sum up the absolute lengths of the deviations we plot above? The reason for that lies in the fact that squares are just much easier to handle mathematically, and it turns out that if we work with squares, we can prove all kinds of helpful theorems about $R^2$ and related quantities, namely $F$ tests and ANOVA tables.
R-squared is equal to 81% means what?
As a matter of fact, this last explanation is the best one: r-squared is the percentage of variation in 'Y' that is accounted for by its regression on 'X' Yes, it is quite abstract. Let's try to und
R-squared is equal to 81% means what? As a matter of fact, this last explanation is the best one: r-squared is the percentage of variation in 'Y' that is accounted for by its regression on 'X' Yes, it is quite abstract. Let's try to understand it. Here is some simulated data. R code: set.seed(1) xx <- runif(100) yy <- 1-xx^2+rnorm(length(xx),0,0.1) plot(xx,yy,pch=19) What we are mainly interested in is the variation in the dependent variable $y$. In a first step, let's disregard the predictor $x$. In this very simple "model", the variation in $y$ is the sum of the squared differences between the entries of $y$ and the mean of $y$, $\overline{y}$: abline(h=mean(yy),col="red",lwd=2) lines(rbind(xx,xx,NA),rbind(yy,mean(yy),NA),col="gray") This sum of squares turns out to be: sum((yy-mean(yy))^2) [1] 8.14846 Now, we try a slightly more sophisticated model: we regress $y$ on $x$ and check how much variation remains after that. That is, we now calculate the sums of squared differences between the $y$ and the regression line: plot(xx,yy,pch=19) model <- lm(yy~xx) abline(model,col="red",lwd=2) lines(rbind(xx,xx,NA),rbind(yy,predict(model),NA),col="gray") Note how the differences - the gray lines - are much smaller now than before! And here is the sum of squared differences between the $y$ and the regression line: sum(residuals(model)^2) [1] 1.312477 It turns out that this is only about 16% of the sums of squared residuals we had above: sum(residuals(model)^2)/sum((yy-mean(yy))^2) [1] 0.1610705 Thus, our regression line model reduced the unexplained variation in the observed data $y$ by 100%-16% = 84%. And this number is precisely the $R^2$ that R will report to us: summary(model) Call: lm(formula = yy ~ xx) ... snip ... Multiple R-squared: 0.8389, Adjusted R-squared: 0.8373 Now, one question you might have is why we calculate variation as a sum of squares. Wouldn't it be easier to just sum up the absolute lengths of the deviations we plot above? The reason for that lies in the fact that squares are just much easier to handle mathematically, and it turns out that if we work with squares, we can prove all kinds of helpful theorems about $R^2$ and related quantities, namely $F$ tests and ANOVA tables.
R-squared is equal to 81% means what? As a matter of fact, this last explanation is the best one: r-squared is the percentage of variation in 'Y' that is accounted for by its regression on 'X' Yes, it is quite abstract. Let's try to und
11,849
R-squared is equal to 81% means what?
An R-squared is the percentage of variance explained by a model. Let's say your data has a variance of 100: that is the sum of squared errors versus the mean and divided by $N-1$ (the degrees of freedom). Then you go model the data and your model has an $R^2$ of 81%. That means that the model predictions have a variance of 81. The remaining variance, 19, is the variance of your data versus the conditional mean (i.e. the variance about the regression line). Thus your first statement is correct: there is "81% less variance around the regression line than mean line." Your second and third statements are not correct since "less error" and "closer" could easily be interpreted as using the distance between points and the regression line (and so minimizing the $L_1$ norm=absolute value of errors). Your fourth statement is very difficult to interpret, so I do not know if you could even say it is wrong. Prediction being "81% better" is totally unclear in what it means. You have already mentioned "closer" yet we cannot conclude that this model is 81% closer to the observed data (as per the above critiques of statements #2 and #3.) Worse: we could just add many noise variables to the model. Those are likely to be insignificant yet you could find some set of them which would increase the $R^2$. (You have then overfit your data.) I doubt you or any statistician would conclude this larger model with is better in any sense. Furthermore, your model may only be trying to explain and not predict, so I would especially avoid statements like #4.
R-squared is equal to 81% means what?
An R-squared is the percentage of variance explained by a model. Let's say your data has a variance of 100: that is the sum of squared errors versus the mean and divided by $N-1$ (the degrees of freed
R-squared is equal to 81% means what? An R-squared is the percentage of variance explained by a model. Let's say your data has a variance of 100: that is the sum of squared errors versus the mean and divided by $N-1$ (the degrees of freedom). Then you go model the data and your model has an $R^2$ of 81%. That means that the model predictions have a variance of 81. The remaining variance, 19, is the variance of your data versus the conditional mean (i.e. the variance about the regression line). Thus your first statement is correct: there is "81% less variance around the regression line than mean line." Your second and third statements are not correct since "less error" and "closer" could easily be interpreted as using the distance between points and the regression line (and so minimizing the $L_1$ norm=absolute value of errors). Your fourth statement is very difficult to interpret, so I do not know if you could even say it is wrong. Prediction being "81% better" is totally unclear in what it means. You have already mentioned "closer" yet we cannot conclude that this model is 81% closer to the observed data (as per the above critiques of statements #2 and #3.) Worse: we could just add many noise variables to the model. Those are likely to be insignificant yet you could find some set of them which would increase the $R^2$. (You have then overfit your data.) I doubt you or any statistician would conclude this larger model with is better in any sense. Furthermore, your model may only be trying to explain and not predict, so I would especially avoid statements like #4.
R-squared is equal to 81% means what? An R-squared is the percentage of variance explained by a model. Let's say your data has a variance of 100: that is the sum of squared errors versus the mean and divided by $N-1$ (the degrees of freed
11,850
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?
Both the standard Normal and Student t distributions are rather poor approximations to the distribution of $$Z = \frac{\hat p - p}{\sqrt{\hat p(1-\hat p)/n}}$$ for small $n,$ so poor that the error dwarfs the differences between these two distributions. Here is a comparison of all three distributions (omitting the cases where $\hat p$ or $1-\hat p$ are zero, where the ratio is undefined) for $n=10, p=1/2:$ The "empirical" distribution is that of $Z,$ which must be discrete because the estimates $\hat p$ are limited to the finite set $\{0, 1/n, 2/n, \ldots, n/n\}.$ The $t$ distribution appears to do a better job of approximation. For $n=30$ and $p=1/2,$ you can see the difference between the standard Normal and Student t distributions is completely negligible: Because the Student t distribution is more complicated than the standard Normal (it's really an entire family of distributions indexed by the "degrees of freedom," formerly requiring entire chapters of tables rather than a single page), the standard Normal is used for almost all approximations.
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?
Both the standard Normal and Student t distributions are rather poor approximations to the distribution of $$Z = \frac{\hat p - p}{\sqrt{\hat p(1-\hat p)/n}}$$ for small $n,$ so poor that the error d
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion? Both the standard Normal and Student t distributions are rather poor approximations to the distribution of $$Z = \frac{\hat p - p}{\sqrt{\hat p(1-\hat p)/n}}$$ for small $n,$ so poor that the error dwarfs the differences between these two distributions. Here is a comparison of all three distributions (omitting the cases where $\hat p$ or $1-\hat p$ are zero, where the ratio is undefined) for $n=10, p=1/2:$ The "empirical" distribution is that of $Z,$ which must be discrete because the estimates $\hat p$ are limited to the finite set $\{0, 1/n, 2/n, \ldots, n/n\}.$ The $t$ distribution appears to do a better job of approximation. For $n=30$ and $p=1/2,$ you can see the difference between the standard Normal and Student t distributions is completely negligible: Because the Student t distribution is more complicated than the standard Normal (it's really an entire family of distributions indexed by the "degrees of freedom," formerly requiring entire chapters of tables rather than a single page), the standard Normal is used for almost all approximations.
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion? Both the standard Normal and Student t distributions are rather poor approximations to the distribution of $$Z = \frac{\hat p - p}{\sqrt{\hat p(1-\hat p)/n}}$$ for small $n,$ so poor that the error d
11,851
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?
The justification for using the t distribution in the confidence interval for a mean relies on the assumption that the underlying data follows a normal distribution, which leads to a chi-squared distribution when estimating the standard deviation, and thus $\frac{\bar{x}-\mu}{s/ \sqrt{n}} \sim t_{n-1}$. This is an exact result under the assumption that the data are exactly normal that leads to confidence intervals with exactly 95% coverage when using $t$, and less than 95% coverage if using $z$. In the case of Wald intervals for proportions, you only get asymptotic normality for $\frac{\hat{p}- p}{\sqrt{ \hat{p}(1-\hat{p} )/n}}$ when n is large enough, which depends on p. The actual coverage probability of the procedure, since the underlying counts of successes are discrete, is sometimes below and sometimes above the nominal coverage probability of 95% depending on the unknown $p$. So, there is no theoretical justification for using $t$, and there is no guarantee that from a practical perspective that using $t$ just to make the intervals wider would actually help achieve nominal coverage of 95%. The coverage probability can be calculated exactly, though it's fairly straightforward to simulate it. The following example shows the simulated coverage probability when n=35. It demonstrates that the coverage probability for using the z-interval is generally slightly smaller than .95, while the coverage probability for the t-interval may generally be slighter closer to .95 on average depending on your prior beliefs on the plausible values of p.
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?
The justification for using the t distribution in the confidence interval for a mean relies on the assumption that the underlying data follows a normal distribution, which leads to a chi-squared distr
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion? The justification for using the t distribution in the confidence interval for a mean relies on the assumption that the underlying data follows a normal distribution, which leads to a chi-squared distribution when estimating the standard deviation, and thus $\frac{\bar{x}-\mu}{s/ \sqrt{n}} \sim t_{n-1}$. This is an exact result under the assumption that the data are exactly normal that leads to confidence intervals with exactly 95% coverage when using $t$, and less than 95% coverage if using $z$. In the case of Wald intervals for proportions, you only get asymptotic normality for $\frac{\hat{p}- p}{\sqrt{ \hat{p}(1-\hat{p} )/n}}$ when n is large enough, which depends on p. The actual coverage probability of the procedure, since the underlying counts of successes are discrete, is sometimes below and sometimes above the nominal coverage probability of 95% depending on the unknown $p$. So, there is no theoretical justification for using $t$, and there is no guarantee that from a practical perspective that using $t$ just to make the intervals wider would actually help achieve nominal coverage of 95%. The coverage probability can be calculated exactly, though it's fairly straightforward to simulate it. The following example shows the simulated coverage probability when n=35. It demonstrates that the coverage probability for using the z-interval is generally slightly smaller than .95, while the coverage probability for the t-interval may generally be slighter closer to .95 on average depending on your prior beliefs on the plausible values of p.
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion? The justification for using the t distribution in the confidence interval for a mean relies on the assumption that the underlying data follows a normal distribution, which leads to a chi-squared distr
11,852
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?
Both AdamO and jsk give a great answer. I would try to repeat their points with plain English: When the underlying distribution is normal, you know there are two parameters: mean and variance. T distribution offers a way to do inference on the mean without knowing the exact value of the variances. Instead of using actual variances, only sample means and sample variances are needed. Because it is an exact distribution, you know exactly what you are getting. In other words, the coverage probability is correct. The usage of t simply reflects the desire to get around the unknown populuation variance. When we do inference on proportion, however, the underlying distribution is binomial. To get the exact distribution, you need to look at Clopper-Pearson confidence intervals. The formula you provide is the formula for Wald confidence interval. It use the normal distribution to approximate the binomial distribution, because normal distribution is the limiting distribution of the binomial distribution. In this case, because you are only approximating, the extra level of precision from using t statistics becomes unnecessary, it all comes down to empirical performance. As suggested in BruceET's answer, the Agresti-Coull is simple and standard formula nowadays for such approximation. My professor Dr Longnecker of Texas A&M has done a simple simulation to illustrate how the different approximation works compared to the binomial based CI. Further information can be found in the article Interval Estimation for a Binomial Proportion in Statistical Science, Vol. 16, pp.101-133, by L. Brown, T. Cai and A. DasGupta. Basically, A-C CI is recommended for n >= 40.
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?
Both AdamO and jsk give a great answer. I would try to repeat their points with plain English: When the underlying distribution is normal, you know there are two parameters: mean and variance. T dis
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion? Both AdamO and jsk give a great answer. I would try to repeat their points with plain English: When the underlying distribution is normal, you know there are two parameters: mean and variance. T distribution offers a way to do inference on the mean without knowing the exact value of the variances. Instead of using actual variances, only sample means and sample variances are needed. Because it is an exact distribution, you know exactly what you are getting. In other words, the coverage probability is correct. The usage of t simply reflects the desire to get around the unknown populuation variance. When we do inference on proportion, however, the underlying distribution is binomial. To get the exact distribution, you need to look at Clopper-Pearson confidence intervals. The formula you provide is the formula for Wald confidence interval. It use the normal distribution to approximate the binomial distribution, because normal distribution is the limiting distribution of the binomial distribution. In this case, because you are only approximating, the extra level of precision from using t statistics becomes unnecessary, it all comes down to empirical performance. As suggested in BruceET's answer, the Agresti-Coull is simple and standard formula nowadays for such approximation. My professor Dr Longnecker of Texas A&M has done a simple simulation to illustrate how the different approximation works compared to the binomial based CI. Further information can be found in the article Interval Estimation for a Binomial Proportion in Statistical Science, Vol. 16, pp.101-133, by L. Brown, T. Cai and A. DasGupta. Basically, A-C CI is recommended for n >= 40.
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion? Both AdamO and jsk give a great answer. I would try to repeat their points with plain English: When the underlying distribution is normal, you know there are two parameters: mean and variance. T dis
11,853
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?
Confidence interval for normal mean. Suppose we have a random sample $X_1, X_2, \dots X_n$ from a normal population. Let's look at the confidence interval for normal mean $\mu$ in terms of hypothesis testing. If $\sigma$ is known, then a two-sided test of $H_0:\mu = \mu_0$ against $H_a: \mu \ne \mu_0$ is based on the statistic $Z = \frac{\bar X - \mu_0}{\sigma/\sqrt{n}}.$ When $H_0$ is true, $Z \sim \mathsf{Norm}(0,1),$ so we reject $H_0$ at the 5% level if $|Z| \ge 1.96.$ Then 'inverting the test', we say that a 95% CI for $\mu$ consists of the values $\mu_0$ that do not lead to rejection--the 'believable' values of $\mu.$ The CI is of the form $\bar X \pm 1.96\sigma/\sqrt{n},$ where $\pm 1.96$ cut probability 0.025 from the upper and lower tails, respectively, of the standard normal distribution. If the population standard deviation $\sigma$ is unknown and estimated by by the sample standard deviation $S,$ then we use the statistic $T=\frac{\bar X - \mu_0}{S/\sqrt{n}}.$ Before the early 1900's people supposed that $T$ is approximately standard normal for $n$ large enough and used $S$ as a substitute for unknown $\sigma.$ There was debate about how large counts as large enough. Eventually, it was known that $T \sim \mathsf{T}(\nu = n-1),$ Student's t distribution with $n-1$ degrees of freedom. Accordingly, when $\sigma$ is not known, we use $\bar X \pm t^*S/\sqrt{n},$ where $\pm t^*$ cut probability 0.025 from the upper and lower tails, respectively, of $\mathsf{T}(n-1).$ [Note: For $n > 30,$ people have noticed that for 95% CIs $t^* \approx 2 \approx 1.96.$ Thus the century-old idea that you can "get by" just substituting $S$ for $\sigma$ when $\sigma$ is unknown and $n > 30,$ has persisted even in some recently-published books.] Confidence interval for binomial proportion. In the binomial case, suppose we have observed $X$ successes in a binomial experiment with $n$ independent trials. Then we use $\hat p =X/n$ as an estimate of the binomial success probability $p.$ In order to test $H_0:p = p_0$ vs $H_a: p \ne p>0,$ we use the statitic $Z = \frac{\hat p - p_0}{\sqrt{p_0(1-p_0)/n}}.$ Under $H_0,$ we know that $Z \stackrel{aprx}{\sim} \mathsf{Norm}(0,1).$ So we reject $H_0$ if $|Z| \ge 1.96.$ If we seek to invert this test to get a 95% CI for $p,$ we run into some difficulties. The 'easy' way to invert the test is to start by writing $\hat p \pm 1.96\sqrt{\frac{p(1-p)}{n}}.$ But his is useless because the value of $p$ under the square root is unknown. The traditional Wald CI assumes that, for sufficiently large $n,$ it is OK to substitute $\hat p$ for unknown $p.$ Thus the Wald CI is of the form $\hat p \pm 1.96\sqrt{\frac{\hat p(1-\hat p)}{n}}.$ [Unfortunately, the Wald interval works well only if the number of trials $n$ is at least several hundred.] More carefully, one can solve a somewhat messy quadratic inequality to 'invert the test'. The result is the Wilson interval. (See Wikipedia.) For a 95% confidence interval a somewhat simplified version of this result comes from defining $\check n = n+4$ and $\check p = (X+2)/\check n$ and then computing the interval as $\check p \pm 1.96\sqrt{\frac{\check p(1-\check p)}{\check n}}.$ This style of binomial confidence interval is widely known as the Agresti-Coull interval; it has been widely advocated in elementary textbooks for about the last 20 years. In summary, one way to look at your question is that CIs for normal $\mu$ and binomial $p$ can be viewed as inversions of tests. (a) The t distribution provides an exact solution to the problem of needing to use $S$ for $\sigma$ when $\sigma$ is unknown. (b) Using $\hat p$ for $p$ requires some care because the mean and variance of $\hat p$ both depend on $p.$ The Agresti-Coull CI provides one serviceable way to get CIs for binomial $p$ that are reasonably accurate even for moderately small $n.$
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?
Confidence interval for normal mean. Suppose we have a random sample $X_1, X_2, \dots X_n$ from a normal population. Let's look at the confidence interval for normal mean $\mu$ in terms of hypothesis
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion? Confidence interval for normal mean. Suppose we have a random sample $X_1, X_2, \dots X_n$ from a normal population. Let's look at the confidence interval for normal mean $\mu$ in terms of hypothesis testing. If $\sigma$ is known, then a two-sided test of $H_0:\mu = \mu_0$ against $H_a: \mu \ne \mu_0$ is based on the statistic $Z = \frac{\bar X - \mu_0}{\sigma/\sqrt{n}}.$ When $H_0$ is true, $Z \sim \mathsf{Norm}(0,1),$ so we reject $H_0$ at the 5% level if $|Z| \ge 1.96.$ Then 'inverting the test', we say that a 95% CI for $\mu$ consists of the values $\mu_0$ that do not lead to rejection--the 'believable' values of $\mu.$ The CI is of the form $\bar X \pm 1.96\sigma/\sqrt{n},$ where $\pm 1.96$ cut probability 0.025 from the upper and lower tails, respectively, of the standard normal distribution. If the population standard deviation $\sigma$ is unknown and estimated by by the sample standard deviation $S,$ then we use the statistic $T=\frac{\bar X - \mu_0}{S/\sqrt{n}}.$ Before the early 1900's people supposed that $T$ is approximately standard normal for $n$ large enough and used $S$ as a substitute for unknown $\sigma.$ There was debate about how large counts as large enough. Eventually, it was known that $T \sim \mathsf{T}(\nu = n-1),$ Student's t distribution with $n-1$ degrees of freedom. Accordingly, when $\sigma$ is not known, we use $\bar X \pm t^*S/\sqrt{n},$ where $\pm t^*$ cut probability 0.025 from the upper and lower tails, respectively, of $\mathsf{T}(n-1).$ [Note: For $n > 30,$ people have noticed that for 95% CIs $t^* \approx 2 \approx 1.96.$ Thus the century-old idea that you can "get by" just substituting $S$ for $\sigma$ when $\sigma$ is unknown and $n > 30,$ has persisted even in some recently-published books.] Confidence interval for binomial proportion. In the binomial case, suppose we have observed $X$ successes in a binomial experiment with $n$ independent trials. Then we use $\hat p =X/n$ as an estimate of the binomial success probability $p.$ In order to test $H_0:p = p_0$ vs $H_a: p \ne p>0,$ we use the statitic $Z = \frac{\hat p - p_0}{\sqrt{p_0(1-p_0)/n}}.$ Under $H_0,$ we know that $Z \stackrel{aprx}{\sim} \mathsf{Norm}(0,1).$ So we reject $H_0$ if $|Z| \ge 1.96.$ If we seek to invert this test to get a 95% CI for $p,$ we run into some difficulties. The 'easy' way to invert the test is to start by writing $\hat p \pm 1.96\sqrt{\frac{p(1-p)}{n}}.$ But his is useless because the value of $p$ under the square root is unknown. The traditional Wald CI assumes that, for sufficiently large $n,$ it is OK to substitute $\hat p$ for unknown $p.$ Thus the Wald CI is of the form $\hat p \pm 1.96\sqrt{\frac{\hat p(1-\hat p)}{n}}.$ [Unfortunately, the Wald interval works well only if the number of trials $n$ is at least several hundred.] More carefully, one can solve a somewhat messy quadratic inequality to 'invert the test'. The result is the Wilson interval. (See Wikipedia.) For a 95% confidence interval a somewhat simplified version of this result comes from defining $\check n = n+4$ and $\check p = (X+2)/\check n$ and then computing the interval as $\check p \pm 1.96\sqrt{\frac{\check p(1-\check p)}{\check n}}.$ This style of binomial confidence interval is widely known as the Agresti-Coull interval; it has been widely advocated in elementary textbooks for about the last 20 years. In summary, one way to look at your question is that CIs for normal $\mu$ and binomial $p$ can be viewed as inversions of tests. (a) The t distribution provides an exact solution to the problem of needing to use $S$ for $\sigma$ when $\sigma$ is unknown. (b) Using $\hat p$ for $p$ requires some care because the mean and variance of $\hat p$ both depend on $p.$ The Agresti-Coull CI provides one serviceable way to get CIs for binomial $p$ that are reasonably accurate even for moderately small $n.$
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion? Confidence interval for normal mean. Suppose we have a random sample $X_1, X_2, \dots X_n$ from a normal population. Let's look at the confidence interval for normal mean $\mu$ in terms of hypothesis
11,854
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?
Note your use of the $\sigma$ notation which means the (known) population standard deviation. The T-distribution arose as an answer to the question: what happens when you don't know $\sigma$? He noted that, when you cheat by estimating $\sigma$ from the sample as a plug-in estimator, your CIs are on average too narrow. This necessitated the T-distribution. Conversely, if you use the T distribution when you actually do know $\sigma$, your confidence intervals will on average be too wide. Also, it should be noted that this question mirrors the answer solicited by this question.
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?
Note your use of the $\sigma$ notation which means the (known) population standard deviation. The T-distribution arose as an answer to the question: what happens when you don't know $\sigma$? He noted
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion? Note your use of the $\sigma$ notation which means the (known) population standard deviation. The T-distribution arose as an answer to the question: what happens when you don't know $\sigma$? He noted that, when you cheat by estimating $\sigma$ from the sample as a plug-in estimator, your CIs are on average too narrow. This necessitated the T-distribution. Conversely, if you use the T distribution when you actually do know $\sigma$, your confidence intervals will on average be too wide. Also, it should be noted that this question mirrors the answer solicited by this question.
Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion? Note your use of the $\sigma$ notation which means the (known) population standard deviation. The T-distribution arose as an answer to the question: what happens when you don't know $\sigma$? He noted
11,855
Why is a $p(\sigma^2)\sim\text{IG(0.001, 0.001)}$ prior on variance considered weak?
Using the inverse gamma distribution, we get: $$p(\sigma^2|\alpha,\beta) \propto (\sigma^2)^{-\alpha-1} \exp(-\frac{\beta}{\sigma^2})$$ You can see easily that if $\beta \rightarrow 0$ and $\alpha \rightarrow 0$ then the inverse gamma will approach the Jeffreys prior. This distribution is called "uninformative" because it is a proper approximation to the Jeffreys prior $$p(\sigma^2) \propto \frac{1}{\sigma^2}$$ Which is uninformative for scale parameters see page 18 here for example, because this prior is the only one which remains invariant under a change of scale (note that the approximation is not invariant). This has a indefinite integral of $\log(\sigma^2)$ which shows that it is improper if the range of $\sigma^2$ includes either $0$ or $\infty$. But these cases are only problems in the maths - not in the real world. Never actually observe infinite value for variance, and if the observed variance is zero, you have perfect data!. For you can set a lower limit equal to $L>0$ and upper limit equal $U<\infty$, and your distribution is proper. While it may seem strange that this is "uninformative" in that it prefers small variance to large ones, but this is only on one scale. You can show that $\log(\sigma^2)$ has an improper uniform distribution. So this prior does not favor any one scale over any other Although not directly related to your question, I would suggest a "better" non-informative distribution by choosing the upper and lower limits $L$ and $U$ in the Jeffreys prior rather than $\alpha$ and $\beta$. Usually the limits can be set fairly easily with a bit of thought to what $\sigma^2$ actually means in the real world. If it was the error in some kind of physical quantity - $L$ cannot be smaller than the size of an atom, or the smallest size you can observe in your experiment. Further $U$ could not be bigger than the earth (or the sun if you wanted to be really conservative). This way you keep your invariance properties, and its an easier prior to sample from: take $q_{(b)} \sim \mathrm{Uniform}(\log(L),\log(U))$, and then the simulated value as $\sigma^{2}_{(b)}=\exp(q_{(b)})$.
Why is a $p(\sigma^2)\sim\text{IG(0.001, 0.001)}$ prior on variance considered weak?
Using the inverse gamma distribution, we get: $$p(\sigma^2|\alpha,\beta) \propto (\sigma^2)^{-\alpha-1} \exp(-\frac{\beta}{\sigma^2})$$ You can see easily that if $\beta \rightarrow 0$ and $\alpha \ri
Why is a $p(\sigma^2)\sim\text{IG(0.001, 0.001)}$ prior on variance considered weak? Using the inverse gamma distribution, we get: $$p(\sigma^2|\alpha,\beta) \propto (\sigma^2)^{-\alpha-1} \exp(-\frac{\beta}{\sigma^2})$$ You can see easily that if $\beta \rightarrow 0$ and $\alpha \rightarrow 0$ then the inverse gamma will approach the Jeffreys prior. This distribution is called "uninformative" because it is a proper approximation to the Jeffreys prior $$p(\sigma^2) \propto \frac{1}{\sigma^2}$$ Which is uninformative for scale parameters see page 18 here for example, because this prior is the only one which remains invariant under a change of scale (note that the approximation is not invariant). This has a indefinite integral of $\log(\sigma^2)$ which shows that it is improper if the range of $\sigma^2$ includes either $0$ or $\infty$. But these cases are only problems in the maths - not in the real world. Never actually observe infinite value for variance, and if the observed variance is zero, you have perfect data!. For you can set a lower limit equal to $L>0$ and upper limit equal $U<\infty$, and your distribution is proper. While it may seem strange that this is "uninformative" in that it prefers small variance to large ones, but this is only on one scale. You can show that $\log(\sigma^2)$ has an improper uniform distribution. So this prior does not favor any one scale over any other Although not directly related to your question, I would suggest a "better" non-informative distribution by choosing the upper and lower limits $L$ and $U$ in the Jeffreys prior rather than $\alpha$ and $\beta$. Usually the limits can be set fairly easily with a bit of thought to what $\sigma^2$ actually means in the real world. If it was the error in some kind of physical quantity - $L$ cannot be smaller than the size of an atom, or the smallest size you can observe in your experiment. Further $U$ could not be bigger than the earth (or the sun if you wanted to be really conservative). This way you keep your invariance properties, and its an easier prior to sample from: take $q_{(b)} \sim \mathrm{Uniform}(\log(L),\log(U))$, and then the simulated value as $\sigma^{2}_{(b)}=\exp(q_{(b)})$.
Why is a $p(\sigma^2)\sim\text{IG(0.001, 0.001)}$ prior on variance considered weak? Using the inverse gamma distribution, we get: $$p(\sigma^2|\alpha,\beta) \propto (\sigma^2)^{-\alpha-1} \exp(-\frac{\beta}{\sigma^2})$$ You can see easily that if $\beta \rightarrow 0$ and $\alpha \ri
11,856
Why is a $p(\sigma^2)\sim\text{IG(0.001, 0.001)}$ prior on variance considered weak?
It's pretty close to flat. Its median is 1.9 E298, almost the largest number one can represent in double precision floating arithmetic. As you point out, the probability it assigns to any interval that isn't really huge is really small. It's hard to get less informative than that!
Why is a $p(\sigma^2)\sim\text{IG(0.001, 0.001)}$ prior on variance considered weak?
It's pretty close to flat. Its median is 1.9 E298, almost the largest number one can represent in double precision floating arithmetic. As you point out, the probability it assigns to any interval t
Why is a $p(\sigma^2)\sim\text{IG(0.001, 0.001)}$ prior on variance considered weak? It's pretty close to flat. Its median is 1.9 E298, almost the largest number one can represent in double precision floating arithmetic. As you point out, the probability it assigns to any interval that isn't really huge is really small. It's hard to get less informative than that!
Why is a $p(\sigma^2)\sim\text{IG(0.001, 0.001)}$ prior on variance considered weak? It's pretty close to flat. Its median is 1.9 E298, almost the largest number one can represent in double precision floating arithmetic. As you point out, the probability it assigns to any interval t
11,857
Is 50% 100% higher than 25% or is it 25% higher than 25%?
There are percent (%) and there are percentage points (%p), which are two different things. 50% (of $X$) is 100% more than 25% (of $X$). At the same time, 50% (of $X$) is 25%p more than 25% (of $X$). So if your bank promises to increase the interest rates on your deposit by 5%, that means nearly nothing; 5% of, say, 1% original rate is just 0.05%, resulting in 1.05% after the increase. But if it promises to increase the interest rate by 5%p (or 500 basis points, as Chris Haug notes), then it is an attractive deal; 5%p on top of, say, 1% original rate gives 6%.
Is 50% 100% higher than 25% or is it 25% higher than 25%?
There are percent (%) and there are percentage points (%p), which are two different things. 50% (of $X$) is 100% more than 25% (of $X$). At the same time, 50% (of $X$) is 25%p more than 25% (of $X$).
Is 50% 100% higher than 25% or is it 25% higher than 25%? There are percent (%) and there are percentage points (%p), which are two different things. 50% (of $X$) is 100% more than 25% (of $X$). At the same time, 50% (of $X$) is 25%p more than 25% (of $X$). So if your bank promises to increase the interest rates on your deposit by 5%, that means nearly nothing; 5% of, say, 1% original rate is just 0.05%, resulting in 1.05% after the increase. But if it promises to increase the interest rate by 5%p (or 500 basis points, as Chris Haug notes), then it is an attractive deal; 5%p on top of, say, 1% original rate gives 6%.
Is 50% 100% higher than 25% or is it 25% higher than 25%? There are percent (%) and there are percentage points (%p), which are two different things. 50% (of $X$) is 100% more than 25% (of $X$). At the same time, 50% (of $X$) is 25%p more than 25% (of $X$).
11,858
Is 50% 100% higher than 25% or is it 25% higher than 25%?
Both are correct, as long as the increase is described correctly. A common way of distinguishing the two cases is to say there is a 100% relative increase or a 25% absolute increase. However, this might not be clear to all audiences. Most laypeople probably expect the latter number, and quoting the multiplicative increase may be considered intentionally misleading.
Is 50% 100% higher than 25% or is it 25% higher than 25%?
Both are correct, as long as the increase is described correctly. A common way of distinguishing the two cases is to say there is a 100% relative increase or a 25% absolute increase. However, this mig
Is 50% 100% higher than 25% or is it 25% higher than 25%? Both are correct, as long as the increase is described correctly. A common way of distinguishing the two cases is to say there is a 100% relative increase or a 25% absolute increase. However, this might not be clear to all audiences. Most laypeople probably expect the latter number, and quoting the multiplicative increase may be considered intentionally misleading.
Is 50% 100% higher than 25% or is it 25% higher than 25%? Both are correct, as long as the increase is described correctly. A common way of distinguishing the two cases is to say there is a 100% relative increase or a 25% absolute increase. However, this mig
11,859
Is 50% 100% higher than 25% or is it 25% higher than 25%?
The expression "B is x % higher than A", implies that x is calculated as a percentage of A, because it is against A that B is being compared, not some unspecified third entity. If A=25% of C and B=50% of C, then B is 100% higher than A. It's also 2 times A. Confusingly, many people will say "B is 2 times more than A", which is completely illogical. For B to be 2 times more than A, it would be 2 * A + A, or 3 * A (in this case, 75% of C). However, "B is 25 percentage points higher than A, when both are compared to C". If the context of the percentage being calculated relative to C is omitted (and not strongly implied), the statement is meaningless, because a percentage is always a percentage of something. [If you doubt this, consider whether you'd rather have 50% of the money spent in a year on pork sausage in Jerusalem or 1% of the money spent in the same year on rice in China.]
Is 50% 100% higher than 25% or is it 25% higher than 25%?
The expression "B is x % higher than A", implies that x is calculated as a percentage of A, because it is against A that B is being compared, not some unspecified third entity. If A=25% of C and B=50%
Is 50% 100% higher than 25% or is it 25% higher than 25%? The expression "B is x % higher than A", implies that x is calculated as a percentage of A, because it is against A that B is being compared, not some unspecified third entity. If A=25% of C and B=50% of C, then B is 100% higher than A. It's also 2 times A. Confusingly, many people will say "B is 2 times more than A", which is completely illogical. For B to be 2 times more than A, it would be 2 * A + A, or 3 * A (in this case, 75% of C). However, "B is 25 percentage points higher than A, when both are compared to C". If the context of the percentage being calculated relative to C is omitted (and not strongly implied), the statement is meaningless, because a percentage is always a percentage of something. [If you doubt this, consider whether you'd rather have 50% of the money spent in a year on pork sausage in Jerusalem or 1% of the money spent in the same year on rice in China.]
Is 50% 100% higher than 25% or is it 25% higher than 25%? The expression "B is x % higher than A", implies that x is calculated as a percentage of A, because it is against A that B is being compared, not some unspecified third entity. If A=25% of C and B=50%
11,860
Is 50% 100% higher than 25% or is it 25% higher than 25%?
The only valid approach here is to assume your reader does not know which version you are using, and make sure you build up enough context to make it clear. One context may be to state what Richard Hardy suggested, differentiating between percentages and percentage points. That being said, I've never seen the %p notation before, so if you use that notation you might want to clarify it as well. Wikipedia suggests pp or p.p. as other possible notations. Another context might be nearby numbers. If I say "Inflation went up .2% this year," people reliably understand that that number must be an addition of 0.2% to the inflation rate percentage, as opposed to a claim that inflation has been scaled by 100.2%. This holds true even if I was imprecise in my use of percent vs. percentage points. On the other hand, if I say "murder rates were at 3% last year, but went up 30% this year," you can be quite confident that that was a scaling factor, unless you knew there was some major insurrection in the area. One of the easiest ways to maintain this context is to say the value in several different ways. If you say "unemployment went up 25%, to a record high of 18%," it's pretty darn clear that you intended to say unemployement rates were multiplied by 1.25. Incidentally, this is where the duplicated legal terms like "null and void" or "aiding and abetting" came from -- they were saying the same thing twice, once in common law speak and one in the official terminology which derived from French law. We have a similar issue with the nuanced difference between an absolute temperature measured in Fahrenheit and a differential temperature measured in Fahrenheit. The conversions are different because one has to account for the fact that the Fahrenheit scale does not start at absolute zero. Dozens of notations have been suggested to resolve this, but nothing is quite as effective as maintaining a clear context so that the reader understands what you meant. Communication is all about context, and different phrasing will mean different things to different people.
Is 50% 100% higher than 25% or is it 25% higher than 25%?
The only valid approach here is to assume your reader does not know which version you are using, and make sure you build up enough context to make it clear. One context may be to state what Richard Ha
Is 50% 100% higher than 25% or is it 25% higher than 25%? The only valid approach here is to assume your reader does not know which version you are using, and make sure you build up enough context to make it clear. One context may be to state what Richard Hardy suggested, differentiating between percentages and percentage points. That being said, I've never seen the %p notation before, so if you use that notation you might want to clarify it as well. Wikipedia suggests pp or p.p. as other possible notations. Another context might be nearby numbers. If I say "Inflation went up .2% this year," people reliably understand that that number must be an addition of 0.2% to the inflation rate percentage, as opposed to a claim that inflation has been scaled by 100.2%. This holds true even if I was imprecise in my use of percent vs. percentage points. On the other hand, if I say "murder rates were at 3% last year, but went up 30% this year," you can be quite confident that that was a scaling factor, unless you knew there was some major insurrection in the area. One of the easiest ways to maintain this context is to say the value in several different ways. If you say "unemployment went up 25%, to a record high of 18%," it's pretty darn clear that you intended to say unemployement rates were multiplied by 1.25. Incidentally, this is where the duplicated legal terms like "null and void" or "aiding and abetting" came from -- they were saying the same thing twice, once in common law speak and one in the official terminology which derived from French law. We have a similar issue with the nuanced difference between an absolute temperature measured in Fahrenheit and a differential temperature measured in Fahrenheit. The conversions are different because one has to account for the fact that the Fahrenheit scale does not start at absolute zero. Dozens of notations have been suggested to resolve this, but nothing is quite as effective as maintaining a clear context so that the reader understands what you meant. Communication is all about context, and different phrasing will mean different things to different people.
Is 50% 100% higher than 25% or is it 25% higher than 25%? The only valid approach here is to assume your reader does not know which version you are using, and make sure you build up enough context to make it clear. One context may be to state what Richard Ha
11,861
Using offset in binomial model to account for increased numbers of patients
If you are interested in the probability of an incident given N days of patients on ward then you want a model either like: mod1 <- glm(incident ~ 1, offset=patients.on.ward, family=binomial) the offset represents trials, incident is either 0 or 1, and the probability of an incident is constant (no heterogeneity in tendency to generate incidents) and patients do not interact to cause incidents (no contagion). Alternatively, if the chance of an incident is small, which it is for you (or you've thresholded the incident counts without mentioning it to us) then you might prefer the Poisson formulation log.patients.on.ward <- log(patients.on.ward) mod2 <- glm(incident ~ 1, offset=log.patients.on.ward, family=poisson) where the same assumptions apply. The offset is logged because the number of patients on ward has a proportional/multiplicative effect. Expanding on the second model, maybe you think there are more incidents than would be otherwise expected simply due to increased patient numbers. That is, perhaps patients do interact or are heterogenous. So you try mod3 <- glm(incident ~ 1 + log.patients.on.ward, family=poisson) If the coefficient on log.patients.on.ward is significantly different from 1, where it was fixed in mod2, then something may indeed be wrong with your assumptions of no heterogeneity and no contagion. And while you cannot of course distinguish these two (nor either one from other missing variables), you do now have an estimate of how much increasing the number of patients on ward increases the rate / probability of an incidents over and above what you'd expect from chance. In the space of parameters it's 1-coef(mod3)[2] with interval derivable from confint. Alternatively you can just work with the log quantity and its coefficient directly. If you just want to predict the probability of incident using the number of patients on ward, then this model would be a simple way to do it. The Questions Is it ok to have dependent variables in your offset? It sounds like a very bad idea to me, but I don't see that you have to. The offset in Poisson regression models for exposure is indeed log(exposure). Perhaps confusingly the use of offset in R's Binomial regression models is basically way to indicate the number of trials. It can always be replaced by a dependent variable defined as cbind(incidents, patients.on.ward-incidents) and no offset. Think of it like this: in the Poisson model it enters on the right hand side behind the log link function, and in the Binomial model it enters on the left hand side in front of the logit link function.
Using offset in binomial model to account for increased numbers of patients
If you are interested in the probability of an incident given N days of patients on ward then you want a model either like: mod1 <- glm(incident ~ 1, offset=patients.on.ward, family=binomial) the off
Using offset in binomial model to account for increased numbers of patients If you are interested in the probability of an incident given N days of patients on ward then you want a model either like: mod1 <- glm(incident ~ 1, offset=patients.on.ward, family=binomial) the offset represents trials, incident is either 0 or 1, and the probability of an incident is constant (no heterogeneity in tendency to generate incidents) and patients do not interact to cause incidents (no contagion). Alternatively, if the chance of an incident is small, which it is for you (or you've thresholded the incident counts without mentioning it to us) then you might prefer the Poisson formulation log.patients.on.ward <- log(patients.on.ward) mod2 <- glm(incident ~ 1, offset=log.patients.on.ward, family=poisson) where the same assumptions apply. The offset is logged because the number of patients on ward has a proportional/multiplicative effect. Expanding on the second model, maybe you think there are more incidents than would be otherwise expected simply due to increased patient numbers. That is, perhaps patients do interact or are heterogenous. So you try mod3 <- glm(incident ~ 1 + log.patients.on.ward, family=poisson) If the coefficient on log.patients.on.ward is significantly different from 1, where it was fixed in mod2, then something may indeed be wrong with your assumptions of no heterogeneity and no contagion. And while you cannot of course distinguish these two (nor either one from other missing variables), you do now have an estimate of how much increasing the number of patients on ward increases the rate / probability of an incidents over and above what you'd expect from chance. In the space of parameters it's 1-coef(mod3)[2] with interval derivable from confint. Alternatively you can just work with the log quantity and its coefficient directly. If you just want to predict the probability of incident using the number of patients on ward, then this model would be a simple way to do it. The Questions Is it ok to have dependent variables in your offset? It sounds like a very bad idea to me, but I don't see that you have to. The offset in Poisson regression models for exposure is indeed log(exposure). Perhaps confusingly the use of offset in R's Binomial regression models is basically way to indicate the number of trials. It can always be replaced by a dependent variable defined as cbind(incidents, patients.on.ward-incidents) and no offset. Think of it like this: in the Poisson model it enters on the right hand side behind the log link function, and in the Binomial model it enters on the left hand side in front of the logit link function.
Using offset in binomial model to account for increased numbers of patients If you are interested in the probability of an incident given N days of patients on ward then you want a model either like: mod1 <- glm(incident ~ 1, offset=patients.on.ward, family=binomial) the off
11,862
Using offset in binomial model to account for increased numbers of patients
Offsets in Poisson regressions Lets start by looking at why we use an offset in a Poisson regression. Often we want to due this to control for exposure. Let $\lambda$ be the baseline rate per unit of exposure and $t$ be the exposure time in the same units. The expected number of events will be $\lambda \times t$. In a GLM model we are modelling the expected value using a link function $g$, that is $$g(\lambda t_i) = \log(\lambda t_i) = \beta_0 + \beta_1x_{1,i} + \dots $$ where $t_i$ is the exposure duration for individual $i$ and $x_i$ is the covariate value for individual $i$. The ellipsis simply indicates additional regression terms we may want to add. We can simplify simplifying the above expression $$\log(\lambda) = \log(t_i) + \beta_0 +\beta_1x_{1,i} + \dots$$ The $\log(t_i)$ is simply an "offset" added to the Poisson regression as it is not a product of any of the model parameters which we will be estimating. Binomial Regression In a binomial regression, which typically use a logit link, that is: $$g(p_i) = \textrm{logit}(p_i) = log\left(\frac{p_i}{1-p_i}\right) = \beta_0 +\beta_1x_{1,i}+\dots $$ You can see it will be difficult to derive a model for $p_i$ that will produce a constant offset. For example, if $p_i$ is the probability that one any patient on day $i$ has an incident. It will be a function of the the individual patients available on that day. As jboman stated it is easier to derive the compliment of no incidence, rather than directly determine probability for at least one incident. Let $p_{i,j}^*$ be the probability of a patient $j$ having an incident on day $i$. The probability of no patients having an incident on day $i$ will be $\prod_{j=1}^{N_i}(1-p^*_{i,j})$, where $N_i$ is the number of patients on day $i$. By the compliment, the probability of at least one patient having an incident will be, $$p_i = 1-\prod_{j=1}^{N_i}(1-p^*_{i,j}).$$ If we are willing to assume the probability of any patient having an incident on any day is the same we can simplify this to $$p_i = 1-(q^*)^{N_i},$$ where $q^*= 1-p^*$ and $p^*$ is the shared incidence probability. If we substitute this new definition of $p_i$ back into our logit link function $g(p_i)$, the best we can do in terms of simplification and rearranging is $\log\left((q^*)^{-N} -1 \right)$. This still does not leave us with a constant term that can be factored out. As a result we cannot use an offset in this case. The best you can do is discretize the problem (as suggested by jboman) you can create bins for the number of patients and estimate a separate value for $p$ for each of these bins. Otherwise you will need to derive a more complicated model.
Using offset in binomial model to account for increased numbers of patients
Offsets in Poisson regressions Lets start by looking at why we use an offset in a Poisson regression. Often we want to due this to control for exposure. Let $\lambda$ be the baseline rate per unit o
Using offset in binomial model to account for increased numbers of patients Offsets in Poisson regressions Lets start by looking at why we use an offset in a Poisson regression. Often we want to due this to control for exposure. Let $\lambda$ be the baseline rate per unit of exposure and $t$ be the exposure time in the same units. The expected number of events will be $\lambda \times t$. In a GLM model we are modelling the expected value using a link function $g$, that is $$g(\lambda t_i) = \log(\lambda t_i) = \beta_0 + \beta_1x_{1,i} + \dots $$ where $t_i$ is the exposure duration for individual $i$ and $x_i$ is the covariate value for individual $i$. The ellipsis simply indicates additional regression terms we may want to add. We can simplify simplifying the above expression $$\log(\lambda) = \log(t_i) + \beta_0 +\beta_1x_{1,i} + \dots$$ The $\log(t_i)$ is simply an "offset" added to the Poisson regression as it is not a product of any of the model parameters which we will be estimating. Binomial Regression In a binomial regression, which typically use a logit link, that is: $$g(p_i) = \textrm{logit}(p_i) = log\left(\frac{p_i}{1-p_i}\right) = \beta_0 +\beta_1x_{1,i}+\dots $$ You can see it will be difficult to derive a model for $p_i$ that will produce a constant offset. For example, if $p_i$ is the probability that one any patient on day $i$ has an incident. It will be a function of the the individual patients available on that day. As jboman stated it is easier to derive the compliment of no incidence, rather than directly determine probability for at least one incident. Let $p_{i,j}^*$ be the probability of a patient $j$ having an incident on day $i$. The probability of no patients having an incident on day $i$ will be $\prod_{j=1}^{N_i}(1-p^*_{i,j})$, where $N_i$ is the number of patients on day $i$. By the compliment, the probability of at least one patient having an incident will be, $$p_i = 1-\prod_{j=1}^{N_i}(1-p^*_{i,j}).$$ If we are willing to assume the probability of any patient having an incident on any day is the same we can simplify this to $$p_i = 1-(q^*)^{N_i},$$ where $q^*= 1-p^*$ and $p^*$ is the shared incidence probability. If we substitute this new definition of $p_i$ back into our logit link function $g(p_i)$, the best we can do in terms of simplification and rearranging is $\log\left((q^*)^{-N} -1 \right)$. This still does not leave us with a constant term that can be factored out. As a result we cannot use an offset in this case. The best you can do is discretize the problem (as suggested by jboman) you can create bins for the number of patients and estimate a separate value for $p$ for each of these bins. Otherwise you will need to derive a more complicated model.
Using offset in binomial model to account for increased numbers of patients Offsets in Poisson regressions Lets start by looking at why we use an offset in a Poisson regression. Often we want to due this to control for exposure. Let $\lambda$ be the baseline rate per unit o
11,863
Using offset in binomial model to account for increased numbers of patients
This answer comes in two parts, the first a direct answer to the question and the second a commentary on the model you're proposing. The first part relates to the use of Numbers as an offset along with having it on the r.h.s. of the equation. The effect of doing this will simply be to subtract 1 from the estimated coefficient of Numbers, thereby reversing out the effect of the offset, and will not otherwise change the results. The following example, with a few lines of irrelevant output removed, demonstrates this: library(MASS) Numbers <- rpois(100,12) p <- 1 / (1 + exp(0.25*Numbers)) y <- rbinom(100, Numbers, p) Incident <- pmin(y, 1) > summary(glm(Incident~Numbers, family="binomial")) Deviance Residuals: Min 1Q Median 3Q Max -1.3121 -1.0246 -0.8731 1.2512 1.7465 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 0.99299 0.80624 1.232 0.2181 Numbers -0.11364 0.06585 -1.726 0.0844 . <= COEFFICIENT WITH NO OFFSET TERM --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for binomial family taken to be 1) Null deviance: 135.37 on 99 degrees of freedom Residual deviance: 132.24 on 98 degrees of freedom AIC: 136.24 > summary(glm(Incident~Numbers, offset=Numbers, family="binomial")) Deviance Residuals: Min 1Q Median 3Q Max -1.3121 -1.0246 -0.8731 1.2512 1.7465 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 0.99299 0.80624 1.232 0.218 Numbers -1.11364 0.06585 -16.911 <2e-16 *** <= COEFFICIENT WITH OFFSET TERM --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for binomial family taken to be 1) Null deviance: 342.48 on 99 degrees of freedom Residual deviance: 132.24 on 98 degrees of freedom AIC: 136.24 Note how everything is the same except the coefficient of Numbers and the null deviance (and the t-statistic, because it's still testing against 0 instead of -1.) The second part relates to the model you are building. Since the incidents are recorded not as the number of incidents in a day but whether there were any incidents in a day, the probability of observing a 1 on day $t$ is $1-(1-p_t)^{N_t}$, where $N_t$ is the number of patients on day $t$ and $p_t$ is the per-patient probability of an incident on day $t$. The usual link function, the logit, would parameterize this as $\log(1-(1-p_t)^{N_t})/N_t\log(1-p_t)$. This indicates that the relationship between the probability of observing a 1 on day $t$ and $N_t$ may not be well-modeled by a linear function on the logit scale. (This may be the case anyway, as one might expect some rough "threshold" below which the quality of patient care is OK but above which the quality of patient care drops rapidly.) Reversing the definition of the probabilities so as to move the $N_t$ in the denominator instead of the numerator still leaves you with that awkward exponential inside the log. One might also suspect that the per-patient probability varies from patient to patient, which would lead to a more complex, hierarchical model, but I won't go into that here. In any case, given this and the limited range of the number of patients you observe, rather than use a model that is linear on the logit scale, it might be better to be nonparametric about the relationship and group the number of patients into three or four groups, for example, 10-11, 12-13, 14-15, and 16-17, construct dummy variables for those groups, then run the logistic regression with the dummy variables on the right hand side. This will better enable the capture of nonlinear relationships such as "the system is overloaded around 16 patients and incidents start to ramp up significantly." If you had a much wider range of patients, I'd suggest a generalized additive model, e.g., 'gam' from the 'mgcv' package.
Using offset in binomial model to account for increased numbers of patients
This answer comes in two parts, the first a direct answer to the question and the second a commentary on the model you're proposing. The first part relates to the use of Numbers as an offset along w
Using offset in binomial model to account for increased numbers of patients This answer comes in two parts, the first a direct answer to the question and the second a commentary on the model you're proposing. The first part relates to the use of Numbers as an offset along with having it on the r.h.s. of the equation. The effect of doing this will simply be to subtract 1 from the estimated coefficient of Numbers, thereby reversing out the effect of the offset, and will not otherwise change the results. The following example, with a few lines of irrelevant output removed, demonstrates this: library(MASS) Numbers <- rpois(100,12) p <- 1 / (1 + exp(0.25*Numbers)) y <- rbinom(100, Numbers, p) Incident <- pmin(y, 1) > summary(glm(Incident~Numbers, family="binomial")) Deviance Residuals: Min 1Q Median 3Q Max -1.3121 -1.0246 -0.8731 1.2512 1.7465 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 0.99299 0.80624 1.232 0.2181 Numbers -0.11364 0.06585 -1.726 0.0844 . <= COEFFICIENT WITH NO OFFSET TERM --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for binomial family taken to be 1) Null deviance: 135.37 on 99 degrees of freedom Residual deviance: 132.24 on 98 degrees of freedom AIC: 136.24 > summary(glm(Incident~Numbers, offset=Numbers, family="binomial")) Deviance Residuals: Min 1Q Median 3Q Max -1.3121 -1.0246 -0.8731 1.2512 1.7465 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 0.99299 0.80624 1.232 0.218 Numbers -1.11364 0.06585 -16.911 <2e-16 *** <= COEFFICIENT WITH OFFSET TERM --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for binomial family taken to be 1) Null deviance: 342.48 on 99 degrees of freedom Residual deviance: 132.24 on 98 degrees of freedom AIC: 136.24 Note how everything is the same except the coefficient of Numbers and the null deviance (and the t-statistic, because it's still testing against 0 instead of -1.) The second part relates to the model you are building. Since the incidents are recorded not as the number of incidents in a day but whether there were any incidents in a day, the probability of observing a 1 on day $t$ is $1-(1-p_t)^{N_t}$, where $N_t$ is the number of patients on day $t$ and $p_t$ is the per-patient probability of an incident on day $t$. The usual link function, the logit, would parameterize this as $\log(1-(1-p_t)^{N_t})/N_t\log(1-p_t)$. This indicates that the relationship between the probability of observing a 1 on day $t$ and $N_t$ may not be well-modeled by a linear function on the logit scale. (This may be the case anyway, as one might expect some rough "threshold" below which the quality of patient care is OK but above which the quality of patient care drops rapidly.) Reversing the definition of the probabilities so as to move the $N_t$ in the denominator instead of the numerator still leaves you with that awkward exponential inside the log. One might also suspect that the per-patient probability varies from patient to patient, which would lead to a more complex, hierarchical model, but I won't go into that here. In any case, given this and the limited range of the number of patients you observe, rather than use a model that is linear on the logit scale, it might be better to be nonparametric about the relationship and group the number of patients into three or four groups, for example, 10-11, 12-13, 14-15, and 16-17, construct dummy variables for those groups, then run the logistic regression with the dummy variables on the right hand side. This will better enable the capture of nonlinear relationships such as "the system is overloaded around 16 patients and incidents start to ramp up significantly." If you had a much wider range of patients, I'd suggest a generalized additive model, e.g., 'gam' from the 'mgcv' package.
Using offset in binomial model to account for increased numbers of patients This answer comes in two parts, the first a direct answer to the question and the second a commentary on the model you're proposing. The first part relates to the use of Numbers as an offset along w
11,864
Using offset in binomial model to account for increased numbers of patients
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. Seems simplest to specify a log-link and keep the offset as for a Poisson model.
Using offset in binomial model to account for increased numbers of patients
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Using offset in binomial model to account for increased numbers of patients Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. Seems simplest to specify a log-link and keep the offset as for a Poisson model.
Using offset in binomial model to account for increased numbers of patients Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
11,865
R's randomForest can not handle more than 32 levels. What is workaround?
It is actually a pretty reasonable constrain because a split on a factor with $N$ levels is actually a selection of one of the $2^N-2$ possible combinations. So even with $N$ like 25 the space of combinations is so huge that such inference makes minor sense. Most other implementations simply treat factor as an ordinal one (i.e. integers from 1 to $N$), and this is one option how you can solve this problem. Actually RF is often wise enough to slice this into arbitrary groups with several splits. The other option is to change representation -- maybe your outcome does not directly depend on state entity but, for instance, area, population, number of pine trees per capita or other attribute(s) you can plug into your information system instead. It may be also that each state is such an isolated and uncorrelated entity that it requires a separate model for itself. Clustering based on a decision is probably a bad idea because this way you are smuggling information from the decision into attributes, which often ends in overfitting.
R's randomForest can not handle more than 32 levels. What is workaround?
It is actually a pretty reasonable constrain because a split on a factor with $N$ levels is actually a selection of one of the $2^N-2$ possible combinations. So even with $N$ like 25 the space of comb
R's randomForest can not handle more than 32 levels. What is workaround? It is actually a pretty reasonable constrain because a split on a factor with $N$ levels is actually a selection of one of the $2^N-2$ possible combinations. So even with $N$ like 25 the space of combinations is so huge that such inference makes minor sense. Most other implementations simply treat factor as an ordinal one (i.e. integers from 1 to $N$), and this is one option how you can solve this problem. Actually RF is often wise enough to slice this into arbitrary groups with several splits. The other option is to change representation -- maybe your outcome does not directly depend on state entity but, for instance, area, population, number of pine trees per capita or other attribute(s) you can plug into your information system instead. It may be also that each state is such an isolated and uncorrelated entity that it requires a separate model for itself. Clustering based on a decision is probably a bad idea because this way you are smuggling information from the decision into attributes, which often ends in overfitting.
R's randomForest can not handle more than 32 levels. What is workaround? It is actually a pretty reasonable constrain because a split on a factor with $N$ levels is actually a selection of one of the $2^N-2$ possible combinations. So even with $N$ like 25 the space of comb
11,866
R's randomForest can not handle more than 32 levels. What is workaround?
The main reason is how randomForest is implemented. Implementation from R follows a lot from the original Breiman's specifications. What is important here to note is that for factor/categorical variables, the split criteria is binary with some label values on the left and the rest label values on the right. That means it searches for all combinations of grouping label values in two groups. If you denote with $0$ the left group and with $1$ the right group and you enumerate for each label one digit, you will get a number in range $[0;2^M-1]$ combinations, which is prohibitive from a computational point of view. Why the implementations from Weka and Python works? The weka implementation does not use CART trees by default. It uses C45 trees which does not have this computational problem, since for categorical inputs it splits in multiple node, one for each level value. The python random forest implementation can't use categorical/factor variables. You have to encode those variables into dummy or numerical variables. Another implementations might allow multiple levels (including weka here) because even if they use CART, they does not necessarily implements twoing. Which means they allow finding best split for a factor variable only by grouping one label against all the other values. This is requires by far less computation since it needs to check only $M$ split points.
R's randomForest can not handle more than 32 levels. What is workaround?
The main reason is how randomForest is implemented. Implementation from R follows a lot from the original Breiman's specifications. What is important here to note is that for factor/categorical variab
R's randomForest can not handle more than 32 levels. What is workaround? The main reason is how randomForest is implemented. Implementation from R follows a lot from the original Breiman's specifications. What is important here to note is that for factor/categorical variables, the split criteria is binary with some label values on the left and the rest label values on the right. That means it searches for all combinations of grouping label values in two groups. If you denote with $0$ the left group and with $1$ the right group and you enumerate for each label one digit, you will get a number in range $[0;2^M-1]$ combinations, which is prohibitive from a computational point of view. Why the implementations from Weka and Python works? The weka implementation does not use CART trees by default. It uses C45 trees which does not have this computational problem, since for categorical inputs it splits in multiple node, one for each level value. The python random forest implementation can't use categorical/factor variables. You have to encode those variables into dummy or numerical variables. Another implementations might allow multiple levels (including weka here) because even if they use CART, they does not necessarily implements twoing. Which means they allow finding best split for a factor variable only by grouping one label against all the other values. This is requires by far less computation since it needs to check only $M$ split points.
R's randomForest can not handle more than 32 levels. What is workaround? The main reason is how randomForest is implemented. Implementation from R follows a lot from the original Breiman's specifications. What is important here to note is that for factor/categorical variab
11,867
R's randomForest can not handle more than 32 levels. What is workaround?
You might try representing that one column differently. You could represent the same data as a sparse dataframe. Minimum viable code; example <- as.data.frame(c("A", "A", "B", "F", "C", "G", "C", "D", "E", "F")) names(example) <- "strcol" for(level in unique(example$strcol)){ example[paste("dummy", level, sep = "_")] <- ifelse(example$strcol == level, 1, 0) } Notice how each value in the original column now becomes a separate dummy column. More extensive example code; set.seed(0) combs1 = sample.int(33, size= 10000, replace=TRUE) combs2 = sample.int(33, size= 10000, replace=TRUE) combs3 = combs1 * combs2 + rnorm(10000,mean=0,100) df_hard = data.frame(y=combs3, first=factor(combs1), second=factor(combs2)) for(level in unique(df_hard$first)){ df_hard[paste("first", level, sep = "_")] <- ifelse(df_hard$first == level, 1, 0) } for(level in unique(df_hard$second)){ df_hard[paste("second", level, sep = "_")] <- ifelse(df_hard$second == level, 1, 0) } example$first <- NULL example$second <- NULL rf_mod = randomForest( y ~ ., data=example ) Even though this piece of code shows that you indeed will no longer get the error, you will notice that the randomForest algorithm now needs a long time before it finishes. This is due to a CPU constraint, you could map reduce this task via sampling now as well. For more information please check out this blogpost: https://blog.cloudera.com/blog/2013/02/how-to-resample-from-a-large-data-set-in-parallel-with-r-on-hadoop/
R's randomForest can not handle more than 32 levels. What is workaround?
You might try representing that one column differently. You could represent the same data as a sparse dataframe. Minimum viable code; example <- as.data.frame(c("A", "A", "B", "F", "C", "G", "C", "D
R's randomForest can not handle more than 32 levels. What is workaround? You might try representing that one column differently. You could represent the same data as a sparse dataframe. Minimum viable code; example <- as.data.frame(c("A", "A", "B", "F", "C", "G", "C", "D", "E", "F")) names(example) <- "strcol" for(level in unique(example$strcol)){ example[paste("dummy", level, sep = "_")] <- ifelse(example$strcol == level, 1, 0) } Notice how each value in the original column now becomes a separate dummy column. More extensive example code; set.seed(0) combs1 = sample.int(33, size= 10000, replace=TRUE) combs2 = sample.int(33, size= 10000, replace=TRUE) combs3 = combs1 * combs2 + rnorm(10000,mean=0,100) df_hard = data.frame(y=combs3, first=factor(combs1), second=factor(combs2)) for(level in unique(df_hard$first)){ df_hard[paste("first", level, sep = "_")] <- ifelse(df_hard$first == level, 1, 0) } for(level in unique(df_hard$second)){ df_hard[paste("second", level, sep = "_")] <- ifelse(df_hard$second == level, 1, 0) } example$first <- NULL example$second <- NULL rf_mod = randomForest( y ~ ., data=example ) Even though this piece of code shows that you indeed will no longer get the error, you will notice that the randomForest algorithm now needs a long time before it finishes. This is due to a CPU constraint, you could map reduce this task via sampling now as well. For more information please check out this blogpost: https://blog.cloudera.com/blog/2013/02/how-to-resample-from-a-large-data-set-in-parallel-with-r-on-hadoop/
R's randomForest can not handle more than 32 levels. What is workaround? You might try representing that one column differently. You could represent the same data as a sparse dataframe. Minimum viable code; example <- as.data.frame(c("A", "A", "B", "F", "C", "G", "C", "D
11,868
R's randomForest can not handle more than 32 levels. What is workaround?
Another option: depending on the number of levels and number of observations in your data, you could merge some levels. Beyond getting under the limit, it may reduce variance if you have many levels with just a few observations. Hadley's forcats:fct_lump does this.
R's randomForest can not handle more than 32 levels. What is workaround?
Another option: depending on the number of levels and number of observations in your data, you could merge some levels. Beyond getting under the limit, it may reduce variance if you have many levels w
R's randomForest can not handle more than 32 levels. What is workaround? Another option: depending on the number of levels and number of observations in your data, you could merge some levels. Beyond getting under the limit, it may reduce variance if you have many levels with just a few observations. Hadley's forcats:fct_lump does this.
R's randomForest can not handle more than 32 levels. What is workaround? Another option: depending on the number of levels and number of observations in your data, you could merge some levels. Beyond getting under the limit, it may reduce variance if you have many levels w
11,869
R's randomForest can not handle more than 32 levels. What is workaround?
You may use package extraTrees instead. Extremely randomized forests algorithm do not try any breakpoint/split, but only a limited random subset of splits.
R's randomForest can not handle more than 32 levels. What is workaround?
You may use package extraTrees instead. Extremely randomized forests algorithm do not try any breakpoint/split, but only a limited random subset of splits.
R's randomForest can not handle more than 32 levels. What is workaround? You may use package extraTrees instead. Extremely randomized forests algorithm do not try any breakpoint/split, but only a limited random subset of splits.
R's randomForest can not handle more than 32 levels. What is workaround? You may use package extraTrees instead. Extremely randomized forests algorithm do not try any breakpoint/split, but only a limited random subset of splits.
11,870
What are some alternatives to a boxplot?
A boxplot isn't that complicated. After all, you just need to compute the three quartiles, and the min and max which define the range; a subtlety arises when we want to draw the whiskers and various methods have been proposed. For instance, in a Tukey boxplot values outside 1.5 times the inter-quartile from the first or third quartile would be considered as outliers and displayed as simple points. See also Methods for Presenting Statistical Information: The Box Plot for a good overview, by Kristin Potter. The R software implements a slightly different rule but the source code is available if you want to study it (see the boxplot() and boxplot.stats() functions). However, it is not very useful when the interest is in identifying outliers from a very skewed distribution (but see, An adjusted boxplot for skewed distributions, by Hubert and Vandervieren, CSDA 2008 52(12)). As far as online visualization is concerned, I would suggest taking a look at Protovis which is a plugin-free js toolbox for interactive web displays. The examples page has very illustrations of what can be achieved with it, in very few lines.
What are some alternatives to a boxplot?
A boxplot isn't that complicated. After all, you just need to compute the three quartiles, and the min and max which define the range; a subtlety arises when we want to draw the whiskers and various m
What are some alternatives to a boxplot? A boxplot isn't that complicated. After all, you just need to compute the three quartiles, and the min and max which define the range; a subtlety arises when we want to draw the whiskers and various methods have been proposed. For instance, in a Tukey boxplot values outside 1.5 times the inter-quartile from the first or third quartile would be considered as outliers and displayed as simple points. See also Methods for Presenting Statistical Information: The Box Plot for a good overview, by Kristin Potter. The R software implements a slightly different rule but the source code is available if you want to study it (see the boxplot() and boxplot.stats() functions). However, it is not very useful when the interest is in identifying outliers from a very skewed distribution (but see, An adjusted boxplot for skewed distributions, by Hubert and Vandervieren, CSDA 2008 52(12)). As far as online visualization is concerned, I would suggest taking a look at Protovis which is a plugin-free js toolbox for interactive web displays. The examples page has very illustrations of what can be achieved with it, in very few lines.
What are some alternatives to a boxplot? A boxplot isn't that complicated. After all, you just need to compute the three quartiles, and the min and max which define the range; a subtlety arises when we want to draw the whiskers and various m
11,871
What are some alternatives to a boxplot?
You might also want to have a look at beanplots. [Source] Implemented in R package by Peter Kampstra.
What are some alternatives to a boxplot?
You might also want to have a look at beanplots. [Source] Implemented in R package by Peter Kampstra.
What are some alternatives to a boxplot? You might also want to have a look at beanplots. [Source] Implemented in R package by Peter Kampstra.
What are some alternatives to a boxplot? You might also want to have a look at beanplots. [Source] Implemented in R package by Peter Kampstra.
11,872
What are some alternatives to a boxplot?
I'd suggest you persevere with histograms. They're much more widely understood than the alternatives. Use a log scale to cope with the large range of values. Here's an example I cooked up in a couple of minutes in Stata: I admit that the x-axis numerical labels weren't entirely straightforward or automatic, but as you're building a website I'm sure your programming skills are up to the challenge!
What are some alternatives to a boxplot?
I'd suggest you persevere with histograms. They're much more widely understood than the alternatives. Use a log scale to cope with the large range of values. Here's an example I cooked up in a couple
What are some alternatives to a boxplot? I'd suggest you persevere with histograms. They're much more widely understood than the alternatives. Use a log scale to cope with the large range of values. Here's an example I cooked up in a couple of minutes in Stata: I admit that the x-axis numerical labels weren't entirely straightforward or automatic, but as you're building a website I'm sure your programming skills are up to the challenge!
What are some alternatives to a boxplot? I'd suggest you persevere with histograms. They're much more widely understood than the alternatives. Use a log scale to cope with the large range of values. Here's an example I cooked up in a couple
11,873
What are some alternatives to a boxplot?
I rather like violin plots myself, as this gives an idea of the shape of the distribution. However if the large range of values is the issue, then maybe it would be best to plot the log of the data rather than the raw values, that would then make choosing the box sizes for histograms etc. As the display is for laymen, don't mention logs and mark the axis 10, 100, 1000, 10000, 100000, 1000000 etc.
What are some alternatives to a boxplot?
I rather like violin plots myself, as this gives an idea of the shape of the distribution. However if the large range of values is the issue, then maybe it would be best to plot the log of the data r
What are some alternatives to a boxplot? I rather like violin plots myself, as this gives an idea of the shape of the distribution. However if the large range of values is the issue, then maybe it would be best to plot the log of the data rather than the raw values, that would then make choosing the box sizes for histograms etc. As the display is for laymen, don't mention logs and mark the axis 10, 100, 1000, 10000, 100000, 1000000 etc.
What are some alternatives to a boxplot? I rather like violin plots myself, as this gives an idea of the shape of the distribution. However if the large range of values is the issue, then maybe it would be best to plot the log of the data r
11,874
What are some alternatives to a boxplot?
Here is a matlab function for plotting multiple histograms side-by-side in 2D as an alternative to box-plot. See the picture on the top. And here is another one The density strip is another alternative to box-plot. It is a shaded monochrome strip whose darkness at a point is proportional to the probability density of the quantity at that point. This is an R implementation of the density strip
What are some alternatives to a boxplot?
Here is a matlab function for plotting multiple histograms side-by-side in 2D as an alternative to box-plot. See the picture on the top. And here is another one The density strip is another alternativ
What are some alternatives to a boxplot? Here is a matlab function for plotting multiple histograms side-by-side in 2D as an alternative to box-plot. See the picture on the top. And here is another one The density strip is another alternative to box-plot. It is a shaded monochrome strip whose darkness at a point is proportional to the probability density of the quantity at that point. This is an R implementation of the density strip
What are some alternatives to a boxplot? Here is a matlab function for plotting multiple histograms side-by-side in 2D as an alternative to box-plot. See the picture on the top. And here is another one The density strip is another alternativ
11,875
What are some alternatives to a boxplot?
How about using quantiles? It is not necessary to present a graph then, only a table. For village census I think the users will be most interested how many there are villages of certain size, so giving for example deciles will tell them them information such as $x\%$ of all the villages are smaller than the certain number. For deciles $x=0,10,20,...,100$. You can graph this table with the percents on a x-axis and the deciles on the y-axis.
What are some alternatives to a boxplot?
How about using quantiles? It is not necessary to present a graph then, only a table. For village census I think the users will be most interested how many there are villages of certain size, so givin
What are some alternatives to a boxplot? How about using quantiles? It is not necessary to present a graph then, only a table. For village census I think the users will be most interested how many there are villages of certain size, so giving for example deciles will tell them them information such as $x\%$ of all the villages are smaller than the certain number. For deciles $x=0,10,20,...,100$. You can graph this table with the percents on a x-axis and the deciles on the y-axis.
What are some alternatives to a boxplot? How about using quantiles? It is not necessary to present a graph then, only a table. For village census I think the users will be most interested how many there are villages of certain size, so givin
11,876
What are some alternatives to a boxplot?
If you are targeting the general population (i.e. a non statistical-savvy audience) you should focus on eye-candy rather than statistical accuracy. Forget about boxplots, let alone violin plots (I personally find them very difficult to read)! If you'd ask the average street man what a quantile is, you would mostly get some wide eyed silence... You should use barplots, bubble charts, maybe some pie charts (brrrr). Forget about error bars (although I would put SD in text somewhere where applicable). Use colors, shapes, thick lines, 3D. You should make each chart unique and immediately easy to understand, even without having to read all the legends/axes etc. Make a smart use of maps by coloring them. Information is beautiful is a very good resource to get ideas. Look at this chart for instance: Caffeine and Calories: anyone can understand it, and it's pleasing to the eye. And, of course, have a look at Edward Tufte's work.
What are some alternatives to a boxplot?
If you are targeting the general population (i.e. a non statistical-savvy audience) you should focus on eye-candy rather than statistical accuracy. Forget about boxplots, let alone violin plots (I per
What are some alternatives to a boxplot? If you are targeting the general population (i.e. a non statistical-savvy audience) you should focus on eye-candy rather than statistical accuracy. Forget about boxplots, let alone violin plots (I personally find them very difficult to read)! If you'd ask the average street man what a quantile is, you would mostly get some wide eyed silence... You should use barplots, bubble charts, maybe some pie charts (brrrr). Forget about error bars (although I would put SD in text somewhere where applicable). Use colors, shapes, thick lines, 3D. You should make each chart unique and immediately easy to understand, even without having to read all the legends/axes etc. Make a smart use of maps by coloring them. Information is beautiful is a very good resource to get ideas. Look at this chart for instance: Caffeine and Calories: anyone can understand it, and it's pleasing to the eye. And, of course, have a look at Edward Tufte's work.
What are some alternatives to a boxplot? If you are targeting the general population (i.e. a non statistical-savvy audience) you should focus on eye-candy rather than statistical accuracy. Forget about boxplots, let alone violin plots (I per
11,877
Average value paradox - What is this called?
The average of every subcategory can be above the overall average if the subcategories overlap on the larger customers. Simple example to gain intuition: Let $A$ be an indicator whether an individual purchased an item in category A. Let $B$ be an indicator whether an individual purchased an item in category B. Let $X = A + B$ be the number of items purchased. \begin{array}{ccc} \text{Person} & A & B \\ i & 1 & 0 \\ ii & 0 & 1 \\ iii & 1 & 1 \end{array} The set of individuals where $A$ is true overlaps the set of individuals where $B$ is true. They are NOT disjoint sets. Then $\operatorname{E}[X] \approx 1.33$ while $\operatorname{E}[X \mid A] = 1.5$ and $\operatorname{E}[X \mid B] = 1.5$ The statement that would be true is: $$ P(A)\operatorname{E}[X\mid A] + P(B)\operatorname{E}[X\mid B] - P(AB)\operatorname{E}[X\mid AB] = \operatorname{E}[X]$$ $$ \frac{2}{3}1.5 + \frac{2}{3}1.5 - \frac{1}{3}2 = 1.3333$$ You can't simply compute $P(A)\operatorname{E}[X\mid A] + P(B)\operatorname{E}[X\mid B] $ because sets $A$ and $B$ overlap, the expression double counts the person who purchases both item $A$ and $B$! Name for illusion/paradox? I'd argue it's related to the majority illusion paradox in social networks. You may have a single dude who networks/friends everyone. That person may be one out of a million overall, but he'll be one of each persons's $k$ friends. Similarly, you have 1 out of 3 here purchasing both categories A and B. But within either category A or B, 1 out of the 2 purchasers is the super purchaser. Extreme case: Let's create $n$ sets of lotto tickets. Every set $S_i$ includes two tickets: a losing ticket $i$ and the jackpot winning ticket. The average winnings in every set $S_i$ is then $\frac{J}{2}$ where $J$ is the jackpot. The average of each category is WAY above the average winnings per ticket overall $\frac{J}{n+1}$. It's the same conceptual dynamic as the sales case. Every set $S_i$ includes the jackpot ticket in the same way that every category A, B, or C includes the heavy purchasers. My bottom line point would be that intuition based upon disjoint sets, a full partition of the sample space does not carry over to a series of overlapping sets. If you condition on overlapping categories, every category can be above average. If you partition the sample space and condition on disjoint sets, then categories have to average out to the overall mean, but that's not true for overlapping sets.
Average value paradox - What is this called?
The average of every subcategory can be above the overall average if the subcategories overlap on the larger customers. Simple example to gain intuition: Let $A$ be an indicator whether an individual
Average value paradox - What is this called? The average of every subcategory can be above the overall average if the subcategories overlap on the larger customers. Simple example to gain intuition: Let $A$ be an indicator whether an individual purchased an item in category A. Let $B$ be an indicator whether an individual purchased an item in category B. Let $X = A + B$ be the number of items purchased. \begin{array}{ccc} \text{Person} & A & B \\ i & 1 & 0 \\ ii & 0 & 1 \\ iii & 1 & 1 \end{array} The set of individuals where $A$ is true overlaps the set of individuals where $B$ is true. They are NOT disjoint sets. Then $\operatorname{E}[X] \approx 1.33$ while $\operatorname{E}[X \mid A] = 1.5$ and $\operatorname{E}[X \mid B] = 1.5$ The statement that would be true is: $$ P(A)\operatorname{E}[X\mid A] + P(B)\operatorname{E}[X\mid B] - P(AB)\operatorname{E}[X\mid AB] = \operatorname{E}[X]$$ $$ \frac{2}{3}1.5 + \frac{2}{3}1.5 - \frac{1}{3}2 = 1.3333$$ You can't simply compute $P(A)\operatorname{E}[X\mid A] + P(B)\operatorname{E}[X\mid B] $ because sets $A$ and $B$ overlap, the expression double counts the person who purchases both item $A$ and $B$! Name for illusion/paradox? I'd argue it's related to the majority illusion paradox in social networks. You may have a single dude who networks/friends everyone. That person may be one out of a million overall, but he'll be one of each persons's $k$ friends. Similarly, you have 1 out of 3 here purchasing both categories A and B. But within either category A or B, 1 out of the 2 purchasers is the super purchaser. Extreme case: Let's create $n$ sets of lotto tickets. Every set $S_i$ includes two tickets: a losing ticket $i$ and the jackpot winning ticket. The average winnings in every set $S_i$ is then $\frac{J}{2}$ where $J$ is the jackpot. The average of each category is WAY above the average winnings per ticket overall $\frac{J}{n+1}$. It's the same conceptual dynamic as the sales case. Every set $S_i$ includes the jackpot ticket in the same way that every category A, B, or C includes the heavy purchasers. My bottom line point would be that intuition based upon disjoint sets, a full partition of the sample space does not carry over to a series of overlapping sets. If you condition on overlapping categories, every category can be above average. If you partition the sample space and condition on disjoint sets, then categories have to average out to the overall mean, but that's not true for overlapping sets.
Average value paradox - What is this called? The average of every subcategory can be above the overall average if the subcategories overlap on the larger customers. Simple example to gain intuition: Let $A$ be an indicator whether an individual
11,878
Average value paradox - What is this called?
I would call this the family size paradox or something similar Suppose, for a simple example, everybody had one partner and a Poisson-distributed number of children with parameter $2$: The average number of children per person would be $2$ The average number of children per person with children would be $\frac{2}{1-e^{-2}} \approx 2.313$ The average sibling group size for each individual (counting their brothers and sisters and themselves) would be $3$ Real demographic and survey numbers produce different numbers but similar patterns The apparent paradox is that the average size of individuals' sibling groups is larger than the average number of children per family; with stable population dynamics, people tend to have fewer children on average than their parents did The explanation is whether the average is being taken over parents and families or over siblings: there are different weightings being applied to large families. In your example there is a difference between weighting by individuals or by purchases; your conditional averages are pushed up by fact you condition on a particular purchase being made.
Average value paradox - What is this called?
I would call this the family size paradox or something similar Suppose, for a simple example, everybody had one partner and a Poisson-distributed number of children with parameter $2$: The average n
Average value paradox - What is this called? I would call this the family size paradox or something similar Suppose, for a simple example, everybody had one partner and a Poisson-distributed number of children with parameter $2$: The average number of children per person would be $2$ The average number of children per person with children would be $\frac{2}{1-e^{-2}} \approx 2.313$ The average sibling group size for each individual (counting their brothers and sisters and themselves) would be $3$ Real demographic and survey numbers produce different numbers but similar patterns The apparent paradox is that the average size of individuals' sibling groups is larger than the average number of children per family; with stable population dynamics, people tend to have fewer children on average than their parents did The explanation is whether the average is being taken over parents and families or over siblings: there are different weightings being applied to large families. In your example there is a difference between weighting by individuals or by purchases; your conditional averages are pushed up by fact you condition on a particular purchase being made.
Average value paradox - What is this called? I would call this the family size paradox or something similar Suppose, for a simple example, everybody had one partner and a Poisson-distributed number of children with parameter $2$: The average n
11,879
Average value paradox - What is this called?
The other answers are overthinking what's going on. Suppose there is one product and two customers. One bought the product (once) and one didn't. The average number of products bought is 0.5, but if you look only at the customer who bought the product, the average rises to 1. This doesn't seem like a paradox or counterintuitive to me; conditioning on buying a product will generally raise the average number of products bought.
Average value paradox - What is this called?
The other answers are overthinking what's going on. Suppose there is one product and two customers. One bought the product (once) and one didn't. The average number of products bought is 0.5, but i
Average value paradox - What is this called? The other answers are overthinking what's going on. Suppose there is one product and two customers. One bought the product (once) and one didn't. The average number of products bought is 0.5, but if you look only at the customer who bought the product, the average rises to 1. This doesn't seem like a paradox or counterintuitive to me; conditioning on buying a product will generally raise the average number of products bought.
Average value paradox - What is this called? The other answers are overthinking what's going on. Suppose there is one product and two customers. One bought the product (once) and one didn't. The average number of products bought is 0.5, but i
11,880
Average value paradox - What is this called?
Is this not merely the "average of averages" confusion (e.g. previous stackexchange question) in disguise? Your temptation appears to be that the subsample averages should end up averaging to the population average, but this will rarely happen. In the classical "average of averages", someone finds the average of N mutually exclusive subsets, and then is flabbergasted that these values do not average to the population average. The only way this average of averages works out is if your non-overlapping subsets have the same size. Otherwise, you need to take a weighted average. Your problem is made more complex than this traditional average of averages confusion by having overlapping subsets, but it appears to me to just be this classic mistake with a twist. With overlapping subsets, it is even harder to end up with subsample averages that average to the population average. In your example, since users who appear in multiple subsamples (and therefore have bought many things) will increase these averages. Basically you're counting each big-spender multiple times, while the frugal people that only buy one item are only encountered once, so you're biased to larger values. This is why your particular subsets have above average values, but I think this is still just the "average of averages" problem. You can also construct all kinds of other subsets from your data where the subsample averages take on different values. For example, let's take subsets somewhat similar to your subsets. If you take the subset of people who did not buy A, you get 7/5=1.4 items on average. With the subset that did not buy B, you also get 1.4 items on average. Those who did not buy C, bought 1.5 items on average. These are all below the population average of 1.6 items/customer. Given the right dataset and the right collection of subsets, you could end up with overlapping subsets whose averages average to the population average; however, this would be uncommon in normal applications. Is it just me, or does the word average now seem weird after so many repetitions... Hope my answer was helpful, and sorry if I ruined the word average for you!
Average value paradox - What is this called?
Is this not merely the "average of averages" confusion (e.g. previous stackexchange question) in disguise? Your temptation appears to be that the subsample averages should end up averaging to the popu
Average value paradox - What is this called? Is this not merely the "average of averages" confusion (e.g. previous stackexchange question) in disguise? Your temptation appears to be that the subsample averages should end up averaging to the population average, but this will rarely happen. In the classical "average of averages", someone finds the average of N mutually exclusive subsets, and then is flabbergasted that these values do not average to the population average. The only way this average of averages works out is if your non-overlapping subsets have the same size. Otherwise, you need to take a weighted average. Your problem is made more complex than this traditional average of averages confusion by having overlapping subsets, but it appears to me to just be this classic mistake with a twist. With overlapping subsets, it is even harder to end up with subsample averages that average to the population average. In your example, since users who appear in multiple subsamples (and therefore have bought many things) will increase these averages. Basically you're counting each big-spender multiple times, while the frugal people that only buy one item are only encountered once, so you're biased to larger values. This is why your particular subsets have above average values, but I think this is still just the "average of averages" problem. You can also construct all kinds of other subsets from your data where the subsample averages take on different values. For example, let's take subsets somewhat similar to your subsets. If you take the subset of people who did not buy A, you get 7/5=1.4 items on average. With the subset that did not buy B, you also get 1.4 items on average. Those who did not buy C, bought 1.5 items on average. These are all below the population average of 1.6 items/customer. Given the right dataset and the right collection of subsets, you could end up with overlapping subsets whose averages average to the population average; however, this would be uncommon in normal applications. Is it just me, or does the word average now seem weird after so many repetitions... Hope my answer was helpful, and sorry if I ruined the word average for you!
Average value paradox - What is this called? Is this not merely the "average of averages" confusion (e.g. previous stackexchange question) in disguise? Your temptation appears to be that the subsample averages should end up averaging to the popu
11,881
Average value paradox - What is this called?
Since the issue is "I understand it but need to explain this to marketing", OP seems concerned with how a layman will interpret these facts - (not whether the facts are true, or how to show that they are). The question references 10 product categories, (A-J), so how about this example: [in meeting with marketing group] OP: So, as you can see here, customers who buy A, B, and C, are all more valuable than average. Layman: Wait?! How can everyone be higher than average? OP: Good question. This slide focuses on customers of A, B, and C, but there are other, low performing, groups not shown. For example, customers of categories D and G are each worth about half of average. This should quell everyone's internal bs-alarm about 'everything is above average'.
Average value paradox - What is this called?
Since the issue is "I understand it but need to explain this to marketing", OP seems concerned with how a layman will interpret these facts - (not whether the facts are true, or how to show that they
Average value paradox - What is this called? Since the issue is "I understand it but need to explain this to marketing", OP seems concerned with how a layman will interpret these facts - (not whether the facts are true, or how to show that they are). The question references 10 product categories, (A-J), so how about this example: [in meeting with marketing group] OP: So, as you can see here, customers who buy A, B, and C, are all more valuable than average. Layman: Wait?! How can everyone be higher than average? OP: Good question. This slide focuses on customers of A, B, and C, but there are other, low performing, groups not shown. For example, customers of categories D and G are each worth about half of average. This should quell everyone's internal bs-alarm about 'everything is above average'.
Average value paradox - What is this called? Since the issue is "I understand it but need to explain this to marketing", OP seems concerned with how a layman will interpret these facts - (not whether the facts are true, or how to show that they
11,882
Average value paradox - What is this called?
Ignore the other answers here. This actually is not a paradox at all. The actual issue at hand here which everyone seems to be ignoring is that you are mistaking which probability you are actually looking at. There are in fact two completely different averages and statistics at play here which both have there own uses and interpretations in your proposed example (marketing)! First off there is the average number of products bought per customer. So on average, one customer buys 1.6 items. Of course, a customer cannot but 0.6 of the product (assuming it isn't something like rice or grain that has a continuous measurement associated with it). Secondly, there is the average number of customers that buy a particular product. Sounds weird right? So on average a product has 5.33333333... customers buying it. This is different however. What we're describing here is not the number of products bought (there's only three of them!) but rather the number of people actually purchasing said product. Think of the two values this way: What would these two values represent if there was only one customer or only one product? After all, the average of a single data point is just that given data point. Or better yet, think of the chart as if it were giving you dollar amounts spent to buy the product. Obviously the average amount spent by an individual customer will be far less than the amount of money made on average by a product supplied by a major corporation (or even just a small business). I'm sure you can think of good ways to use both values when discussing the well-being of the company. When you go to explain this to the marketing staff, explain it to them just like I have said. It isn't a paradox. It's just a completely different statistic. The only issue here was noticing that there was in fact, two different ways to read the chart (i.e. number of people buying per product vs. number of products bought per person). tl;dr the first thing you described is the average amount an individual customer is willing to spend buying your products. The second is the average demand for a given product by the public. I'm sure you can see now why both are most certainly not the same thing. Comparing them as such will just give you garbage information. EDIT It would appear the question is actually asking about the average money spent by customers who buy some product a,b, or c. Alright. This is actually just an error in calculations. I wouldn't call this a paradox. It's really just a subtle flub. Look at your columns. There are people that are shared between columns. Let's assume you did a proper weighted average. You are still adding up people twice. This means that the average will contain extra people with a value greater than or equal to 2. Now what was your average? It was 1.6! In essence your average looks like this: $\frac {\sum_{i = 0}^{n} valueOfPerson_i*valueOfPerson_i} {n}$ That is definitely not the right formula. It is a weighted average though assuming mutual exclusiveness that is how you would adjust to get a true average in your situation. $\frac {\sum_{i = 0}^{n} numberOfPeopleBuying_i*averageSpentByPersonBuying_i} {n}$ Either way you'll get a messed up average. One mistake was ignoring the need for a weighted average as one category has a greater "weight" in terms of the average. It's like density. One value is denser in people represents. The other issue is duplicate adding which will distort the average. I don't call either of these "paradoxes" though. Once I saw what you were doing it seemed obvious to me why that wouldn't work. The weighted average is somewhat self-explanatory for its need and I think now that you see that you added values multiple times... that cannot work. You basically took the average of the squares of their values.
Average value paradox - What is this called?
Ignore the other answers here. This actually is not a paradox at all. The actual issue at hand here which everyone seems to be ignoring is that you are mistaking which probability you are actually loo
Average value paradox - What is this called? Ignore the other answers here. This actually is not a paradox at all. The actual issue at hand here which everyone seems to be ignoring is that you are mistaking which probability you are actually looking at. There are in fact two completely different averages and statistics at play here which both have there own uses and interpretations in your proposed example (marketing)! First off there is the average number of products bought per customer. So on average, one customer buys 1.6 items. Of course, a customer cannot but 0.6 of the product (assuming it isn't something like rice or grain that has a continuous measurement associated with it). Secondly, there is the average number of customers that buy a particular product. Sounds weird right? So on average a product has 5.33333333... customers buying it. This is different however. What we're describing here is not the number of products bought (there's only three of them!) but rather the number of people actually purchasing said product. Think of the two values this way: What would these two values represent if there was only one customer or only one product? After all, the average of a single data point is just that given data point. Or better yet, think of the chart as if it were giving you dollar amounts spent to buy the product. Obviously the average amount spent by an individual customer will be far less than the amount of money made on average by a product supplied by a major corporation (or even just a small business). I'm sure you can think of good ways to use both values when discussing the well-being of the company. When you go to explain this to the marketing staff, explain it to them just like I have said. It isn't a paradox. It's just a completely different statistic. The only issue here was noticing that there was in fact, two different ways to read the chart (i.e. number of people buying per product vs. number of products bought per person). tl;dr the first thing you described is the average amount an individual customer is willing to spend buying your products. The second is the average demand for a given product by the public. I'm sure you can see now why both are most certainly not the same thing. Comparing them as such will just give you garbage information. EDIT It would appear the question is actually asking about the average money spent by customers who buy some product a,b, or c. Alright. This is actually just an error in calculations. I wouldn't call this a paradox. It's really just a subtle flub. Look at your columns. There are people that are shared between columns. Let's assume you did a proper weighted average. You are still adding up people twice. This means that the average will contain extra people with a value greater than or equal to 2. Now what was your average? It was 1.6! In essence your average looks like this: $\frac {\sum_{i = 0}^{n} valueOfPerson_i*valueOfPerson_i} {n}$ That is definitely not the right formula. It is a weighted average though assuming mutual exclusiveness that is how you would adjust to get a true average in your situation. $\frac {\sum_{i = 0}^{n} numberOfPeopleBuying_i*averageSpentByPersonBuying_i} {n}$ Either way you'll get a messed up average. One mistake was ignoring the need for a weighted average as one category has a greater "weight" in terms of the average. It's like density. One value is denser in people represents. The other issue is duplicate adding which will distort the average. I don't call either of these "paradoxes" though. Once I saw what you were doing it seemed obvious to me why that wouldn't work. The weighted average is somewhat self-explanatory for its need and I think now that you see that you added values multiple times... that cannot work. You basically took the average of the squares of their values.
Average value paradox - What is this called? Ignore the other answers here. This actually is not a paradox at all. The actual issue at hand here which everyone seems to be ignoring is that you are mistaking which probability you are actually loo
11,883
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
The approach based on the Cholesky decomposition should work, it is described here and is shown in the answer by Mark L. Stone posted almost at the same time that this answer. Nevertheless, I have sometimes generated draws from the multivariate Normal distribution $N(\vec\mu, \Sigma)$ as follows: $$ Y = Q X + \vec\mu \,, \quad \hbox{with}\quad Q=\Lambda^{1/2}\Phi \,, $$ where $Y$ are the final draws, $X$ are draws from the univariate standard Normal distribution, $\Phi$ is a matrix containing the normalized eigenvectors of the target matrix $\Sigma$ and $\Lambda$ is a diagonal matrix containing the eigenvalues of $\Sigma$ arranged in the same order as the eigenvectors in the columns of $\Phi$. Example in R (sorry I'm not using the same software you used in the question): n <- 10000 corM <- rbind(c(1.0, 0.6, 0.9), c(0.6, 1.0, 0.5), c(0.9, 0.5, 1.0)) set.seed(123) SigmaEV <- eigen(corM) eps <- rnorm(n * ncol(SigmaEV$vectors)) Meps <- matrix(eps, ncol = n, byrow = TRUE) Meps <- SigmaEV$vectors %*% diag(sqrt(SigmaEV$values)) %*% Meps Meps <- t(Meps) # target correlation matrix corM # [,1] [,2] [,3] # [1,] 1.0 0.6 0.9 # [2,] 0.6 1.0 0.5 # [3,] 0.9 0.5 1.0 # correlation matrix for simulated data cor(Meps) # [,1] [,2] [,3] # [1,] 1.0000000 0.6002078 0.8994329 # [2,] 0.6002078 1.0000000 0.5006346 # [3,] 0.8994329 0.5006346 1.0000000 You may be also interested in this post and this post.
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
The approach based on the Cholesky decomposition should work, it is described here and is shown in the answer by Mark L. Stone posted almost at the same time that this answer. Nevertheless, I have so
How to use the Cholesky decomposition, or an alternative, for correlated data simulation The approach based on the Cholesky decomposition should work, it is described here and is shown in the answer by Mark L. Stone posted almost at the same time that this answer. Nevertheless, I have sometimes generated draws from the multivariate Normal distribution $N(\vec\mu, \Sigma)$ as follows: $$ Y = Q X + \vec\mu \,, \quad \hbox{with}\quad Q=\Lambda^{1/2}\Phi \,, $$ where $Y$ are the final draws, $X$ are draws from the univariate standard Normal distribution, $\Phi$ is a matrix containing the normalized eigenvectors of the target matrix $\Sigma$ and $\Lambda$ is a diagonal matrix containing the eigenvalues of $\Sigma$ arranged in the same order as the eigenvectors in the columns of $\Phi$. Example in R (sorry I'm not using the same software you used in the question): n <- 10000 corM <- rbind(c(1.0, 0.6, 0.9), c(0.6, 1.0, 0.5), c(0.9, 0.5, 1.0)) set.seed(123) SigmaEV <- eigen(corM) eps <- rnorm(n * ncol(SigmaEV$vectors)) Meps <- matrix(eps, ncol = n, byrow = TRUE) Meps <- SigmaEV$vectors %*% diag(sqrt(SigmaEV$values)) %*% Meps Meps <- t(Meps) # target correlation matrix corM # [,1] [,2] [,3] # [1,] 1.0 0.6 0.9 # [2,] 0.6 1.0 0.5 # [3,] 0.9 0.5 1.0 # correlation matrix for simulated data cor(Meps) # [,1] [,2] [,3] # [1,] 1.0000000 0.6002078 0.8994329 # [2,] 0.6002078 1.0000000 0.5006346 # [3,] 0.8994329 0.5006346 1.0000000 You may be also interested in this post and this post.
How to use the Cholesky decomposition, or an alternative, for correlated data simulation The approach based on the Cholesky decomposition should work, it is described here and is shown in the answer by Mark L. Stone posted almost at the same time that this answer. Nevertheless, I have so
11,884
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
People would be likely find your error much faster if you explained what you did with words and algebra rather than code (or at least writing it using pseudocode). You appear to be doing the equivalent of this (though possibly transposed): Generate an $n\times k$ matrix of standard normals, $Z$ multiply the columns by $\sigma_i$ and add $\mu_i$ to get nonstandard normals calculate $Y=LX$ to get correlated normals. where $L$ is the left Cholesky factor of your correlation matrix. What you should do is this: Generate an $n\times k$ matrix of standard normals, $Z$ calculate $X=LZ$ to get correlated normals. multiply the columns by $\sigma_i$ and add $\mu_i$ to get nonstandard normals There's many explanations of this algorithm on site. e.g. How to generate correlated random numbers (given means, variances and degree of correlation)? Can I use the Cholesky-method for generating correlated random variables with given mean? This one discusses it directly in terms of the desired covariance matrix, and also gives an algorithm for getting a desired sample covariance: Generating data with a given sample covariance matrix
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
People would be likely find your error much faster if you explained what you did with words and algebra rather than code (or at least writing it using pseudocode). You appear to be doing the equivale
How to use the Cholesky decomposition, or an alternative, for correlated data simulation People would be likely find your error much faster if you explained what you did with words and algebra rather than code (or at least writing it using pseudocode). You appear to be doing the equivalent of this (though possibly transposed): Generate an $n\times k$ matrix of standard normals, $Z$ multiply the columns by $\sigma_i$ and add $\mu_i$ to get nonstandard normals calculate $Y=LX$ to get correlated normals. where $L$ is the left Cholesky factor of your correlation matrix. What you should do is this: Generate an $n\times k$ matrix of standard normals, $Z$ calculate $X=LZ$ to get correlated normals. multiply the columns by $\sigma_i$ and add $\mu_i$ to get nonstandard normals There's many explanations of this algorithm on site. e.g. How to generate correlated random numbers (given means, variances and degree of correlation)? Can I use the Cholesky-method for generating correlated random variables with given mean? This one discusses it directly in terms of the desired covariance matrix, and also gives an algorithm for getting a desired sample covariance: Generating data with a given sample covariance matrix
How to use the Cholesky decomposition, or an alternative, for correlated data simulation People would be likely find your error much faster if you explained what you did with words and algebra rather than code (or at least writing it using pseudocode). You appear to be doing the equivale
11,885
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
There's nothing wrong with the Cholesky factorization. There is an error in your code. See edit below. Here is MATLAB code and results, first for n_obs = 10000 as you have, then for n_obs = 1e8. For simplicity, since it doesn't affect the results, I don't bother with means, i.e., I make them zeros. Note that MATLAB's chol produces an upper triangular Cholesky factor R of the matrix M such that R' * R = M. numpy.linalg.cholesky produces a lower triangular Cholesky factor, so an adjustment vs. my code is needed; but I believe your code is fine in that respect. >> correlation_matrix = [1.0, 0.6, 0.9; 0.6, 1.0, 0.5;0.9, 0.5, 1.0]; >> SD = diag([1 2 3]); >> covariance_matrix = SD*correlation_matrix*SD covariance_matrix = 1.000000000000000 1.200000000000000 2.700000000000000 1.200000000000000 4.000000000000000 3.000000000000000 2.700000000000000 3.000000000000000 9.000000000000000 >> n_obs = 10000; >> Random_sample = randn(n_obs,3)*chol(covariance_matrix); >> disp(corr(Random_sample)) 1.000000000000000 0.599105015695768 0.898395949647890 0.599105015695768 1.000000000000000 0.495147514173305 0.898395949647890 0.495147514173305 1.000000000000000 >> n_obs = 1e8; >> Random_sample = randn(n_obs,3)*chol(covariance_matrix); >> disp(corr(Random_sample)) 1.000000000000000 0.600101477583914 0.899986072541418 0.600101477583914 1.000000000000000 0.500112824962378 0.899986072541418 0.500112824962378 1.000000000000000 Edit: I found your mistake. You incorrectly applied the standard deviation. This is the equivalent of what you did, which is wrong. >> n_obs = 10000; >> Random_sample = randn(n_obs,3)*SD*chol(correlation_matrix); >> disp(corr(Random_sample)) 1.000000000000000 0.336292731308138 0.562331469857830 0.336292731308138 1.000000000000000 0.131270077244625 0.562331469857830 0.131270077244625 1.000000000000000 >> n_obs=1e8; >> Random_sample = randn(n_obs,3)*SD*chol(correlation_matrix); >> disp(corr(Random_sample)) 1.000000000000000 0.351254525742470 0.568291702131030 0.351254525742470 1.000000000000000 0.140443281045496 0.568291702131030 0.140443281045496 1.000000000000000
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
There's nothing wrong with the Cholesky factorization. There is an error in your code. See edit below. Here is MATLAB code and results, first for n_obs = 10000 as you have, then for n_obs = 1e8. For s
How to use the Cholesky decomposition, or an alternative, for correlated data simulation There's nothing wrong with the Cholesky factorization. There is an error in your code. See edit below. Here is MATLAB code and results, first for n_obs = 10000 as you have, then for n_obs = 1e8. For simplicity, since it doesn't affect the results, I don't bother with means, i.e., I make them zeros. Note that MATLAB's chol produces an upper triangular Cholesky factor R of the matrix M such that R' * R = M. numpy.linalg.cholesky produces a lower triangular Cholesky factor, so an adjustment vs. my code is needed; but I believe your code is fine in that respect. >> correlation_matrix = [1.0, 0.6, 0.9; 0.6, 1.0, 0.5;0.9, 0.5, 1.0]; >> SD = diag([1 2 3]); >> covariance_matrix = SD*correlation_matrix*SD covariance_matrix = 1.000000000000000 1.200000000000000 2.700000000000000 1.200000000000000 4.000000000000000 3.000000000000000 2.700000000000000 3.000000000000000 9.000000000000000 >> n_obs = 10000; >> Random_sample = randn(n_obs,3)*chol(covariance_matrix); >> disp(corr(Random_sample)) 1.000000000000000 0.599105015695768 0.898395949647890 0.599105015695768 1.000000000000000 0.495147514173305 0.898395949647890 0.495147514173305 1.000000000000000 >> n_obs = 1e8; >> Random_sample = randn(n_obs,3)*chol(covariance_matrix); >> disp(corr(Random_sample)) 1.000000000000000 0.600101477583914 0.899986072541418 0.600101477583914 1.000000000000000 0.500112824962378 0.899986072541418 0.500112824962378 1.000000000000000 Edit: I found your mistake. You incorrectly applied the standard deviation. This is the equivalent of what you did, which is wrong. >> n_obs = 10000; >> Random_sample = randn(n_obs,3)*SD*chol(correlation_matrix); >> disp(corr(Random_sample)) 1.000000000000000 0.336292731308138 0.562331469857830 0.336292731308138 1.000000000000000 0.131270077244625 0.562331469857830 0.131270077244625 1.000000000000000 >> n_obs=1e8; >> Random_sample = randn(n_obs,3)*SD*chol(correlation_matrix); >> disp(corr(Random_sample)) 1.000000000000000 0.351254525742470 0.568291702131030 0.351254525742470 1.000000000000000 0.140443281045496 0.568291702131030 0.140443281045496 1.000000000000000
How to use the Cholesky decomposition, or an alternative, for correlated data simulation There's nothing wrong with the Cholesky factorization. There is an error in your code. See edit below. Here is MATLAB code and results, first for n_obs = 10000 as you have, then for n_obs = 1e8. For s
11,886
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
CV is not about code, but I was intrigued to see how this would look after all the good answers, and specifically @Mark L. Stone contribution. The actual answer to the question is provided on his post (please credit his post in case of doubt). I'm moving this appended info here to facilitate retrieval of this post in the future. Without playing down any of the other excellent answers, after Mark's answer, this wraps up the issue by correcting the post in the OP. Source IN PYTHON: import numpy as np no_obs = 1000 # Number of observations per column means = [1, 2, 3] # Mean values of each column no_cols = 3 # Number of columns sds = [1, 2, 3] # SD of each column sd = np.diag(sds) # SD in a diagonal matrix for later operations observations = np.random.normal(0, 1, (no_cols, no_obs)) # Rd draws N(0,1) in [3 x 1,000] cor_matrix = np.array([[1.0, 0.6, 0.9], [0.6, 1.0, 0.5], [0.9, 0.5, 1.0]]) # The correlation matrix [3 x 3] cov_matrix = np.dot(sd, np.dot(cor_matrix, sd)) # The covariance matrix Chol = np.linalg.cholesky(cov_matrix) # Cholesky decomposition array([[ 1. , 0. , 0. ], [ 1.2 , 1.6 , 0. ], [ 2.7 , -0.15 , 1.29903811]]) sam_eq_mean = Chol .dot(observations) # Generating random MVN (0, cov_matrix) s = sam_eq_mean.transpose() + means # Adding the means column wise samples = s.transpose() # Transposing back print(np.corrcoef(samples)) # Checking correlation consistency. [[ 1. 0.59167434 0.90182308] [ 0.59167434 1. 0.49279316] [ 0.90182308 0.49279316 1. ]] IN [R]: no_obs = 1000 # Number of observations per column means = 1:3 # Mean values of each column no_cols = 3 # Number of columns sds = 1:3 # SD of each column sd = diag(sds) # SD in a diagonal matrix for later operations observations = matrix(rnorm(no_cols * no_obs), nrow = no_cols) # Rd draws N(0,1) cor_matrix = matrix(c(1.0, 0.6, 0.9, 0.6, 1.0, 0.5, 0.9, 0.5, 1.0), byrow = T, nrow = 3) # cor matrix [3 x 3] cov_matrix = sd %*% cor_matrix %*% sd # The covariance matrix Chol = chol(cov_matrix) # Cholesky decomposition [,1] [,2] [,3] [1,] 1 1.2 2.700000 [2,] 0 1.6 -0.150000 [3,] 0 0.0 1.299038 sam_eq_mean = t(observations) %*% Chol # Generating random MVN (0, cov_matrix) samples = t(sam_eq_mean) + means cor(t(samples)) [,1] [,2] [,3] [1,] 1.0000000 0.6071067 0.8857339 [2,] 0.6071067 1.0000000 0.4655579 [3,] 0.8857339 0.4655579 1.0000000 colMeans(t(samples)) [1] 1.035056 2.099352 3.065797 apply(t(samples), 2, sd) [1] 0.9543873 1.9788250 2.8903964
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
CV is not about code, but I was intrigued to see how this would look after all the good answers, and specifically @Mark L. Stone contribution. The actual answer to the question is provided on his post
How to use the Cholesky decomposition, or an alternative, for correlated data simulation CV is not about code, but I was intrigued to see how this would look after all the good answers, and specifically @Mark L. Stone contribution. The actual answer to the question is provided on his post (please credit his post in case of doubt). I'm moving this appended info here to facilitate retrieval of this post in the future. Without playing down any of the other excellent answers, after Mark's answer, this wraps up the issue by correcting the post in the OP. Source IN PYTHON: import numpy as np no_obs = 1000 # Number of observations per column means = [1, 2, 3] # Mean values of each column no_cols = 3 # Number of columns sds = [1, 2, 3] # SD of each column sd = np.diag(sds) # SD in a diagonal matrix for later operations observations = np.random.normal(0, 1, (no_cols, no_obs)) # Rd draws N(0,1) in [3 x 1,000] cor_matrix = np.array([[1.0, 0.6, 0.9], [0.6, 1.0, 0.5], [0.9, 0.5, 1.0]]) # The correlation matrix [3 x 3] cov_matrix = np.dot(sd, np.dot(cor_matrix, sd)) # The covariance matrix Chol = np.linalg.cholesky(cov_matrix) # Cholesky decomposition array([[ 1. , 0. , 0. ], [ 1.2 , 1.6 , 0. ], [ 2.7 , -0.15 , 1.29903811]]) sam_eq_mean = Chol .dot(observations) # Generating random MVN (0, cov_matrix) s = sam_eq_mean.transpose() + means # Adding the means column wise samples = s.transpose() # Transposing back print(np.corrcoef(samples)) # Checking correlation consistency. [[ 1. 0.59167434 0.90182308] [ 0.59167434 1. 0.49279316] [ 0.90182308 0.49279316 1. ]] IN [R]: no_obs = 1000 # Number of observations per column means = 1:3 # Mean values of each column no_cols = 3 # Number of columns sds = 1:3 # SD of each column sd = diag(sds) # SD in a diagonal matrix for later operations observations = matrix(rnorm(no_cols * no_obs), nrow = no_cols) # Rd draws N(0,1) cor_matrix = matrix(c(1.0, 0.6, 0.9, 0.6, 1.0, 0.5, 0.9, 0.5, 1.0), byrow = T, nrow = 3) # cor matrix [3 x 3] cov_matrix = sd %*% cor_matrix %*% sd # The covariance matrix Chol = chol(cov_matrix) # Cholesky decomposition [,1] [,2] [,3] [1,] 1 1.2 2.700000 [2,] 0 1.6 -0.150000 [3,] 0 0.0 1.299038 sam_eq_mean = t(observations) %*% Chol # Generating random MVN (0, cov_matrix) samples = t(sam_eq_mean) + means cor(t(samples)) [,1] [,2] [,3] [1,] 1.0000000 0.6071067 0.8857339 [2,] 0.6071067 1.0000000 0.4655579 [3,] 0.8857339 0.4655579 1.0000000 colMeans(t(samples)) [1] 1.035056 2.099352 3.065797 apply(t(samples), 2, sd) [1] 0.9543873 1.9788250 2.8903964
How to use the Cholesky decomposition, or an alternative, for correlated data simulation CV is not about code, but I was intrigued to see how this would look after all the good answers, and specifically @Mark L. Stone contribution. The actual answer to the question is provided on his post
11,887
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
As others have already shown: cholesky works. Here a piece of code which is very short and very near to pseudocode: a codepiece in MatMate: Co = {{1.0, 0.6, 0.9}, _ {0.6, 1.0, 0.5}, _ {0.9, 0.5, 1.0}} // make correlation matrix chol = cholesky(co) // do cholesky-decomposition data = chol * unkorrzl(randomn(3,100,0,1)) // dot-multiply cholesky with random- // vectors with mean=0, sdev=1 //(refined by a "decorrelation" //to remove spurious/random correlations) chk = data *' /100 // check the correlation of the data list chk 1.0000 0.6000 0.9000 0.6000 1.0000 0.5000 0.9000 0.5000 1.0000
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
As others have already shown: cholesky works. Here a piece of code which is very short and very near to pseudocode: a codepiece in MatMate: Co = {{1.0, 0.6, 0.9}, _ {0.6, 1.0, 0.5}, _ {0
How to use the Cholesky decomposition, or an alternative, for correlated data simulation As others have already shown: cholesky works. Here a piece of code which is very short and very near to pseudocode: a codepiece in MatMate: Co = {{1.0, 0.6, 0.9}, _ {0.6, 1.0, 0.5}, _ {0.9, 0.5, 1.0}} // make correlation matrix chol = cholesky(co) // do cholesky-decomposition data = chol * unkorrzl(randomn(3,100,0,1)) // dot-multiply cholesky with random- // vectors with mean=0, sdev=1 //(refined by a "decorrelation" //to remove spurious/random correlations) chk = data *' /100 // check the correlation of the data list chk 1.0000 0.6000 0.9000 0.6000 1.0000 0.5000 0.9000 0.5000 1.0000
How to use the Cholesky decomposition, or an alternative, for correlated data simulation As others have already shown: cholesky works. Here a piece of code which is very short and very near to pseudocode: a codepiece in MatMate: Co = {{1.0, 0.6, 0.9}, _ {0.6, 1.0, 0.5}, _ {0
11,888
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
Python code: import numpy as np # desired correlation matrix cor_matrix = np.array([[1.0, 0.6, 0.9], [0.6, 1.0, 0.5], [0.9, 0.5, 1.0]]) L = np.linalg.cholesky(cor_matrix) # build some signals that will result in the desired correlation matrix X = L.dot(np.random.normal(0,1,(3,1000))) # the more the sample (1000) the better # estimate their correlation matrix np.corrcoef(X) array([[1. , 0.58773667, 0.8978625 ], [0.58773667, 1. , 0.47424997], [0.8978625 , 0.47424997, 1. ]]) # Very good approxiamation :)
How to use the Cholesky decomposition, or an alternative, for correlated data simulation
Python code: import numpy as np # desired correlation matrix cor_matrix = np.array([[1.0, 0.6, 0.9], [0.6, 1.0, 0.5], [0.9, 0.5, 1.0]]) L = np.linalg.ch
How to use the Cholesky decomposition, or an alternative, for correlated data simulation Python code: import numpy as np # desired correlation matrix cor_matrix = np.array([[1.0, 0.6, 0.9], [0.6, 1.0, 0.5], [0.9, 0.5, 1.0]]) L = np.linalg.cholesky(cor_matrix) # build some signals that will result in the desired correlation matrix X = L.dot(np.random.normal(0,1,(3,1000))) # the more the sample (1000) the better # estimate their correlation matrix np.corrcoef(X) array([[1. , 0.58773667, 0.8978625 ], [0.58773667, 1. , 0.47424997], [0.8978625 , 0.47424997, 1. ]]) # Very good approxiamation :)
How to use the Cholesky decomposition, or an alternative, for correlated data simulation Python code: import numpy as np # desired correlation matrix cor_matrix = np.array([[1.0, 0.6, 0.9], [0.6, 1.0, 0.5], [0.9, 0.5, 1.0]]) L = np.linalg.ch
11,889
Time series for count data, with counts < 20
To assess the historical trend, I'd use a gam with trend and seasonal components. For example require(mgcv) require(forecast) x <- ts(rpois(100,1+sin(seq(0,3*pi,l=100))),f=12) tt <- 1:100 season <- seasonaldummy(x) fit <- gam(x ~ s(tt,k=5) + season, family="poisson") plot(fit) Then summary(fit) will give you a test of significance of the change in trend and the plot will give you some confidence intervals. The assumptions here are that the observations are independent and the conditional distribution is Poisson. Because the mean is allowed to change smoothly over time, these are not particularly strong assumptions. To forecast is more difficult as you need to project the trend into the future. If you are willing to accept a linear extrapolation of the trend at the end of the data (which is certainly dodgy but probably ok for a few months), then use fcast <- predict(fit,se.fit=TRUE, newdata=list(tt=101:112,season=seasonaldummyf(x,h=12))) To see the forecasts on the same graph: plot(x,xlim=c(0,10.5)) lines(ts(exp(fcast$fit),f=12,s=112/12),col=2) lines(ts(exp(fcast$fit-2*fcast$se),f=12,s=112/12),col=2,lty=2) lines(ts(exp(fcast$fit+2*fcast$se),f=12,s=112/12),col=2,lty=2) You can spot the unusual months by looking for outliers in the (deviance) residuals of the fit.
Time series for count data, with counts < 20
To assess the historical trend, I'd use a gam with trend and seasonal components. For example require(mgcv) require(forecast) x <- ts(rpois(100,1+sin(seq(0,3*pi,l=100))),f=12) tt <- 1:100 season <- se
Time series for count data, with counts < 20 To assess the historical trend, I'd use a gam with trend and seasonal components. For example require(mgcv) require(forecast) x <- ts(rpois(100,1+sin(seq(0,3*pi,l=100))),f=12) tt <- 1:100 season <- seasonaldummy(x) fit <- gam(x ~ s(tt,k=5) + season, family="poisson") plot(fit) Then summary(fit) will give you a test of significance of the change in trend and the plot will give you some confidence intervals. The assumptions here are that the observations are independent and the conditional distribution is Poisson. Because the mean is allowed to change smoothly over time, these are not particularly strong assumptions. To forecast is more difficult as you need to project the trend into the future. If you are willing to accept a linear extrapolation of the trend at the end of the data (which is certainly dodgy but probably ok for a few months), then use fcast <- predict(fit,se.fit=TRUE, newdata=list(tt=101:112,season=seasonaldummyf(x,h=12))) To see the forecasts on the same graph: plot(x,xlim=c(0,10.5)) lines(ts(exp(fcast$fit),f=12,s=112/12),col=2) lines(ts(exp(fcast$fit-2*fcast$se),f=12,s=112/12),col=2,lty=2) lines(ts(exp(fcast$fit+2*fcast$se),f=12,s=112/12),col=2,lty=2) You can spot the unusual months by looking for outliers in the (deviance) residuals of the fit.
Time series for count data, with counts < 20 To assess the historical trend, I'd use a gam with trend and seasonal components. For example require(mgcv) require(forecast) x <- ts(rpois(100,1+sin(seq(0,3*pi,l=100))),f=12) tt <- 1:100 season <- se
11,890
Time series for count data, with counts < 20
You might want to have a look at strucchange: Testing, monitoring and dating structural changes in (linear) regression models. strucchange features tests/methods from the generalized fluctuation test framework as well as from the F test (Chow test) framework. This includes methods to fit, plot and test fluctuation processes (e.g., CUSUM, MOSUM, recursive/moving estimates) and F statistics, respectively. It is possible to monitor incoming data online using fluctuation processes. Finally, the breakpoints in regression models with structural changes can be estimated together with confidence intervals. Emphasis is always given to methods for visualizing the data." PS. Nice graphics ;)
Time series for count data, with counts < 20
You might want to have a look at strucchange: Testing, monitoring and dating structural changes in (linear) regression models. strucchange features tests/methods from the generalized fluctuation tes
Time series for count data, with counts < 20 You might want to have a look at strucchange: Testing, monitoring and dating structural changes in (linear) regression models. strucchange features tests/methods from the generalized fluctuation test framework as well as from the F test (Chow test) framework. This includes methods to fit, plot and test fluctuation processes (e.g., CUSUM, MOSUM, recursive/moving estimates) and F statistics, respectively. It is possible to monitor incoming data online using fluctuation processes. Finally, the breakpoints in regression models with structural changes can be estimated together with confidence intervals. Emphasis is always given to methods for visualizing the data." PS. Nice graphics ;)
Time series for count data, with counts < 20 You might want to have a look at strucchange: Testing, monitoring and dating structural changes in (linear) regression models. strucchange features tests/methods from the generalized fluctuation tes
11,891
Time series for count data, with counts < 20
Does it really need some advanced model? Based on what I know about TB, in case there is no epidemy the infections are stochastic acts and so the count form month N shouldn't be correlated with count from month N-1. (You can check this assumption with autocorrelation). If so, analyzing just the distribution of monthly counts may be sufficient to decide if some count is significantly higher than normal. On the other hand you can look for correlations with some other variables, like season, travel traffic, or anything that you can imagine that may be correlated. If you would found something like this, it could be then used for some data normalization.
Time series for count data, with counts < 20
Does it really need some advanced model? Based on what I know about TB, in case there is no epidemy the infections are stochastic acts and so the count form month N shouldn't be correlated with count
Time series for count data, with counts < 20 Does it really need some advanced model? Based on what I know about TB, in case there is no epidemy the infections are stochastic acts and so the count form month N shouldn't be correlated with count from month N-1. (You can check this assumption with autocorrelation). If so, analyzing just the distribution of monthly counts may be sufficient to decide if some count is significantly higher than normal. On the other hand you can look for correlations with some other variables, like season, travel traffic, or anything that you can imagine that may be correlated. If you would found something like this, it could be then used for some data normalization.
Time series for count data, with counts < 20 Does it really need some advanced model? Based on what I know about TB, in case there is no epidemy the infections are stochastic acts and so the count form month N shouldn't be correlated with count
11,892
Time series for count data, with counts < 20
You may try to model your data using a Dynamic Generalized Linear Model (DGLM). In R, you can fit this kind of models using packages sspir and KFAS. In a sense, this is similar to the gam approach suggested by Rob, except that instead of assuming that the log mean of the Poisson observations be a smooth function of time, it assumes that it follows a stochastic dynamics.
Time series for count data, with counts < 20
You may try to model your data using a Dynamic Generalized Linear Model (DGLM). In R, you can fit this kind of models using packages sspir and KFAS. In a sense, this is similar to the gam approach sug
Time series for count data, with counts < 20 You may try to model your data using a Dynamic Generalized Linear Model (DGLM). In R, you can fit this kind of models using packages sspir and KFAS. In a sense, this is similar to the gam approach suggested by Rob, except that instead of assuming that the log mean of the Poisson observations be a smooth function of time, it assumes that it follows a stochastic dynamics.
Time series for count data, with counts < 20 You may try to model your data using a Dynamic Generalized Linear Model (DGLM). In R, you can fit this kind of models using packages sspir and KFAS. In a sense, this is similar to the gam approach sug
11,893
Time series for count data, with counts < 20
Often, disease data like this is performed with a generalized linear model, as its not necessarily a great application of time series analysis - the months often aren't all that correlated with each other. If I were given this data, here's what I would do (and indeed, have done with data similar to it): Create a "time" variable that's more accurately described as "Months since 1/1/2000" if I'm eyeballing your data correctly. Then I'd run a general linear model in R using the Poisson distribution (or Negative Binomial) and a log link with roughly the following form: log(Counts) = b0 + b1*t + b2*(t^2) + b3*cos(2pi*w*t) + b4*sin(2pi*w*t) Where t is the time described above, and w is 1/365 for a yearly disease like flu. Generally its 1/n, where n is the length of your disease's cycle. I don't know offhand what it is for TB. The two time trends will show you - outside normal seasonal variation - if you have meaningful variation over time.
Time series for count data, with counts < 20
Often, disease data like this is performed with a generalized linear model, as its not necessarily a great application of time series analysis - the months often aren't all that correlated with each o
Time series for count data, with counts < 20 Often, disease data like this is performed with a generalized linear model, as its not necessarily a great application of time series analysis - the months often aren't all that correlated with each other. If I were given this data, here's what I would do (and indeed, have done with data similar to it): Create a "time" variable that's more accurately described as "Months since 1/1/2000" if I'm eyeballing your data correctly. Then I'd run a general linear model in R using the Poisson distribution (or Negative Binomial) and a log link with roughly the following form: log(Counts) = b0 + b1*t + b2*(t^2) + b3*cos(2pi*w*t) + b4*sin(2pi*w*t) Where t is the time described above, and w is 1/365 for a yearly disease like flu. Generally its 1/n, where n is the length of your disease's cycle. I don't know offhand what it is for TB. The two time trends will show you - outside normal seasonal variation - if you have meaningful variation over time.
Time series for count data, with counts < 20 Often, disease data like this is performed with a generalized linear model, as its not necessarily a great application of time series analysis - the months often aren't all that correlated with each o
11,894
Time series for count data, with counts < 20
You might consider applying a Tukey Control chart to the data.
Time series for count data, with counts < 20
You might consider applying a Tukey Control chart to the data.
Time series for count data, with counts < 20 You might consider applying a Tukey Control chart to the data.
Time series for count data, with counts < 20 You might consider applying a Tukey Control chart to the data.
11,895
Time series for count data, with counts < 20
I'm going to leave the main question alone, because I think I will get it wrong (although I too analyse data for a healthcare provider, and to be honest, if I had these data, I would just analyse them using standard techniques and hope for the best, they look pretty okay to me). As for R packages, I have found the TSA library and it's accompanying book very useful indeed. The armasubsets command, particularly, I think is a great time saver.
Time series for count data, with counts < 20
I'm going to leave the main question alone, because I think I will get it wrong (although I too analyse data for a healthcare provider, and to be honest, if I had these data, I would just analyse them
Time series for count data, with counts < 20 I'm going to leave the main question alone, because I think I will get it wrong (although I too analyse data for a healthcare provider, and to be honest, if I had these data, I would just analyse them using standard techniques and hope for the best, they look pretty okay to me). As for R packages, I have found the TSA library and it's accompanying book very useful indeed. The armasubsets command, particularly, I think is a great time saver.
Time series for count data, with counts < 20 I'm going to leave the main question alone, because I think I will get it wrong (although I too analyse data for a healthcare provider, and to be honest, if I had these data, I would just analyse them
11,896
Time series for count data, with counts < 20
Escape from traditional enumerative statistics as Deming would suggest and venture into traditional analytical statistics - in this case, control charts. See any books by Donald Wheeler PhD, particularly his "Advanced Topics in SPC" for more info.
Time series for count data, with counts < 20
Escape from traditional enumerative statistics as Deming would suggest and venture into traditional analytical statistics - in this case, control charts. See any books by Donald Wheeler PhD, particul
Time series for count data, with counts < 20 Escape from traditional enumerative statistics as Deming would suggest and venture into traditional analytical statistics - in this case, control charts. See any books by Donald Wheeler PhD, particularly his "Advanced Topics in SPC" for more info.
Time series for count data, with counts < 20 Escape from traditional enumerative statistics as Deming would suggest and venture into traditional analytical statistics - in this case, control charts. See any books by Donald Wheeler PhD, particul
11,897
Time series for count data, with counts < 20
In response to your direct question "How can I test if there's a real change in the process? And if I can identify a decline, how could I use that trend and whatever seasonality there might be to estimate the number of cases we might see in the upcoming months?" Develop a Transfer Function Model ( ARMAX ) that readily explains period-to-period dependency including and seasonal ARIMA structure. Incorporate any Identifiable Level Shifts , Seasonal Pulses, Local Time Trends and PUlses that may have been suggested by empirical/analystical methods like Intervention Detection. IF THIS ROBUST MODEL INCLUDES A FACTOR/SERIES matching up with "declines" Then your prayers have been answerered. In the alternative simply add an hypothesized structure e.g. to test a time trend change at point T1 construct two dummies X1 = 1,1,2,3,,,,,,T and X2 = 0,0,0,0,0,0,0,1,2,3,4,5,.... WHERE THE ZEROES END AT PERIOD T1-1 . The test of the hypothesis of a significant trend change at time period T1 will be assessed using the "t value" for X2 . Edited 9/22/11 Often, disease data like this has monthly effects since weather/temperature is often an unspecified causal . In the omission of the true caudsal series ARIMA models use memory or seasonal dummies as a surrogate. Additionally series like this can have level shifts and/or local time trends reflecting structural change over time. Exploiting the autoregressive structure in the data rather than imposing various artifacts like time and time square and time cubic etc. have been found to be quite useful and less presumptive and ad hoc. Care should also be taken to identify "unusual values" as they can often be useful in suggestng additional cause variables and at a minimum lead to robust estimates of the other model parameters. Finally we have found that the variability/paramaters may vary over times thus these model refinements may be in order.
Time series for count data, with counts < 20
In response to your direct question "How can I test if there's a real change in the process? And if I can identify a decline, how could I use that trend and whatever seasonality there might be to esti
Time series for count data, with counts < 20 In response to your direct question "How can I test if there's a real change in the process? And if I can identify a decline, how could I use that trend and whatever seasonality there might be to estimate the number of cases we might see in the upcoming months?" Develop a Transfer Function Model ( ARMAX ) that readily explains period-to-period dependency including and seasonal ARIMA structure. Incorporate any Identifiable Level Shifts , Seasonal Pulses, Local Time Trends and PUlses that may have been suggested by empirical/analystical methods like Intervention Detection. IF THIS ROBUST MODEL INCLUDES A FACTOR/SERIES matching up with "declines" Then your prayers have been answerered. In the alternative simply add an hypothesized structure e.g. to test a time trend change at point T1 construct two dummies X1 = 1,1,2,3,,,,,,T and X2 = 0,0,0,0,0,0,0,1,2,3,4,5,.... WHERE THE ZEROES END AT PERIOD T1-1 . The test of the hypothesis of a significant trend change at time period T1 will be assessed using the "t value" for X2 . Edited 9/22/11 Often, disease data like this has monthly effects since weather/temperature is often an unspecified causal . In the omission of the true caudsal series ARIMA models use memory or seasonal dummies as a surrogate. Additionally series like this can have level shifts and/or local time trends reflecting structural change over time. Exploiting the autoregressive structure in the data rather than imposing various artifacts like time and time square and time cubic etc. have been found to be quite useful and less presumptive and ad hoc. Care should also be taken to identify "unusual values" as they can often be useful in suggestng additional cause variables and at a minimum lead to robust estimates of the other model parameters. Finally we have found that the variability/paramaters may vary over times thus these model refinements may be in order.
Time series for count data, with counts < 20 In response to your direct question "How can I test if there's a real change in the process? And if I can identify a decline, how could I use that trend and whatever seasonality there might be to esti
11,898
Difference between selecting features based on "F regression" and based on $R^2$ values?
TL:DR There won't be a difference if F-regression just computes the F statistic and pick the best features. There might be a difference in the ranking, assuming F-regression does the following: Start with a constant model, $M_0$ Try all models $M_1$ consisting of just one feature and pick the best according to the F statistic Try all models $M_2$ consisting of $M_1$ plus one other feature and pick the best ... As the correlation will not be the same at each iteration. But you can still get this ranking by just computing the correlation at each step, so why does F-regression takes an additional step? It does two things: Feature selection: If you want to select the $k$ best features in a Machine learning pipeline, where you only care about accuracy and have measures to adjust under/overfitting, you might only care about the ranking and the additional computation is not useful. Test for significance: If you are trying to understand the effect of some variables on an output in a study, you might want to build a linear model, and only include the variables that are significantly improving your model, with respect to some $p$-value. Here, F-regression comes in handy. What is a F-test A F-test (Wikipedia) is a way of comparing the significance of the improvement of a model, with respect to the addition of new variables. You can use it when have a basic model $M_0$ and a more complicated model $M_1$, which contains all variables from $M_0$ and some more. The F-test tells you if $M_1$ is significantly better than $M_0$, with respect to a $p$-value. To do so, it uses the residual sum of squares as an error measure, and compares the reduction in error with the number of variables added, and the number of observation (more details on Wikipedia). Adding variables, even if they are completely random, is expected to always help the model achieve lower error by adding another dimension. The goal is to figure out if the new features are really helpful or if they are random numbers but still help the model because they add a dimension. What does f_regression do Note that I am not familiar with the Scikit learn implementation, but lets try to figure out what f_regression is doing. The documentation states that the procedure is sequential. If the word sequential means the same as in other statistical packages, such as Matlab Sequential Feature Selection, here is how I would expect it to proceed: Start with a constant model, $M_0$ Try all models $M_1$ consisting of just one feature and pick the best according to the F statistic Try all models $M_2$ consisting of $M_1$ plus one other feature and pick the best ... For now, I think it is a close enough approximation to answer your question; is there a difference between the ranking of f_regression and ranking by correlation. If you were to start with constant model $M_0$ and try to find the best model with only one feature, $M_1$, you will select the same feature whether you use f_regression or your correlation based approach, as they are both a measure of linear dependency. But if you were to go from $M_0$ to $M_1$ and then to $M_2$, there would be a difference in your scoring. Assume you have three features, $x_1, x_2, x_3$, where both $x_1$ and $x_2$ are highly correlated with the output $y$, but also highly correlated with each other, while $x_3$ is only midly correlated with $y$. Your method of scoring would assign the best scores to $x_1$ and $x_2$, but the sequential method might not. In the first round, it would pick the best feature, say $x_1$, to create $M_1$. Then, it would evaluate both $x_2$ and $x_3$ for $M_2$. As $x_2$ is highly correlated with an already selected feature, most of the information it contains is already incorporated into the model, and therefore the procedure might select $x_3$. While it is less correlated to $y$, it is more correlated to the residuals, the part that $x_1$ does not already explain, than $x_2$. This is how the two procedure you propose are different. You can still emulate the same effect with your idea by building your model sequentially and measuring the difference in gain for each additional feature instead of comparing them to the constant model $M_0$ as you are doing now. The result would not be different from the f_regression results. The reason for this function to exists is to provide this sequential feature selection, and additionnaly converts the result to an F measure which you can use to judge significance. The goal of the F-test is to provide significance level. If you want to make sure the features your are including are significant with respect to your $p$-value, you use an F-test. If you just want to include the $k$ best features, you can use the correlation only. Additional material: Here is an introduction to the F-test you might find helpful
Difference between selecting features based on "F regression" and based on $R^2$ values?
TL:DR There won't be a difference if F-regression just computes the F statistic and pick the best features. There might be a difference in the ranking, assuming F-regression does the following: Start
Difference between selecting features based on "F regression" and based on $R^2$ values? TL:DR There won't be a difference if F-regression just computes the F statistic and pick the best features. There might be a difference in the ranking, assuming F-regression does the following: Start with a constant model, $M_0$ Try all models $M_1$ consisting of just one feature and pick the best according to the F statistic Try all models $M_2$ consisting of $M_1$ plus one other feature and pick the best ... As the correlation will not be the same at each iteration. But you can still get this ranking by just computing the correlation at each step, so why does F-regression takes an additional step? It does two things: Feature selection: If you want to select the $k$ best features in a Machine learning pipeline, where you only care about accuracy and have measures to adjust under/overfitting, you might only care about the ranking and the additional computation is not useful. Test for significance: If you are trying to understand the effect of some variables on an output in a study, you might want to build a linear model, and only include the variables that are significantly improving your model, with respect to some $p$-value. Here, F-regression comes in handy. What is a F-test A F-test (Wikipedia) is a way of comparing the significance of the improvement of a model, with respect to the addition of new variables. You can use it when have a basic model $M_0$ and a more complicated model $M_1$, which contains all variables from $M_0$ and some more. The F-test tells you if $M_1$ is significantly better than $M_0$, with respect to a $p$-value. To do so, it uses the residual sum of squares as an error measure, and compares the reduction in error with the number of variables added, and the number of observation (more details on Wikipedia). Adding variables, even if they are completely random, is expected to always help the model achieve lower error by adding another dimension. The goal is to figure out if the new features are really helpful or if they are random numbers but still help the model because they add a dimension. What does f_regression do Note that I am not familiar with the Scikit learn implementation, but lets try to figure out what f_regression is doing. The documentation states that the procedure is sequential. If the word sequential means the same as in other statistical packages, such as Matlab Sequential Feature Selection, here is how I would expect it to proceed: Start with a constant model, $M_0$ Try all models $M_1$ consisting of just one feature and pick the best according to the F statistic Try all models $M_2$ consisting of $M_1$ plus one other feature and pick the best ... For now, I think it is a close enough approximation to answer your question; is there a difference between the ranking of f_regression and ranking by correlation. If you were to start with constant model $M_0$ and try to find the best model with only one feature, $M_1$, you will select the same feature whether you use f_regression or your correlation based approach, as they are both a measure of linear dependency. But if you were to go from $M_0$ to $M_1$ and then to $M_2$, there would be a difference in your scoring. Assume you have three features, $x_1, x_2, x_3$, where both $x_1$ and $x_2$ are highly correlated with the output $y$, but also highly correlated with each other, while $x_3$ is only midly correlated with $y$. Your method of scoring would assign the best scores to $x_1$ and $x_2$, but the sequential method might not. In the first round, it would pick the best feature, say $x_1$, to create $M_1$. Then, it would evaluate both $x_2$ and $x_3$ for $M_2$. As $x_2$ is highly correlated with an already selected feature, most of the information it contains is already incorporated into the model, and therefore the procedure might select $x_3$. While it is less correlated to $y$, it is more correlated to the residuals, the part that $x_1$ does not already explain, than $x_2$. This is how the two procedure you propose are different. You can still emulate the same effect with your idea by building your model sequentially and measuring the difference in gain for each additional feature instead of comparing them to the constant model $M_0$ as you are doing now. The result would not be different from the f_regression results. The reason for this function to exists is to provide this sequential feature selection, and additionnaly converts the result to an F measure which you can use to judge significance. The goal of the F-test is to provide significance level. If you want to make sure the features your are including are significant with respect to your $p$-value, you use an F-test. If you just want to include the $k$ best features, you can use the correlation only. Additional material: Here is an introduction to the F-test you might find helpful
Difference between selecting features based on "F regression" and based on $R^2$ values? TL:DR There won't be a difference if F-regression just computes the F statistic and pick the best features. There might be a difference in the ranking, assuming F-regression does the following: Start
11,899
Difference between selecting features based on "F regression" and based on $R^2$ values?
I spent some time looking through the Scikit source code in order to understand what f_regression does, and I would like to post my observations here. The original question was: Q: Does SelectKBest(f_regression, k = 4) produce the same result as using LinearRegression(fit_intercept=True) and choosing the first 4 features with the highest scores? The answer is yes. Moreover, the relative ordering given by the scores is the same. Here is what f_regression does, on input matrix $X$ and array $y$. For every feature $X[:, i]$ it computes the correlation with $y$: $$ \rho_i = \frac{(X[:, i] - mean(X[:, i])) * (y - mean(y))}{std(X[:, i]) * std(y)}. $$ Then it computes the F-statistic $$ F_i = \frac{\rho_i^2}{1 - \rho_i^2}*(n-2), $$ where $n = len(y)$, the number of samples (there is a slight difference if parameter center is False; then it multiplies with $n-1$). These F-values are then returned, together with the associated p-values. So the result is a tuple (F-values, p-values). Then SelectKBest takes the first component of this tuple (these will be the scores), sorts it, and picks the first $k$ features of $X$ with the highest scores. There is no sequential application or anything, and the p-values are not used either. Now let $R_i^2$ be the score computed by LinearRegression for $X[:, i]$ and $y$. This is a regression on a single variable, so $R_i^2 = \rho_i^2$. Then $$ R_i^2 < R_j^2 \Leftrightarrow \frac{\rho_i^2}{1 - \rho_i^2} < \frac{\rho_j^2}{1 - \rho_j^2} \Leftrightarrow F_i < F_j. $$ Hence there is no difference between f_regression and LinearRegression. Although one could construct a model sequentially, this is not what SelectKBest does.
Difference between selecting features based on "F regression" and based on $R^2$ values?
I spent some time looking through the Scikit source code in order to understand what f_regression does, and I would like to post my observations here. The original question was: Q: Does SelectKBest(f_
Difference between selecting features based on "F regression" and based on $R^2$ values? I spent some time looking through the Scikit source code in order to understand what f_regression does, and I would like to post my observations here. The original question was: Q: Does SelectKBest(f_regression, k = 4) produce the same result as using LinearRegression(fit_intercept=True) and choosing the first 4 features with the highest scores? The answer is yes. Moreover, the relative ordering given by the scores is the same. Here is what f_regression does, on input matrix $X$ and array $y$. For every feature $X[:, i]$ it computes the correlation with $y$: $$ \rho_i = \frac{(X[:, i] - mean(X[:, i])) * (y - mean(y))}{std(X[:, i]) * std(y)}. $$ Then it computes the F-statistic $$ F_i = \frac{\rho_i^2}{1 - \rho_i^2}*(n-2), $$ where $n = len(y)$, the number of samples (there is a slight difference if parameter center is False; then it multiplies with $n-1$). These F-values are then returned, together with the associated p-values. So the result is a tuple (F-values, p-values). Then SelectKBest takes the first component of this tuple (these will be the scores), sorts it, and picks the first $k$ features of $X$ with the highest scores. There is no sequential application or anything, and the p-values are not used either. Now let $R_i^2$ be the score computed by LinearRegression for $X[:, i]$ and $y$. This is a regression on a single variable, so $R_i^2 = \rho_i^2$. Then $$ R_i^2 < R_j^2 \Leftrightarrow \frac{\rho_i^2}{1 - \rho_i^2} < \frac{\rho_j^2}{1 - \rho_j^2} \Leftrightarrow F_i < F_j. $$ Hence there is no difference between f_regression and LinearRegression. Although one could construct a model sequentially, this is not what SelectKBest does.
Difference between selecting features based on "F regression" and based on $R^2$ values? I spent some time looking through the Scikit source code in order to understand what f_regression does, and I would like to post my observations here. The original question was: Q: Does SelectKBest(f_
11,900
Splitting Time Series Data into Train/Test/Validation Sets
You should use a split based on time to avoid the look-ahead bias. Train/validation/test in this order by time. The test set should be the most recent part of data. You need to simulate a situation in a production environment, where after training a model you evaluate data coming after the time of creation of the model. The random sampling you use for validation and training is therefore not good idea.
Splitting Time Series Data into Train/Test/Validation Sets
You should use a split based on time to avoid the look-ahead bias. Train/validation/test in this order by time. The test set should be the most recent part of data. You need to simulate a situation in
Splitting Time Series Data into Train/Test/Validation Sets You should use a split based on time to avoid the look-ahead bias. Train/validation/test in this order by time. The test set should be the most recent part of data. You need to simulate a situation in a production environment, where after training a model you evaluate data coming after the time of creation of the model. The random sampling you use for validation and training is therefore not good idea.
Splitting Time Series Data into Train/Test/Validation Sets You should use a split based on time to avoid the look-ahead bias. Train/validation/test in this order by time. The test set should be the most recent part of data. You need to simulate a situation in